blob: 0718b9706038e02cd2b2d1db583d7ea13e491efe [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 Labath144119b2016-04-04 14:39:12 +0000397 llvm::StringRef resolve_path_ref(resolved.c_str());
398 size_t dir_end = ParentPathEnd(resolve_path_ref, syntax);
399 if (dir_end == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 {
Pavel Labath144119b2016-04-04 14:39:12 +0000401 m_filename.SetString(resolve_path_ref);
402 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403 }
Pavel Labath144119b2016-04-04 14:39:12 +0000404
405 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
406
407 size_t filename_begin = dir_end;
408 size_t root_dir_start = RootDirStart(resolve_path_ref, syntax);
409 while (filename_begin != llvm::StringRef::npos && filename_begin < resolve_path_ref.size() &&
410 filename_begin != root_dir_start && IsPathSeparator(resolve_path_ref[filename_begin], syntax))
411 ++filename_begin;
412 m_filename.SetString((filename_begin == llvm::StringRef::npos || filename_begin >= resolve_path_ref.size())
413 ? "."
414 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415}
416
Chaoren Lind3173f32015-05-29 19:52:29 +0000417void
Chaoren Lin44145d72015-05-29 19:52:37 +0000418FileSpec::SetFile(const char *pathname, bool resolve, ArchSpec arch)
419{
420 return SetFile(pathname, resolve,
421 arch.GetTriple().isOSWindows()
422 ? ePathSyntaxWindows
423 : ePathSyntaxPosix);
424}
425
426void
Chaoren Lind3173f32015-05-29 19:52:29 +0000427FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
428{
429 return SetFile(pathname.c_str(), resolve, syntax);
430}
431
Chaoren Lin44145d72015-05-29 19:52:37 +0000432void
433FileSpec::SetFile(const std::string &pathname, bool resolve, ArchSpec arch)
434{
435 return SetFile(pathname.c_str(), resolve, arch);
436}
437
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438//----------------------------------------------------------------------
439// Convert to pointer operator. This allows code to check any FileSpec
440// objects to see if they contain anything valid using code such as:
441//
442// if (file_spec)
443// {}
444//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000445FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000446{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000447 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448}
449
450//----------------------------------------------------------------------
451// Logical NOT operator. This allows code to check any FileSpec
452// objects to see if they are invalid using code such as:
453//
454// if (!file_spec)
455// {}
456//----------------------------------------------------------------------
457bool
458FileSpec::operator!() const
459{
460 return !m_directory && !m_filename;
461}
462
Zachary Turner74e08ca2016-03-02 22:05:52 +0000463bool
464FileSpec::DirectoryEquals(const FileSpec &rhs) const
465{
466 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
467 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
468}
469
470bool
471FileSpec::FileEquals(const FileSpec &rhs) const
472{
473 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
474 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
475}
476
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477//------------------------------------------------------------------
478// Equal to operator
479//------------------------------------------------------------------
480bool
481FileSpec::operator== (const FileSpec& rhs) const
482{
Zachary Turner74e08ca2016-03-02 22:05:52 +0000483 if (!FileEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000484 return false;
Zachary Turner74e08ca2016-03-02 22:05:52 +0000485 if (DirectoryEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000486 return true;
487
488 // TODO: determine if we want to keep this code in here.
489 // The code below was added to handle a case where we were
490 // trying to set a file and line breakpoint and one path
491 // was resolved, and the other not and the directory was
492 // in a mount point that resolved to a more complete path:
493 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
494 // this out...
495 if (IsResolved() && rhs.IsResolved())
Greg Clayton7481c202010-11-08 00:28:40 +0000496 {
Zachary Turner47c03462016-02-24 21:26:47 +0000497 // Both paths are resolved, no need to look further...
498 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000499 }
Zachary Turner47c03462016-02-24 21:26:47 +0000500
501 FileSpec resolved_lhs(*this);
502
503 // If "this" isn't resolved, resolve it
504 if (!IsResolved())
505 {
506 if (resolved_lhs.ResolvePath())
507 {
508 // This path wasn't resolved but now it is. Check if the resolved
509 // directory is the same as our unresolved directory, and if so,
510 // we can mark this object as resolved to avoid more future resolves
511 m_is_resolved = (m_directory == resolved_lhs.m_directory);
512 }
513 else
514 return false;
515 }
516
517 FileSpec resolved_rhs(rhs);
518 if (!rhs.IsResolved())
519 {
520 if (resolved_rhs.ResolvePath())
521 {
522 // rhs's path wasn't resolved but now it is. Check if the resolved
523 // directory is the same as rhs's unresolved directory, and if so,
524 // we can mark this object as resolved to avoid more future resolves
525 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
526 }
527 else
528 return false;
529 }
530
531 // If we reach this point in the code we were able to resolve both paths
532 // and since we only resolve the paths if the basenames are equal, then
533 // we can just check if both directories are equal...
Zachary Turner74e08ca2016-03-02 22:05:52 +0000534 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000535}
536
537//------------------------------------------------------------------
538// Not equal to operator
539//------------------------------------------------------------------
540bool
541FileSpec::operator!= (const FileSpec& rhs) const
542{
Greg Clayton7481c202010-11-08 00:28:40 +0000543 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544}
545
546//------------------------------------------------------------------
547// Less than operator
548//------------------------------------------------------------------
549bool
550FileSpec::operator< (const FileSpec& rhs) const
551{
552 return FileSpec::Compare(*this, rhs, true) < 0;
553}
554
555//------------------------------------------------------------------
556// Dump a FileSpec object to a stream
557//------------------------------------------------------------------
558Stream&
559lldb_private::operator << (Stream &s, const FileSpec& f)
560{
561 f.Dump(&s);
562 return s;
563}
564
565//------------------------------------------------------------------
566// Clear this object by releasing both the directory and filename
567// string values and making them both the empty string.
568//------------------------------------------------------------------
569void
570FileSpec::Clear()
571{
572 m_directory.Clear();
573 m_filename.Clear();
574}
575
576//------------------------------------------------------------------
577// Compare two FileSpec objects. If "full" is true, then both
578// the directory and the filename must match. If "full" is false,
579// then the directory names for "a" and "b" are only compared if
580// they are both non-empty. This allows a FileSpec object to only
581// contain a filename and it can match FileSpec objects that have
582// matching filenames with different paths.
583//
584// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
585// and "1" if "a" is greater than "b".
586//------------------------------------------------------------------
587int
588FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
589{
590 int result = 0;
591
Zachary Turner47c03462016-02-24 21:26:47 +0000592 // case sensitivity of compare
593 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
594
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 // If full is true, then we must compare both the directory and filename.
596
597 // If full is false, then if either directory is empty, then we match on
598 // the basename only, and if both directories have valid values, we still
599 // do a full compare. This allows for matching when we just have a filename
600 // in one of the FileSpec objects.
601
602 if (full || (a.m_directory && b.m_directory))
603 {
Zachary Turner47c03462016-02-24 21:26:47 +0000604 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000605 if (result)
606 return result;
607 }
Zachary Turner47c03462016-02-24 21:26:47 +0000608 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000609}
610
611bool
Jim Ingham96a15962014-11-15 01:54:26 +0000612FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613{
Zachary Turner47c03462016-02-24 21:26:47 +0000614 // case sensitivity of equality test
615 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
616
Jim Ingham87df91b2011-09-23 00:54:11 +0000617 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Zachary Turner47c03462016-02-24 21:26:47 +0000618 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000619 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000620 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000621 else
622 {
Zachary Turner47c03462016-02-24 21:26:47 +0000623 if (!ConstString::Equals(a.m_filename, b.m_filename, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000624 return false;
Zachary Turner47c03462016-02-24 21:26:47 +0000625 if (ConstString::Equals(a.m_directory, b.m_directory, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000626 return true;
627 ConstString a_without_dots;
628 ConstString b_without_dots;
629
630 RemoveBackupDots (a.m_directory, a_without_dots);
631 RemoveBackupDots (b.m_directory, b_without_dots);
Zachary Turner47c03462016-02-24 21:26:47 +0000632 return ConstString::Equals(a_without_dots, b_without_dots, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000633 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634}
635
Jim Ingham96a15962014-11-15 01:54:26 +0000636void
Greg Clayton5a271952015-06-02 22:43:29 +0000637FileSpec::NormalizePath ()
638{
639 ConstString normalized_directory;
640 FileSpec::RemoveBackupDots(m_directory, normalized_directory);
641 m_directory = normalized_directory;
642}
643
644void
Jim Ingham96a15962014-11-15 01:54:26 +0000645FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
646{
647 const char *input = input_const_str.GetCString();
648 result_const_str.Clear();
649 if (!input || input[0] == '\0')
650 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651
Jim Ingham96a15962014-11-15 01:54:26 +0000652 const char win_sep = '\\';
653 const char unix_sep = '/';
654 char found_sep;
655 const char *win_backup = "\\..";
656 const char *unix_backup = "/..";
657
658 bool is_win = false;
659
660 // Determine the platform for the path (win or unix):
661
662 if (input[0] == win_sep)
663 is_win = true;
664 else if (input[0] == unix_sep)
665 is_win = false;
666 else if (input[1] == ':')
667 is_win = true;
668 else if (strchr(input, unix_sep) != nullptr)
669 is_win = false;
670 else if (strchr(input, win_sep) != nullptr)
671 is_win = true;
672 else
673 {
674 // No separators at all, no reason to do any work here.
675 result_const_str = input_const_str;
676 return;
677 }
678
679 llvm::StringRef backup_sep;
680 if (is_win)
681 {
682 found_sep = win_sep;
683 backup_sep = win_backup;
684 }
685 else
686 {
687 found_sep = unix_sep;
688 backup_sep = unix_backup;
689 }
690
691 llvm::StringRef input_ref(input);
692 llvm::StringRef curpos(input);
693
694 bool had_dots = false;
695 std::string result;
696
697 while (1)
698 {
699 // Start of loop
700 llvm::StringRef before_sep;
701 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
702
703 before_sep = around_sep.first;
704 curpos = around_sep.second;
705
706 if (curpos.empty())
707 {
708 if (had_dots)
709 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000710 while (before_sep.startswith("//"))
711 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000712 if (!before_sep.empty())
713 {
714 result.append(before_sep.data(), before_sep.size());
715 }
716 }
717 break;
718 }
719 had_dots = true;
720
721 unsigned num_backups = 1;
722 while (curpos.startswith(backup_sep))
723 {
724 num_backups++;
725 curpos = curpos.slice(backup_sep.size(), curpos.size());
726 }
727
728 size_t end_pos = before_sep.size();
729 while (num_backups-- > 0)
730 {
731 end_pos = before_sep.rfind(found_sep, end_pos);
732 if (end_pos == llvm::StringRef::npos)
733 {
734 result_const_str = input_const_str;
735 return;
736 }
737 }
738 result.append(before_sep.data(), end_pos);
739 }
740
741 if (had_dots)
742 result_const_str.SetCString(result.c_str());
743 else
744 result_const_str = input_const_str;
745
746 return;
747}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748
749//------------------------------------------------------------------
750// Dump the object to the supplied stream. If the object contains
751// a valid directory name, it will be displayed followed by a
752// directory delimiter, and the filename.
753//------------------------------------------------------------------
754void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000755FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000757 if (s)
758 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000759 std::string path{GetPath(true)};
760 s->PutCString(path.c_str());
Pavel Labath144119b2016-04-04 14:39:12 +0000761 char path_separator = GetPrefferedPathSeparator(m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000762 if (!m_filename && !path.empty() && path.back() != path_separator)
763 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000764 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765}
766
767//------------------------------------------------------------------
768// Returns true if the file exists.
769//------------------------------------------------------------------
770bool
771FileSpec::Exists () const
772{
773 struct stat file_stats;
774 return GetFileStats (this, &file_stats);
775}
776
Caroline Tice428a9a52010-09-10 04:48:55 +0000777bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000778FileSpec::Readable () const
779{
780 const uint32_t permissions = GetPermissions();
781 if (permissions & eFilePermissionsEveryoneR)
782 return true;
783 return false;
784}
785
786bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000787FileSpec::ResolveExecutableLocation ()
788{
Greg Clayton274060b2010-10-20 20:54:39 +0000789 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000790 {
Greg Clayton58f41712011-01-25 21:32:01 +0000791 const char *file_cstr = m_filename.GetCString();
792 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000793 {
Greg Clayton58f41712011-01-25 21:32:01 +0000794 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000795 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
796 if (!error_or_path)
797 return false;
798 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000799 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000800 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000801 {
Greg Clayton58f41712011-01-25 21:32:01 +0000802 // FindProgramByName returns "." if it can't find the file.
803 if (strcmp (".", dir_ref.data()) == 0)
804 return false;
805
806 m_directory.SetCString (dir_ref.data());
807 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000808 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000809 else
810 {
811 // If FindProgramByName found the file, it returns the directory + filename in its return results.
812 // We need to separate them.
813 FileSpec tmp_file (dir_ref.data(), false);
814 if (tmp_file.Exists())
815 {
816 m_directory = tmp_file.m_directory;
817 return true;
818 }
Caroline Tice391a9602010-09-12 00:10:52 +0000819 }
820 }
821 }
822 }
823
824 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000825}
826
Jim Ingham0909e5f2010-09-16 00:57:33 +0000827bool
828FileSpec::ResolvePath ()
829{
Greg Clayton7481c202010-11-08 00:28:40 +0000830 if (m_is_resolved)
831 return true; // We have already resolved this path
832
833 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000834 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000835 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000836 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000837 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000838 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000839}
840
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841uint64_t
842FileSpec::GetByteSize() const
843{
844 struct stat file_stats;
845 if (GetFileStats (this, &file_stats))
846 return file_stats.st_size;
847 return 0;
848}
849
Zachary Turnerdf62f202014-08-07 17:33:07 +0000850FileSpec::PathSyntax
851FileSpec::GetPathSyntax() const
852{
853 return m_syntax;
854}
855
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000856FileSpec::FileType
857FileSpec::GetFileType () const
858{
859 struct stat file_stats;
860 if (GetFileStats (this, &file_stats))
861 {
862 mode_t file_type = file_stats.st_mode & S_IFMT;
863 switch (file_type)
864 {
865 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000867#ifndef _WIN32
868 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 case S_IFSOCK: return eFileTypeSocket;
870 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000871#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872 default:
873 break;
874 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000875 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876 }
877 return eFileTypeInvalid;
878}
879
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000880bool
881FileSpec::IsSymbolicLink () const
882{
883 char resolved_path[PATH_MAX];
884 if (!GetPath (resolved_path, sizeof (resolved_path)))
885 return false;
886
887#ifdef _WIN32
Zachary Turner190fadc2016-03-22 17:58:09 +0000888 std::wstring wpath;
889 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
890 return false;
891 auto attrs = ::GetFileAttributesW(wpath.c_str());
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000892 if (attrs == INVALID_FILE_ATTRIBUTES)
893 return false;
894
895 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
896#else
897 struct stat file_stats;
898 if (::lstat (resolved_path, &file_stats) != 0)
899 return false;
900
901 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
902#endif
903}
904
Greg Claytonfbb76342013-11-20 21:07:01 +0000905uint32_t
906FileSpec::GetPermissions () const
907{
908 uint32_t file_permissions = 0;
909 if (*this)
Chaoren Lind3173f32015-05-29 19:52:29 +0000910 FileSystem::GetFilePermissions(*this, file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000911 return file_permissions;
912}
913
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914TimeValue
915FileSpec::GetModificationTime () const
916{
917 TimeValue mod_time;
918 struct stat file_stats;
919 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000920 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921 return mod_time;
922}
923
924//------------------------------------------------------------------
925// Directory string get accessor.
926//------------------------------------------------------------------
927ConstString &
928FileSpec::GetDirectory()
929{
930 return m_directory;
931}
932
933//------------------------------------------------------------------
934// Directory string const get accessor.
935//------------------------------------------------------------------
936const ConstString &
937FileSpec::GetDirectory() const
938{
939 return m_directory;
940}
941
942//------------------------------------------------------------------
943// Filename string get accessor.
944//------------------------------------------------------------------
945ConstString &
946FileSpec::GetFilename()
947{
948 return m_filename;
949}
950
951//------------------------------------------------------------------
952// Filename string const get accessor.
953//------------------------------------------------------------------
954const ConstString &
955FileSpec::GetFilename() const
956{
957 return m_filename;
958}
959
960//------------------------------------------------------------------
961// Extract the directory and path into a fixed buffer. This is
962// needed as the directory and path are stored in separate string
963// values.
964//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000965size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000966FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000968 if (!path)
969 return 0;
970
Zachary Turnerdf62f202014-08-07 17:33:07 +0000971 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000972 ::snprintf(path, path_max_len, "%s", result.c_str());
973 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974}
975
Greg Claytona44c1e62013-04-29 16:36:27 +0000976std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000977FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000978{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000979 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000980 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000981 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000982}
983
Chaoren Lind3173f32015-05-29 19:52:29 +0000984const char *
985FileSpec::GetCString(bool denormalize) const
986{
987 return ConstString{GetPath(denormalize)}.AsCString(NULL);
988}
989
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000990void
991FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
992{
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000993 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
Pavel Labath144119b2016-04-04 14:39:12 +0000994 if (m_directory && m_filename && !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
995 path.insert(path.end(), GetPrefferedPathSeparator(m_syntax));
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000996 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000997 Normalize(path, m_syntax);
998 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000999 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +00001000}
1001
Enrico Granataa9dbf432011-10-17 21:45:27 +00001002ConstString
1003FileSpec::GetFileNameExtension () const
1004{
Greg Clayton1f746072012-08-29 21:13:06 +00001005 if (m_filename)
1006 {
1007 const char *filename = m_filename.GetCString();
1008 const char* dot_pos = strrchr(filename, '.');
1009 if (dot_pos && dot_pos[1] != '\0')
1010 return ConstString(dot_pos+1);
1011 }
1012 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +00001013}
1014
1015ConstString
1016FileSpec::GetFileNameStrippingExtension () const
1017{
1018 const char *filename = m_filename.GetCString();
1019 if (filename == NULL)
1020 return ConstString();
1021
Johnny Chenf5df5372011-10-18 19:28:30 +00001022 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +00001023 if (dot_pos == NULL)
1024 return m_filename;
1025
1026 return ConstString(filename, dot_pos-filename);
1027}
1028
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029//------------------------------------------------------------------
1030// Returns a shared pointer to a data buffer that contains all or
1031// part of the contents of a file. The data is memory mapped and
1032// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001033// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034// file, and "file_size" bytes will be mapped. If "file_size" is
1035// greater than the number of bytes available in the file starting
1036// at "file_offset", the number of bytes will be appropriately
1037// truncated. The final number of bytes that get mapped can be
1038// verified using the DataBuffer::GetByteSize() function.
1039//------------------------------------------------------------------
1040DataBufferSP
1041FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
1042{
1043 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +00001044 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 if (mmap_data.get())
1046 {
Greg Claytond398a1c2013-04-20 00:23:26 +00001047 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
1048 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 data_sp.reset(mmap_data.release());
1050 }
1051 return data_sp;
1052}
1053
Greg Clayton736888c2015-02-23 23:47:09 +00001054DataBufferSP
1055FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
1056{
1057 if (FileSystem::IsLocal(*this))
1058 return MemoryMapFileContents(file_offset, file_size);
1059 else
1060 return ReadFileContents(file_offset, file_size, NULL);
1061}
1062
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063
1064//------------------------------------------------------------------
1065// Return the size in bytes that this object takes in memory. This
1066// returns the size in bytes of this object, not any shared string
1067// values it may refer to.
1068//------------------------------------------------------------------
1069size_t
1070FileSpec::MemorySize() const
1071{
1072 return m_filename.MemorySize() + m_directory.MemorySize();
1073}
1074
Greg Claytondda4f7b2010-06-30 23:03:03 +00001075
1076size_t
Greg Clayton4017fa32012-01-06 02:01:06 +00001077FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078{
Greg Clayton4017fa32012-01-06 02:01:06 +00001079 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001080 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081 char resolved_path[PATH_MAX];
1082 if (GetPath(resolved_path, sizeof(resolved_path)))
1083 {
Greg Clayton96c09682012-01-04 22:56:43 +00001084 File file;
1085 error = file.Open(resolved_path, File::eOpenOptionRead);
1086 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087 {
Greg Clayton96c09682012-01-04 22:56:43 +00001088 off_t file_offset_after_seek = file_offset;
1089 bytes_read = dst_len;
1090 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001091 }
Greg Claytondda4f7b2010-06-30 23:03:03 +00001092 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001093 else
1094 {
1095 error.SetErrorString("invalid file specification");
1096 }
1097 if (error_ptr)
1098 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001099 return bytes_read;
1100}
1101
1102//------------------------------------------------------------------
1103// Returns a shared pointer to a data buffer that contains all or
1104// part of the contents of a file. The data copies into a heap based
1105// buffer that lives in the DataBuffer shared pointer object returned.
1106// The data that is cached will start "file_offset" bytes into the
1107// file, and "file_size" bytes will be mapped. If "file_size" is
1108// greater than the number of bytes available in the file starting
1109// at "file_offset", the number of bytes will be appropriately
1110// truncated. The final number of bytes that get mapped can be
1111// verified using the DataBuffer::GetByteSize() function.
1112//------------------------------------------------------------------
1113DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +00001114FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +00001115{
Greg Clayton4017fa32012-01-06 02:01:06 +00001116 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001117 DataBufferSP data_sp;
1118 char resolved_path[PATH_MAX];
1119 if (GetPath(resolved_path, sizeof(resolved_path)))
1120 {
Greg Clayton96c09682012-01-04 22:56:43 +00001121 File file;
1122 error = file.Open(resolved_path, File::eOpenOptionRead);
1123 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +00001124 {
1125 const bool null_terminate = false;
1126 error = file.Read (file_size, file_offset, null_terminate, data_sp);
1127 }
1128 }
1129 else
1130 {
1131 error.SetErrorString("invalid file specification");
1132 }
1133 if (error_ptr)
1134 *error_ptr = error;
1135 return data_sp;
1136}
1137
1138DataBufferSP
1139FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1140{
1141 Error error;
1142 DataBufferSP data_sp;
1143 char resolved_path[PATH_MAX];
1144 if (GetPath(resolved_path, sizeof(resolved_path)))
1145 {
1146 File file;
1147 error = file.Open(resolved_path, File::eOpenOptionRead);
1148 if (error.Success())
1149 {
1150 off_t offset = 0;
1151 size_t length = SIZE_MAX;
1152 const bool null_terminate = true;
1153 error = file.Read (length, offset, null_terminate, data_sp);
1154 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001156 else
1157 {
1158 error.SetErrorString("invalid file specification");
1159 }
1160 if (error_ptr)
1161 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162 return data_sp;
1163}
1164
Greg Clayton58fc50e2010-10-20 22:52:05 +00001165size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166FileSpec::ReadFileLines (STLStringArray &lines)
1167{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001168 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001169 char path[PATH_MAX];
1170 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001172 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173
Greg Clayton58fc50e2010-10-20 22:52:05 +00001174 if (file_stream)
1175 {
1176 std::string line;
1177 while (getline (file_stream, line))
1178 lines.push_back (line);
1179 }
1180 }
1181 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182}
Greg Clayton4272cc72011-02-02 02:24:04 +00001183
1184FileSpec::EnumerateDirectoryResult
Greg Clayton58c65f02015-06-29 18:29:00 +00001185FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const &callback)
1186{
1187 if (dir_path && dir_path[0])
1188 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001189#ifdef _WIN32
Greg Clayton58c65f02015-06-29 18:29:00 +00001190 std::string szDir(dir_path);
1191 szDir += "\\*";
1192
Zachary Turner190fadc2016-03-22 17:58:09 +00001193 std::wstring wszDir;
1194 if (!llvm::ConvertUTF8toWide(szDir, wszDir))
1195 {
1196 return eEnumerateDirectoryResultNext;
1197 }
1198
1199 WIN32_FIND_DATAW ffd;
1200 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
Greg Clayton58c65f02015-06-29 18:29:00 +00001201
1202 if (hFind == INVALID_HANDLE_VALUE)
1203 {
1204 return eEnumerateDirectoryResultNext;
1205 }
1206
1207 do
1208 {
Greg Clayton58c65f02015-06-29 18:29:00 +00001209 FileSpec::FileType file_type = eFileTypeUnknown;
1210 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1211 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001212 size_t len = wcslen(ffd.cFileName);
Greg Clayton58c65f02015-06-29 18:29:00 +00001213
Zachary Turner190fadc2016-03-22 17:58:09 +00001214 if (len == 1 && ffd.cFileName[0] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001215 continue;
1216
Zachary Turner190fadc2016-03-22 17:58:09 +00001217 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001218 continue;
1219
1220 file_type = eFileTypeDirectory;
Greg Clayton58c65f02015-06-29 18:29:00 +00001221 }
1222 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1223 {
1224 file_type = eFileTypeOther;
Greg Clayton58c65f02015-06-29 18:29:00 +00001225 }
1226 else
1227 {
1228 file_type = eFileTypeRegular;
Greg Clayton58c65f02015-06-29 18:29:00 +00001229 }
Ewan Crawford184d4df2015-06-30 15:03:31 +00001230
Zachary Turner190fadc2016-03-22 17:58:09 +00001231 std::string fileName;
1232 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName))
1233 {
1234 continue;
1235 }
1236
1237 std::vector<char> child_path(PATH_MAX);
1238 const int child_path_len =
1239 ::snprintf(child_path.data(), child_path.size(), "%s\\%s", dir_path, fileName.c_str());
1240 if (child_path_len < (int)(child_path.size() - 1))
Greg Clayton58c65f02015-06-29 18:29:00 +00001241 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001242 // Don't resolve the file type or path
Zachary Turner190fadc2016-03-22 17:58:09 +00001243 FileSpec child_path_spec(child_path.data(), false);
Ewan Crawford184d4df2015-06-30 15:03:31 +00001244
1245 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1246
1247 switch (result)
Greg Clayton58c65f02015-06-29 18:29:00 +00001248 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001249 case eEnumerateDirectoryResultNext:
1250 // Enumerate next entry in the current directory. We just
1251 // exit this switch and will continue enumerating the
1252 // current directory as we currently are...
1253 break;
Greg Clayton58c65f02015-06-29 18:29:00 +00001254
Ewan Crawford184d4df2015-06-30 15:03:31 +00001255 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 +00001256 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1257 eEnumerateDirectoryResultQuit)
Ewan Crawford184d4df2015-06-30 15:03:31 +00001258 {
1259 // The subdirectory returned Quit, which means to
1260 // stop all directory enumerations at all levels.
Greg Clayton58c65f02015-06-29 18:29:00 +00001261 return eEnumerateDirectoryResultQuit;
Ewan Crawford184d4df2015-06-30 15:03:31 +00001262 }
1263 break;
1264
1265 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1266 // Exit from this directory level and tell parent to
1267 // keep enumerating.
1268 return eEnumerateDirectoryResultNext;
1269
1270 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1271 return eEnumerateDirectoryResultQuit;
Greg Clayton58c65f02015-06-29 18:29:00 +00001272 }
1273 }
Zachary Turner190fadc2016-03-22 17:58:09 +00001274 } while (FindNextFileW(hFind, &ffd) != 0);
Greg Clayton58c65f02015-06-29 18:29:00 +00001275
1276 FindClose(hFind);
1277#else
1278 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1279 if (dir_path_dir.is_valid())
1280 {
1281 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1282
1283 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1284#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1285 if (path_max < __DARWIN_MAXPATHLEN)
1286 path_max = __DARWIN_MAXPATHLEN;
1287#endif
1288 struct dirent *buf, *dp;
1289 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1290
1291 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1292 {
1293 // Only search directories
1294 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1295 {
1296 size_t len = strlen(dp->d_name);
1297
1298 if (len == 1 && dp->d_name[0] == '.')
1299 continue;
1300
1301 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1302 continue;
1303 }
1304
1305 FileSpec::FileType file_type = eFileTypeUnknown;
1306
1307 switch (dp->d_type)
1308 {
1309 default:
1310 case DT_UNKNOWN: file_type = eFileTypeUnknown; break;
1311 case DT_FIFO: file_type = eFileTypePipe; break;
1312 case DT_CHR: file_type = eFileTypeOther; break;
1313 case DT_DIR: file_type = eFileTypeDirectory; break;
1314 case DT_BLK: file_type = eFileTypeOther; break;
1315 case DT_REG: file_type = eFileTypeRegular; break;
1316 case DT_LNK: file_type = eFileTypeSymbolicLink; break;
1317 case DT_SOCK: file_type = eFileTypeSocket; break;
1318#if !defined(__OpenBSD__)
1319 case DT_WHT: file_type = eFileTypeOther; break;
1320#endif
1321 }
1322
1323 char child_path[PATH_MAX];
1324
1325 // Don't make paths with "/foo//bar", that just confuses everybody.
1326 int child_path_len;
1327 if (dir_path_last_char == '/')
1328 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1329 else
1330 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1331
1332 if (child_path_len < (int)(sizeof(child_path) - 1))
1333 {
1334 // Don't resolve the file type or path
1335 FileSpec child_path_spec (child_path, false);
1336
1337 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1338
1339 switch (result)
1340 {
1341 case eEnumerateDirectoryResultNext:
1342 // Enumerate next entry in the current directory. We just
1343 // exit this switch and will continue enumerating the
1344 // current directory as we currently are...
1345 break;
1346
1347 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1348 if (FileSpec::ForEachItemInDirectory (child_path, callback) == eEnumerateDirectoryResultQuit)
1349 {
1350 // The subdirectory returned Quit, which means to
1351 // stop all directory enumerations at all levels.
1352 if (buf)
1353 free (buf);
1354 return eEnumerateDirectoryResultQuit;
1355 }
1356 break;
1357
1358 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1359 // Exit from this directory level and tell parent to
1360 // keep enumerating.
1361 if (buf)
1362 free (buf);
1363 return eEnumerateDirectoryResultNext;
1364
1365 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1366 if (buf)
1367 free (buf);
1368 return eEnumerateDirectoryResultQuit;
1369 }
1370 }
1371 }
1372 if (buf)
1373 {
1374 free (buf);
1375 }
1376 }
1377#endif
1378 }
1379 // By default when exiting a directory, we tell the parent enumeration
1380 // to continue enumerating.
1381 return eEnumerateDirectoryResultNext;
1382}
1383
1384FileSpec::EnumerateDirectoryResult
Greg Clayton4272cc72011-02-02 02:24:04 +00001385FileSpec::EnumerateDirectory
1386(
1387 const char *dir_path,
1388 bool find_directories,
1389 bool find_files,
1390 bool find_other,
1391 EnumerateDirectoryCallbackType callback,
1392 void *callback_baton
1393)
1394{
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001395 return ForEachItemInDirectory(dir_path,
1396 [&find_directories, &find_files, &find_other, &callback, &callback_baton]
1397 (FileType file_type, const FileSpec &file_spec) {
1398 switch (file_type)
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001399 {
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001400 case FileType::eFileTypeDirectory:
1401 if (find_directories)
1402 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001403 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001404 case FileType::eFileTypeRegular:
1405 if (find_files)
1406 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001407 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001408 default:
1409 if (find_other)
1410 return callback(callback_baton, file_type, file_spec);
1411 break;
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001412 }
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001413 return eEnumerateDirectoryResultNext;
1414 });
Greg Clayton4272cc72011-02-02 02:24:04 +00001415}
1416
Daniel Maleae0f8f572013-08-26 23:57:52 +00001417FileSpec
1418FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1419{
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001420 FileSpec ret = *this;
1421 ret.AppendPathComponent(new_path);
1422 return ret;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001423}
1424
1425FileSpec
1426FileSpec::CopyByRemovingLastPathComponent () const
1427{
1428 const bool resolve = false;
1429 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1430 return FileSpec("",resolve);
1431 if (m_directory.IsEmpty())
1432 return FileSpec("",resolve);
1433 if (m_filename.IsEmpty())
1434 {
1435 const char* dir_cstr = m_directory.GetCString();
1436 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1437
1438 // check for obvious cases before doing the full thing
1439 if (!last_slash_ptr)
1440 return FileSpec("",resolve);
1441 if (last_slash_ptr == dir_cstr)
1442 return FileSpec("/",resolve);
1443
1444 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1445 ConstString new_path(dir_cstr,last_slash_pos);
1446 return FileSpec(new_path.GetCString(),resolve);
1447 }
1448 else
1449 return FileSpec(m_directory.GetCString(),resolve);
1450}
1451
Greg Claytonfbb76342013-11-20 21:07:01 +00001452ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001453FileSpec::GetLastPathComponent () const
1454{
Greg Claytonfbb76342013-11-20 21:07:01 +00001455 if (m_filename)
1456 return m_filename;
1457 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001458 {
1459 const char* dir_cstr = m_directory.GetCString();
1460 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1461 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001462 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001463 if (last_slash_ptr == dir_cstr)
1464 {
1465 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001466 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001467 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001468 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001469 }
1470 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001471 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001472 const char* penultimate_slash_ptr = last_slash_ptr;
1473 while (*penultimate_slash_ptr)
1474 {
1475 --penultimate_slash_ptr;
1476 if (penultimate_slash_ptr == dir_cstr)
1477 break;
1478 if (*penultimate_slash_ptr == '/')
1479 break;
1480 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001481 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1482 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001483 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001484 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001485}
1486
1487void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001488FileSpec::PrependPathComponent(const char *new_path)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001489{
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001490 if (!new_path) return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001491 const bool resolve = false;
1492 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1493 {
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001494 SetFile(new_path, resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001495 return;
1496 }
1497 StreamString stream;
1498 if (m_filename.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001499 stream.Printf("%s/%s", new_path, m_directory.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001500 else if (m_directory.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001501 stream.Printf("%s/%s", new_path, m_filename.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001502 else
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001503 stream.Printf("%s/%s/%s", new_path, m_directory.GetCString(), m_filename.GetCString());
1504 SetFile(stream.GetData(), resolve);
1505}
1506
1507void
1508FileSpec::PrependPathComponent(const std::string &new_path)
1509{
1510 return PrependPathComponent(new_path.c_str());
1511}
1512
1513void
1514FileSpec::PrependPathComponent(const FileSpec &new_path)
1515{
1516 return PrependPathComponent(new_path.GetPath(false));
1517}
1518
1519void
1520FileSpec::AppendPathComponent(const char *new_path)
1521{
1522 if (!new_path) return;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001523
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001524 StreamString stream;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001525 if (!m_directory.IsEmpty())
1526 {
1527 stream.PutCString(m_directory.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001528 if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1529 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001530 }
1531
1532 if (!m_filename.IsEmpty())
1533 {
1534 stream.PutCString(m_filename.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001535 if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
1536 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001537 }
1538
1539 stream.PutCString(new_path);
1540
1541 const bool resolve = false;
1542 SetFile(stream.GetData(), resolve, m_syntax);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001543}
1544
1545void
Chaoren Lind3173f32015-05-29 19:52:29 +00001546FileSpec::AppendPathComponent(const std::string &new_path)
1547{
1548 return AppendPathComponent(new_path.c_str());
1549}
1550
1551void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001552FileSpec::AppendPathComponent(const FileSpec &new_path)
1553{
1554 return AppendPathComponent(new_path.GetPath(false));
1555}
1556
1557void
Daniel Maleae0f8f572013-08-26 23:57:52 +00001558FileSpec::RemoveLastPathComponent ()
1559{
1560 const bool resolve = false;
1561 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1562 {
1563 SetFile("",resolve);
1564 return;
1565 }
1566 if (m_directory.IsEmpty())
1567 {
1568 SetFile("",resolve);
1569 return;
1570 }
1571 if (m_filename.IsEmpty())
1572 {
1573 const char* dir_cstr = m_directory.GetCString();
1574 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1575
1576 // check for obvious cases before doing the full thing
1577 if (!last_slash_ptr)
1578 {
1579 SetFile("",resolve);
1580 return;
1581 }
1582 if (last_slash_ptr == dir_cstr)
1583 {
1584 SetFile("/",resolve);
1585 return;
1586 }
1587 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1588 ConstString new_path(dir_cstr,last_slash_pos);
1589 SetFile(new_path.GetCString(),resolve);
1590 }
1591 else
1592 SetFile(m_directory.GetCString(),resolve);
1593}
Greg Clayton1f746072012-08-29 21:13:06 +00001594//------------------------------------------------------------------
1595/// Returns true if the filespec represents an implementation source
1596/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1597/// extension).
1598///
1599/// @return
1600/// \b true if the filespec represents an implementation source
1601/// file, \b false otherwise.
1602//------------------------------------------------------------------
1603bool
1604FileSpec::IsSourceImplementationFile () const
1605{
1606 ConstString extension (GetFileNameExtension());
1607 if (extension)
1608 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001609 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 +00001610 return g_source_file_regex.Execute (extension.GetCString());
1611 }
1612 return false;
1613}
1614
Greg Claytona0ca6602012-10-18 16:33:33 +00001615bool
Chaoren Lin372e9062015-06-09 17:54:27 +00001616FileSpec::IsRelative() const
Greg Claytona0ca6602012-10-18 16:33:33 +00001617{
Zachary Turner270e99a2014-12-08 21:36:42 +00001618 const char *dir = m_directory.GetCString();
1619 llvm::StringRef directory(dir ? dir : "");
1620
1621 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001622 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001623 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001624 {
1625 // If the path doesn't start with '/' or '~', return true
1626 switch (directory[0])
1627 {
1628 case '/':
1629 case '~':
1630 return false;
1631 default:
1632 return true;
1633 }
1634 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001635 else
1636 {
1637 if (directory.size() >= 2 && directory[1] == ':')
1638 return false;
1639 if (directory[0] == '/')
1640 return false;
1641 return true;
1642 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001643 }
1644 else if (m_filename)
1645 {
1646 // No directory, just a basename, return true
1647 return true;
1648 }
1649 return false;
1650}
Chaoren Lin372e9062015-06-09 17:54:27 +00001651
1652bool
1653FileSpec::IsAbsolute() const
1654{
1655 return !FileSpec::IsRelative();
1656}