blob: 7f0407578e16899d96ee560ee5ce81ee46669e57 [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Rafael Espindola09079162013-06-13 20:10:23 +000021#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000022#include <string.h>
Jim Ingham9035e7c2011-02-07 19:42:39 +000023#include <fstream>
Greg Claytonfd184262011-02-05 02:27:52 +000024
Jim Ingham9035e7c2011-02-07 19:42:39 +000025#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000026#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000027#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000028#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029
Chaoren Linf34f4102015-05-09 01:21:32 +000030#include "lldb/Core/ArchSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000031#include "lldb/Core/DataBufferHeap.h"
32#include "lldb/Core/DataBufferMemoryMap.h"
33#include "lldb/Core/RegularExpression.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Stream.h"
36#include "lldb/Host/File.h"
37#include "lldb/Host/FileSpec.h"
38#include "lldb/Host/FileSystem.h"
39#include "lldb/Host/Host.h"
40#include "lldb/Utility/CleanUp.h"
41
Caroline Tice391a9602010-09-12 00:10:52 +000042#include "llvm/ADT/StringRef.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
50static bool
51GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
52{
53 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000054 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055 return ::stat (resolved_path, stats_ptr) == 0;
56 return false;
57}
58
Jim Inghamf818ca32010-07-01 01:48:53 +000059// Resolves the username part of a path of the form ~user/other/directories, and
Jim Inghamead45cc2014-09-12 23:50:36 +000060// writes the result into dst_path. This will also resolve "~" to the current user.
61// If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
Zachary Turner3f559742014-08-07 17:33:36 +000062void
63FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
Jim Inghamf818ca32010-07-01 01:48:53 +000064{
Zachary Turner3f559742014-08-07 17:33:36 +000065#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
66 if (path.empty() || path[0] != '~')
67 return;
Jim Inghamf818ca32010-07-01 01:48:53 +000068
Jason Molenda3bc66f12015-01-20 04:20:42 +000069 llvm::StringRef path_str(path.data(), path.size());
Zachary Turner3f559742014-08-07 17:33:36 +000070 size_t slash_pos = path_str.find_first_of("/", 1);
Jim Inghamead45cc2014-09-12 23:50:36 +000071 if (slash_pos == 1 || path.size() == 1)
Jim Inghamf818ca32010-07-01 01:48:53 +000072 {
Jim Ingham2f21bbc2014-09-12 23:04:40 +000073 // A path of ~/ resolves to the current user's home dir
Zachary Turner3f559742014-08-07 17:33:36 +000074 llvm::SmallString<64> home_dir;
75 if (!llvm::sys::path::home_directory(home_dir))
76 return;
77
78 // Overwrite the ~ with the first character of the homedir, and insert
79 // the rest. This way we only trigger one move, whereas an insert
80 // followed by a delete (or vice versa) would trigger two.
81 path[0] = home_dir[0];
82 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
83 return;
84 }
85
86 auto username_begin = path.begin()+1;
87 auto username_end = (slash_pos == llvm::StringRef::npos)
88 ? path.end()
89 : (path.begin() + slash_pos);
90 size_t replacement_length = std::distance(path.begin(), username_end);
91
92 llvm::SmallString<20> username(username_begin, username_end);
93 struct passwd *user_entry = ::getpwnam(username.c_str());
94 if (user_entry != nullptr)
95 {
96 // Copy over the first n characters of the path, where n is the smaller of the length
97 // of the home directory and the slash pos.
98 llvm::StringRef homedir(user_entry->pw_dir);
99 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
100 auto src_begin = homedir.begin();
101 auto src_end = src_begin + initial_copy_length;
102 std::copy(src_begin, src_end, path.begin());
103 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000104 {
Zachary Turner3f559742014-08-07 17:33:36 +0000105 // We copied the entire home directory, but the ~username portion of the path was
106 // longer, so there's characters that need to be removed.
107 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000108 }
Zachary Turner3f559742014-08-07 17:33:36 +0000109 else if (replacement_length < homedir.size())
110 {
111 // We copied all the way up to the slash in the destination, but there's still more
112 // characters that need to be inserted.
113 path.insert(username_end, src_end, homedir.end());
114 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000115 }
116 else
117 {
Zachary Turner3f559742014-08-07 17:33:36 +0000118 // Unable to resolve username (user doesn't exist?)
119 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000120 }
Zachary Turner3f559742014-08-07 17:33:36 +0000121#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000122}
123
Greg Claytonc982c762010-07-09 20:39:50 +0000124size_t
Jim Ingham84363072011-02-08 23:24:09 +0000125FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
126{
127#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
128 size_t extant_entries = matches.GetSize();
129
130 setpwent();
131 struct passwd *user_entry;
132 const char *name_start = partial_name + 1;
133 std::set<std::string> name_list;
134
135 while ((user_entry = getpwent()) != NULL)
136 {
137 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
138 {
139 std::string tmp_buf("~");
140 tmp_buf.append(user_entry->pw_name);
141 tmp_buf.push_back('/');
142 name_list.insert(tmp_buf);
143 }
144 }
145 std::set<std::string>::iterator pos, end = name_list.end();
146 for (pos = name_list.begin(); pos != end; pos++)
147 {
148 matches.AppendString((*pos).c_str());
149 }
150 return matches.GetSize() - extant_entries;
151#else
152 // Resolving home directories is not supported, just copy the path...
153 return 0;
154#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
155}
156
Zachary Turner3f559742014-08-07 17:33:36 +0000157void
158FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000159{
Zachary Turner3f559742014-08-07 17:33:36 +0000160 if (path.empty())
161 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000162
Greg Clayton45319462011-02-08 00:35:34 +0000163#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000164 if (path[0] == '~')
165 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000166#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000167
Jason Molenda671a29d2015-02-25 02:35:25 +0000168 // Save a copy of the original path that's passed in
169 llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end());
170
Zachary Turner3f559742014-08-07 17:33:36 +0000171 llvm::sys::fs::make_absolute(path);
Jason Molenda671a29d2015-02-25 02:35:25 +0000172
173
174 path.push_back(0); // Be sure we have a nul terminated string
175 path.pop_back();
176 struct stat file_stats;
177 if (::stat (path.data(), &file_stats) != 0)
178 {
179 path.clear();
180 path.append(original_path.begin(), original_path.end());
181 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000182}
183
Jason Molenda68c85212014-10-15 03:04:33 +0000184FileSpec::FileSpec() :
185 m_directory(),
186 m_filename(),
187 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000188{
189}
190
191//------------------------------------------------------------------
192// Default constructor that can take an optional full path to a
193// file on disk.
194//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000195FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000196 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000197 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000198 m_is_resolved(false),
199 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000200{
201 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000202 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000203}
204
Chaoren Linf34f4102015-05-09 01:21:32 +0000205FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
206 FileSpec(pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix)
207{
208}
209
Jim Ingham0909e5f2010-09-16 00:57:33 +0000210//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211// Copy constructor
212//------------------------------------------------------------------
213FileSpec::FileSpec(const FileSpec& rhs) :
214 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000215 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000216 m_is_resolved (rhs.m_is_resolved),
217 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000218{
219}
220
221//------------------------------------------------------------------
222// Copy constructor
223//------------------------------------------------------------------
224FileSpec::FileSpec(const FileSpec* rhs) :
225 m_directory(),
226 m_filename()
227{
228 if (rhs)
229 *this = *rhs;
230}
231
232//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000233// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000234//------------------------------------------------------------------
235FileSpec::~FileSpec()
236{
237}
238
239//------------------------------------------------------------------
240// Assignment operator.
241//------------------------------------------------------------------
242const FileSpec&
243FileSpec::operator= (const FileSpec& rhs)
244{
245 if (this != &rhs)
246 {
247 m_directory = rhs.m_directory;
248 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000249 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000250 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251 }
252 return *this;
253}
254
Zachary Turner3f559742014-08-07 17:33:36 +0000255void FileSpec::Normalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000256{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000257 if (syntax == ePathSyntaxPosix ||
258 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000259 return;
260
Zachary Turner3f559742014-08-07 17:33:36 +0000261 std::replace(path.begin(), path.end(), '\\', '/');
Hafiz Abid Qadeer93ad6b32015-02-08 20:21:08 +0000262 // Windows path can have \\ slashes which can be changed by replace
263 // call above to //. Here we remove the duplicate.
264 auto iter = std::unique ( path.begin(), path.end(),
265 []( char &c1, char &c2 ){
266 return (c1 == '/' && c2 == '/');});
267 path.erase(iter, path.end());
Zachary Turnerdf62f202014-08-07 17:33:07 +0000268}
269
Zachary Turner3f559742014-08-07 17:33:36 +0000270void FileSpec::DeNormalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000271{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000272 if (syntax == ePathSyntaxPosix ||
273 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000274 return;
275
Zachary Turner3f559742014-08-07 17:33:36 +0000276 std::replace(path.begin(), path.end(), '/', '\\');
Zachary Turnerdf62f202014-08-07 17:33:07 +0000277}
278
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000279//------------------------------------------------------------------
280// Update the contents of this object with a new path. The path will
281// be split up into a directory and filename and stored as uniqued
282// string values for quick comparison and efficient memory usage.
283//------------------------------------------------------------------
284void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000285FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286{
287 m_filename.Clear();
288 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000289 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000290 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000291
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292 if (pathname == NULL || pathname[0] == '\0')
293 return;
294
Zachary Turner3f559742014-08-07 17:33:36 +0000295 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000296
Jim Ingham0909e5f2010-09-16 00:57:33 +0000297 if (resolve)
298 {
Zachary Turner3f559742014-08-07 17:33:36 +0000299 FileSpec::Resolve (normalized);
300 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000301 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000302
303 // Only normalize after resolving the path. Resolution will modify the path
304 // string, potentially adding wrong kinds of slashes to the path, that need
305 // to be re-normalized.
306 Normalize(normalized, syntax);
307
Zachary Turner3f559742014-08-07 17:33:36 +0000308 llvm::StringRef resolve_path_ref(normalized.c_str());
309 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
310 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000311 {
Zachary Turner3f559742014-08-07 17:33:36 +0000312 m_filename.SetString (filename_ref);
313 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
314 if (!directory_ref.empty())
315 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316 }
Zachary Turner3f559742014-08-07 17:33:36 +0000317 else
318 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319}
320
321//----------------------------------------------------------------------
322// Convert to pointer operator. This allows code to check any FileSpec
323// objects to see if they contain anything valid using code such as:
324//
325// if (file_spec)
326// {}
327//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000328FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000330 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000331}
332
333//----------------------------------------------------------------------
334// Logical NOT operator. This allows code to check any FileSpec
335// objects to see if they are invalid using code such as:
336//
337// if (!file_spec)
338// {}
339//----------------------------------------------------------------------
340bool
341FileSpec::operator!() const
342{
343 return !m_directory && !m_filename;
344}
345
346//------------------------------------------------------------------
347// Equal to operator
348//------------------------------------------------------------------
349bool
350FileSpec::operator== (const FileSpec& rhs) const
351{
Greg Clayton7481c202010-11-08 00:28:40 +0000352 if (m_filename == rhs.m_filename)
353 {
354 if (m_directory == rhs.m_directory)
355 return true;
356
357 // TODO: determine if we want to keep this code in here.
358 // The code below was added to handle a case where we were
359 // trying to set a file and line breakpoint and one path
360 // was resolved, and the other not and the directory was
361 // in a mount point that resolved to a more complete path:
362 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
363 // this out...
364 if (IsResolved() && rhs.IsResolved())
365 {
366 // Both paths are resolved, no need to look further...
367 return false;
368 }
369
370 FileSpec resolved_lhs(*this);
371
372 // If "this" isn't resolved, resolve it
373 if (!IsResolved())
374 {
375 if (resolved_lhs.ResolvePath())
376 {
377 // This path wasn't resolved but now it is. Check if the resolved
378 // directory is the same as our unresolved directory, and if so,
379 // we can mark this object as resolved to avoid more future resolves
380 m_is_resolved = (m_directory == resolved_lhs.m_directory);
381 }
382 else
383 return false;
384 }
385
386 FileSpec resolved_rhs(rhs);
387 if (!rhs.IsResolved())
388 {
389 if (resolved_rhs.ResolvePath())
390 {
391 // rhs's path wasn't resolved but now it is. Check if the resolved
392 // directory is the same as rhs's unresolved directory, and if so,
393 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000394 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000395 }
396 else
397 return false;
398 }
399
400 // If we reach this point in the code we were able to resolve both paths
401 // and since we only resolve the paths if the basenames are equal, then
402 // we can just check if both directories are equal...
403 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
404 }
405 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406}
407
408//------------------------------------------------------------------
409// Not equal to operator
410//------------------------------------------------------------------
411bool
412FileSpec::operator!= (const FileSpec& rhs) const
413{
Greg Clayton7481c202010-11-08 00:28:40 +0000414 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415}
416
417//------------------------------------------------------------------
418// Less than operator
419//------------------------------------------------------------------
420bool
421FileSpec::operator< (const FileSpec& rhs) const
422{
423 return FileSpec::Compare(*this, rhs, true) < 0;
424}
425
426//------------------------------------------------------------------
427// Dump a FileSpec object to a stream
428//------------------------------------------------------------------
429Stream&
430lldb_private::operator << (Stream &s, const FileSpec& f)
431{
432 f.Dump(&s);
433 return s;
434}
435
436//------------------------------------------------------------------
437// Clear this object by releasing both the directory and filename
438// string values and making them both the empty string.
439//------------------------------------------------------------------
440void
441FileSpec::Clear()
442{
443 m_directory.Clear();
444 m_filename.Clear();
445}
446
447//------------------------------------------------------------------
448// Compare two FileSpec objects. If "full" is true, then both
449// the directory and the filename must match. If "full" is false,
450// then the directory names for "a" and "b" are only compared if
451// they are both non-empty. This allows a FileSpec object to only
452// contain a filename and it can match FileSpec objects that have
453// matching filenames with different paths.
454//
455// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
456// and "1" if "a" is greater than "b".
457//------------------------------------------------------------------
458int
459FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
460{
461 int result = 0;
462
463 // If full is true, then we must compare both the directory and filename.
464
465 // If full is false, then if either directory is empty, then we match on
466 // the basename only, and if both directories have valid values, we still
467 // do a full compare. This allows for matching when we just have a filename
468 // in one of the FileSpec objects.
469
470 if (full || (a.m_directory && b.m_directory))
471 {
472 result = ConstString::Compare(a.m_directory, b.m_directory);
473 if (result)
474 return result;
475 }
476 return ConstString::Compare (a.m_filename, b.m_filename);
477}
478
479bool
Jim Ingham96a15962014-11-15 01:54:26 +0000480FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000481{
Jim Ingham87df91b2011-09-23 00:54:11 +0000482 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483 return a.m_filename == b.m_filename;
Jim Ingham96a15962014-11-15 01:54:26 +0000484 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000485 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000486 else
487 {
488 if (a.m_filename != b.m_filename)
489 return false;
490 if (a.m_directory == b.m_directory)
491 return true;
492 ConstString a_without_dots;
493 ConstString b_without_dots;
494
495 RemoveBackupDots (a.m_directory, a_without_dots);
496 RemoveBackupDots (b.m_directory, b_without_dots);
497 return a_without_dots == b_without_dots;
498 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000499}
500
Jim Ingham96a15962014-11-15 01:54:26 +0000501void
502FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
503{
504 const char *input = input_const_str.GetCString();
505 result_const_str.Clear();
506 if (!input || input[0] == '\0')
507 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508
Jim Ingham96a15962014-11-15 01:54:26 +0000509 const char win_sep = '\\';
510 const char unix_sep = '/';
511 char found_sep;
512 const char *win_backup = "\\..";
513 const char *unix_backup = "/..";
514
515 bool is_win = false;
516
517 // Determine the platform for the path (win or unix):
518
519 if (input[0] == win_sep)
520 is_win = true;
521 else if (input[0] == unix_sep)
522 is_win = false;
523 else if (input[1] == ':')
524 is_win = true;
525 else if (strchr(input, unix_sep) != nullptr)
526 is_win = false;
527 else if (strchr(input, win_sep) != nullptr)
528 is_win = true;
529 else
530 {
531 // No separators at all, no reason to do any work here.
532 result_const_str = input_const_str;
533 return;
534 }
535
536 llvm::StringRef backup_sep;
537 if (is_win)
538 {
539 found_sep = win_sep;
540 backup_sep = win_backup;
541 }
542 else
543 {
544 found_sep = unix_sep;
545 backup_sep = unix_backup;
546 }
547
548 llvm::StringRef input_ref(input);
549 llvm::StringRef curpos(input);
550
551 bool had_dots = false;
552 std::string result;
553
554 while (1)
555 {
556 // Start of loop
557 llvm::StringRef before_sep;
558 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
559
560 before_sep = around_sep.first;
561 curpos = around_sep.second;
562
563 if (curpos.empty())
564 {
565 if (had_dots)
566 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000567 while (before_sep.startswith("//"))
568 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000569 if (!before_sep.empty())
570 {
571 result.append(before_sep.data(), before_sep.size());
572 }
573 }
574 break;
575 }
576 had_dots = true;
577
578 unsigned num_backups = 1;
579 while (curpos.startswith(backup_sep))
580 {
581 num_backups++;
582 curpos = curpos.slice(backup_sep.size(), curpos.size());
583 }
584
585 size_t end_pos = before_sep.size();
586 while (num_backups-- > 0)
587 {
588 end_pos = before_sep.rfind(found_sep, end_pos);
589 if (end_pos == llvm::StringRef::npos)
590 {
591 result_const_str = input_const_str;
592 return;
593 }
594 }
595 result.append(before_sep.data(), end_pos);
596 }
597
598 if (had_dots)
599 result_const_str.SetCString(result.c_str());
600 else
601 result_const_str = input_const_str;
602
603 return;
604}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000605
606//------------------------------------------------------------------
607// Dump the object to the supplied stream. If the object contains
608// a valid directory name, it will be displayed followed by a
609// directory delimiter, and the filename.
610//------------------------------------------------------------------
611void
Chaoren Lin70e0cbb2015-05-19 23:11:58 +0000612FileSpec::Dump(Stream *s, bool trailing_slash) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000614 if (s)
615 {
616 m_directory.Dump(s);
Chaoren Lin70e0cbb2015-05-19 23:11:58 +0000617 if ((m_filename || trailing_slash) && m_directory &&
618 !m_directory.GetStringRef().endswith("/"))
Enrico Granata80fcdd42012-11-03 00:09:46 +0000619 s->PutChar('/');
620 m_filename.Dump(s);
621 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622}
623
624//------------------------------------------------------------------
625// Returns true if the file exists.
626//------------------------------------------------------------------
627bool
628FileSpec::Exists () const
629{
630 struct stat file_stats;
631 return GetFileStats (this, &file_stats);
632}
633
Caroline Tice428a9a52010-09-10 04:48:55 +0000634bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000635FileSpec::Readable () const
636{
637 const uint32_t permissions = GetPermissions();
638 if (permissions & eFilePermissionsEveryoneR)
639 return true;
640 return false;
641}
642
643bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000644FileSpec::ResolveExecutableLocation ()
645{
Greg Clayton274060b2010-10-20 20:54:39 +0000646 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000647 {
Greg Clayton58f41712011-01-25 21:32:01 +0000648 const char *file_cstr = m_filename.GetCString();
649 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000650 {
Greg Clayton58f41712011-01-25 21:32:01 +0000651 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000652 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
653 if (!error_or_path)
654 return false;
655 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000656 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000657 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000658 {
Greg Clayton58f41712011-01-25 21:32:01 +0000659 // FindProgramByName returns "." if it can't find the file.
660 if (strcmp (".", dir_ref.data()) == 0)
661 return false;
662
663 m_directory.SetCString (dir_ref.data());
664 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000665 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000666 else
667 {
668 // If FindProgramByName found the file, it returns the directory + filename in its return results.
669 // We need to separate them.
670 FileSpec tmp_file (dir_ref.data(), false);
671 if (tmp_file.Exists())
672 {
673 m_directory = tmp_file.m_directory;
674 return true;
675 }
Caroline Tice391a9602010-09-12 00:10:52 +0000676 }
677 }
678 }
679 }
680
681 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000682}
683
Jim Ingham0909e5f2010-09-16 00:57:33 +0000684bool
685FileSpec::ResolvePath ()
686{
Greg Clayton7481c202010-11-08 00:28:40 +0000687 if (m_is_resolved)
688 return true; // We have already resolved this path
689
690 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000691 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000692 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000693 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000694 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000695 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000696}
697
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698uint64_t
699FileSpec::GetByteSize() const
700{
701 struct stat file_stats;
702 if (GetFileStats (this, &file_stats))
703 return file_stats.st_size;
704 return 0;
705}
706
Zachary Turnerdf62f202014-08-07 17:33:07 +0000707FileSpec::PathSyntax
708FileSpec::GetPathSyntax() const
709{
710 return m_syntax;
711}
712
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713FileSpec::FileType
714FileSpec::GetFileType () const
715{
716 struct stat file_stats;
717 if (GetFileStats (this, &file_stats))
718 {
719 mode_t file_type = file_stats.st_mode & S_IFMT;
720 switch (file_type)
721 {
722 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000724#ifndef _WIN32
725 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 case S_IFSOCK: return eFileTypeSocket;
727 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000728#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 default:
730 break;
731 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000732 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
734 return eFileTypeInvalid;
735}
736
Greg Claytonfbb76342013-11-20 21:07:01 +0000737uint32_t
738FileSpec::GetPermissions () const
739{
740 uint32_t file_permissions = 0;
741 if (*this)
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000742 FileSystem::GetFilePermissions(GetPath().c_str(), file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000743 return file_permissions;
744}
745
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746TimeValue
747FileSpec::GetModificationTime () const
748{
749 TimeValue mod_time;
750 struct stat file_stats;
751 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000752 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000753 return mod_time;
754}
755
756//------------------------------------------------------------------
757// Directory string get accessor.
758//------------------------------------------------------------------
759ConstString &
760FileSpec::GetDirectory()
761{
762 return m_directory;
763}
764
765//------------------------------------------------------------------
766// Directory string const get accessor.
767//------------------------------------------------------------------
768const ConstString &
769FileSpec::GetDirectory() const
770{
771 return m_directory;
772}
773
774//------------------------------------------------------------------
775// Filename string get accessor.
776//------------------------------------------------------------------
777ConstString &
778FileSpec::GetFilename()
779{
780 return m_filename;
781}
782
783//------------------------------------------------------------------
784// Filename string const get accessor.
785//------------------------------------------------------------------
786const ConstString &
787FileSpec::GetFilename() const
788{
789 return m_filename;
790}
791
792//------------------------------------------------------------------
793// Extract the directory and path into a fixed buffer. This is
794// needed as the directory and path are stored in separate string
795// values.
796//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000797size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000798FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000800 if (!path)
801 return 0;
802
Zachary Turnerdf62f202014-08-07 17:33:07 +0000803 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000804 ::snprintf(path, path_max_len, "%s", result.c_str());
805 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806}
807
Greg Claytona44c1e62013-04-29 16:36:27 +0000808std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000809FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000810{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000811 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000812 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000813 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000814}
815
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000816void
817FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
818{
Chaoren Linf34f4102015-05-09 01:21:32 +0000819 StreamString stream;
Chaoren Lin70e0cbb2015-05-19 23:11:58 +0000820 Dump(&stream, false);
Chaoren Linf34f4102015-05-09 01:21:32 +0000821 path.append(stream.GetString().begin(), stream.GetString().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000822 Normalize(path, m_syntax);
823 if (denormalize && !path.empty())
824 DeNormalize(path, m_syntax);
825}
826
Enrico Granataa9dbf432011-10-17 21:45:27 +0000827ConstString
828FileSpec::GetFileNameExtension () const
829{
Greg Clayton1f746072012-08-29 21:13:06 +0000830 if (m_filename)
831 {
832 const char *filename = m_filename.GetCString();
833 const char* dot_pos = strrchr(filename, '.');
834 if (dot_pos && dot_pos[1] != '\0')
835 return ConstString(dot_pos+1);
836 }
837 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000838}
839
840ConstString
841FileSpec::GetFileNameStrippingExtension () const
842{
843 const char *filename = m_filename.GetCString();
844 if (filename == NULL)
845 return ConstString();
846
Johnny Chenf5df5372011-10-18 19:28:30 +0000847 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000848 if (dot_pos == NULL)
849 return m_filename;
850
851 return ConstString(filename, dot_pos-filename);
852}
853
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854//------------------------------------------------------------------
855// Returns a shared pointer to a data buffer that contains all or
856// part of the contents of a file. The data is memory mapped and
857// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000858// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000859// file, and "file_size" bytes will be mapped. If "file_size" is
860// greater than the number of bytes available in the file starting
861// at "file_offset", the number of bytes will be appropriately
862// truncated. The final number of bytes that get mapped can be
863// verified using the DataBuffer::GetByteSize() function.
864//------------------------------------------------------------------
865DataBufferSP
866FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
867{
868 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000869 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000870 if (mmap_data.get())
871 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000872 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
873 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874 data_sp.reset(mmap_data.release());
875 }
876 return data_sp;
877}
878
Greg Clayton736888c2015-02-23 23:47:09 +0000879DataBufferSP
880FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
881{
882 if (FileSystem::IsLocal(*this))
883 return MemoryMapFileContents(file_offset, file_size);
884 else
885 return ReadFileContents(file_offset, file_size, NULL);
886}
887
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888
889//------------------------------------------------------------------
890// Return the size in bytes that this object takes in memory. This
891// returns the size in bytes of this object, not any shared string
892// values it may refer to.
893//------------------------------------------------------------------
894size_t
895FileSpec::MemorySize() const
896{
897 return m_filename.MemorySize() + m_directory.MemorySize();
898}
899
Greg Claytondda4f7b2010-06-30 23:03:03 +0000900
901size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000902FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903{
Greg Clayton4017fa32012-01-06 02:01:06 +0000904 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000905 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 char resolved_path[PATH_MAX];
907 if (GetPath(resolved_path, sizeof(resolved_path)))
908 {
Greg Clayton96c09682012-01-04 22:56:43 +0000909 File file;
910 error = file.Open(resolved_path, File::eOpenOptionRead);
911 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 {
Greg Clayton96c09682012-01-04 22:56:43 +0000913 off_t file_offset_after_seek = file_offset;
914 bytes_read = dst_len;
915 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000916 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000917 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000918 else
919 {
920 error.SetErrorString("invalid file specification");
921 }
922 if (error_ptr)
923 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000924 return bytes_read;
925}
926
927//------------------------------------------------------------------
928// Returns a shared pointer to a data buffer that contains all or
929// part of the contents of a file. The data copies into a heap based
930// buffer that lives in the DataBuffer shared pointer object returned.
931// The data that is cached will start "file_offset" bytes into the
932// file, and "file_size" bytes will be mapped. If "file_size" is
933// greater than the number of bytes available in the file starting
934// at "file_offset", the number of bytes will be appropriately
935// truncated. The final number of bytes that get mapped can be
936// verified using the DataBuffer::GetByteSize() function.
937//------------------------------------------------------------------
938DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000939FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000940{
Greg Clayton4017fa32012-01-06 02:01:06 +0000941 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000942 DataBufferSP data_sp;
943 char resolved_path[PATH_MAX];
944 if (GetPath(resolved_path, sizeof(resolved_path)))
945 {
Greg Clayton96c09682012-01-04 22:56:43 +0000946 File file;
947 error = file.Open(resolved_path, File::eOpenOptionRead);
948 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000949 {
950 const bool null_terminate = false;
951 error = file.Read (file_size, file_offset, null_terminate, data_sp);
952 }
953 }
954 else
955 {
956 error.SetErrorString("invalid file specification");
957 }
958 if (error_ptr)
959 *error_ptr = error;
960 return data_sp;
961}
962
963DataBufferSP
964FileSpec::ReadFileContentsAsCString(Error *error_ptr)
965{
966 Error error;
967 DataBufferSP data_sp;
968 char resolved_path[PATH_MAX];
969 if (GetPath(resolved_path, sizeof(resolved_path)))
970 {
971 File file;
972 error = file.Open(resolved_path, File::eOpenOptionRead);
973 if (error.Success())
974 {
975 off_t offset = 0;
976 size_t length = SIZE_MAX;
977 const bool null_terminate = true;
978 error = file.Read (length, offset, null_terminate, data_sp);
979 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000981 else
982 {
983 error.SetErrorString("invalid file specification");
984 }
985 if (error_ptr)
986 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000987 return data_sp;
988}
989
Greg Clayton58fc50e2010-10-20 22:52:05 +0000990size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991FileSpec::ReadFileLines (STLStringArray &lines)
992{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000994 char path[PATH_MAX];
995 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000997 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998
Greg Clayton58fc50e2010-10-20 22:52:05 +0000999 if (file_stream)
1000 {
1001 std::string line;
1002 while (getline (file_stream, line))
1003 lines.push_back (line);
1004 }
1005 }
1006 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007}
Greg Clayton4272cc72011-02-02 02:24:04 +00001008
1009FileSpec::EnumerateDirectoryResult
1010FileSpec::EnumerateDirectory
1011(
1012 const char *dir_path,
1013 bool find_directories,
1014 bool find_files,
1015 bool find_other,
1016 EnumerateDirectoryCallbackType callback,
1017 void *callback_baton
1018)
1019{
1020 if (dir_path && dir_path[0])
1021 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001022#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001023 std::string szDir(dir_path);
1024 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001025
1026 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001027 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001028
1029 if (hFind == INVALID_HANDLE_VALUE)
1030 {
1031 return eEnumerateDirectoryResultNext;
1032 }
1033
1034 do
1035 {
1036 bool call_callback = false;
1037 FileSpec::FileType file_type = eFileTypeUnknown;
1038 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1039 {
1040 size_t len = strlen(ffd.cFileName);
1041
1042 if (len == 1 && ffd.cFileName[0] == '.')
1043 continue;
1044
1045 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1046 continue;
1047
1048 file_type = eFileTypeDirectory;
1049 call_callback = find_directories;
1050 }
1051 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1052 {
1053 file_type = eFileTypeOther;
1054 call_callback = find_other;
1055 }
1056 else
1057 {
1058 file_type = eFileTypeRegular;
1059 call_callback = find_files;
1060 }
1061 if (call_callback)
1062 {
1063 char child_path[MAX_PATH];
1064 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1065 if (child_path_len < (int)(sizeof(child_path) - 1))
1066 {
1067 // Don't resolve the file type or path
1068 FileSpec child_path_spec (child_path, false);
1069
1070 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1071
1072 switch (result)
1073 {
1074 case eEnumerateDirectoryResultNext:
1075 // Enumerate next entry in the current directory. We just
1076 // exit this switch and will continue enumerating the
1077 // current directory as we currently are...
1078 break;
1079
1080 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1081 if (FileSpec::EnumerateDirectory(child_path,
1082 find_directories,
1083 find_files,
1084 find_other,
1085 callback,
1086 callback_baton) == eEnumerateDirectoryResultQuit)
1087 {
1088 // The subdirectory returned Quit, which means to
1089 // stop all directory enumerations at all levels.
1090 return eEnumerateDirectoryResultQuit;
1091 }
1092 break;
1093
1094 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1095 // Exit from this directory level and tell parent to
1096 // keep enumerating.
1097 return eEnumerateDirectoryResultNext;
1098
1099 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1100 return eEnumerateDirectoryResultQuit;
1101 }
1102 }
1103 }
1104 } while (FindNextFile(hFind, &ffd) != 0);
1105
1106 FindClose(hFind);
1107#else
1108 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001109 if (dir_path_dir.is_valid())
1110 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001111 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1112
Jason Molenda14aef122013-04-04 03:19:27 +00001113 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1114#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1115 if (path_max < __DARWIN_MAXPATHLEN)
1116 path_max = __DARWIN_MAXPATHLEN;
1117#endif
1118 struct dirent *buf, *dp;
1119 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1120
1121 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001122 {
1123 // Only search directories
1124 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1125 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001126 size_t len = strlen(dp->d_name);
1127
1128 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001129 continue;
1130
Greg Claytone0f3c022011-02-07 17:41:11 +00001131 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001132 continue;
1133 }
1134
1135 bool call_callback = false;
1136 FileSpec::FileType file_type = eFileTypeUnknown;
1137
1138 switch (dp->d_type)
1139 {
1140 default:
1141 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1142 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1143 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1144 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1145 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1146 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1147 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1148 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001149#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001150 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001151#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001152 }
1153
1154 if (call_callback)
1155 {
1156 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001157
1158 // Don't make paths with "/foo//bar", that just confuses everybody.
1159 int child_path_len;
1160 if (dir_path_last_char == '/')
1161 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1162 else
1163 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1164
Johnny Chen44805302011-07-19 19:48:13 +00001165 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001166 {
1167 // Don't resolve the file type or path
1168 FileSpec child_path_spec (child_path, false);
1169
1170 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1171
1172 switch (result)
1173 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001174 case eEnumerateDirectoryResultNext:
1175 // Enumerate next entry in the current directory. We just
1176 // exit this switch and will continue enumerating the
1177 // current directory as we currently are...
1178 break;
1179
1180 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1181 if (FileSpec::EnumerateDirectory (child_path,
1182 find_directories,
1183 find_files,
1184 find_other,
1185 callback,
1186 callback_baton) == eEnumerateDirectoryResultQuit)
1187 {
1188 // The subdirectory returned Quit, which means to
1189 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001190 if (buf)
1191 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001192 return eEnumerateDirectoryResultQuit;
1193 }
1194 break;
1195
1196 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1197 // Exit from this directory level and tell parent to
1198 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001199 if (buf)
1200 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001201 return eEnumerateDirectoryResultNext;
1202
1203 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001204 if (buf)
1205 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001206 return eEnumerateDirectoryResultQuit;
1207 }
1208 }
1209 }
1210 }
Jason Molenda14aef122013-04-04 03:19:27 +00001211 if (buf)
1212 {
1213 free (buf);
1214 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001215 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001216#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001217 }
1218 // By default when exiting a directory, we tell the parent enumeration
1219 // to continue enumerating.
1220 return eEnumerateDirectoryResultNext;
1221}
1222
Daniel Maleae0f8f572013-08-26 23:57:52 +00001223FileSpec
1224FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1225{
1226 const bool resolve = false;
1227 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1228 return FileSpec(new_path,resolve);
1229 StreamString stream;
1230 if (m_filename.IsEmpty())
1231 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1232 else if (m_directory.IsEmpty())
1233 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1234 else
1235 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1236 return FileSpec(stream.GetData(),resolve);
1237}
1238
1239FileSpec
1240FileSpec::CopyByRemovingLastPathComponent () const
1241{
1242 const bool resolve = false;
1243 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1244 return FileSpec("",resolve);
1245 if (m_directory.IsEmpty())
1246 return FileSpec("",resolve);
1247 if (m_filename.IsEmpty())
1248 {
1249 const char* dir_cstr = m_directory.GetCString();
1250 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1251
1252 // check for obvious cases before doing the full thing
1253 if (!last_slash_ptr)
1254 return FileSpec("",resolve);
1255 if (last_slash_ptr == dir_cstr)
1256 return FileSpec("/",resolve);
1257
1258 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1259 ConstString new_path(dir_cstr,last_slash_pos);
1260 return FileSpec(new_path.GetCString(),resolve);
1261 }
1262 else
1263 return FileSpec(m_directory.GetCString(),resolve);
1264}
1265
Greg Claytonfbb76342013-11-20 21:07:01 +00001266ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001267FileSpec::GetLastPathComponent () const
1268{
Greg Claytonfbb76342013-11-20 21:07:01 +00001269 if (m_filename)
1270 return m_filename;
1271 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001272 {
1273 const char* dir_cstr = m_directory.GetCString();
1274 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1275 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001276 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001277 if (last_slash_ptr == dir_cstr)
1278 {
1279 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001280 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001281 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001282 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001283 }
1284 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001285 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001286 const char* penultimate_slash_ptr = last_slash_ptr;
1287 while (*penultimate_slash_ptr)
1288 {
1289 --penultimate_slash_ptr;
1290 if (penultimate_slash_ptr == dir_cstr)
1291 break;
1292 if (*penultimate_slash_ptr == '/')
1293 break;
1294 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001295 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1296 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001297 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001298 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001299}
1300
1301void
1302FileSpec::AppendPathComponent (const char *new_path)
1303{
1304 const bool resolve = false;
1305 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1306 {
1307 SetFile(new_path,resolve);
1308 return;
1309 }
1310 StreamString stream;
1311 if (m_filename.IsEmpty())
1312 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1313 else if (m_directory.IsEmpty())
1314 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1315 else
1316 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1317 SetFile(stream.GetData(), resolve);
1318}
1319
1320void
1321FileSpec::RemoveLastPathComponent ()
1322{
1323 const bool resolve = false;
1324 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1325 {
1326 SetFile("",resolve);
1327 return;
1328 }
1329 if (m_directory.IsEmpty())
1330 {
1331 SetFile("",resolve);
1332 return;
1333 }
1334 if (m_filename.IsEmpty())
1335 {
1336 const char* dir_cstr = m_directory.GetCString();
1337 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1338
1339 // check for obvious cases before doing the full thing
1340 if (!last_slash_ptr)
1341 {
1342 SetFile("",resolve);
1343 return;
1344 }
1345 if (last_slash_ptr == dir_cstr)
1346 {
1347 SetFile("/",resolve);
1348 return;
1349 }
1350 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1351 ConstString new_path(dir_cstr,last_slash_pos);
1352 SetFile(new_path.GetCString(),resolve);
1353 }
1354 else
1355 SetFile(m_directory.GetCString(),resolve);
1356}
Greg Clayton1f746072012-08-29 21:13:06 +00001357//------------------------------------------------------------------
1358/// Returns true if the filespec represents an implementation source
1359/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1360/// extension).
1361///
1362/// @return
1363/// \b true if the filespec represents an implementation source
1364/// file, \b false otherwise.
1365//------------------------------------------------------------------
1366bool
1367FileSpec::IsSourceImplementationFile () const
1368{
1369 ConstString extension (GetFileNameExtension());
1370 if (extension)
1371 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001372 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 +00001373 return g_source_file_regex.Execute (extension.GetCString());
1374 }
1375 return false;
1376}
1377
Greg Claytona0ca6602012-10-18 16:33:33 +00001378bool
1379FileSpec::IsRelativeToCurrentWorkingDirectory () const
1380{
Zachary Turner270e99a2014-12-08 21:36:42 +00001381 const char *dir = m_directory.GetCString();
1382 llvm::StringRef directory(dir ? dir : "");
1383
1384 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001385 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001386 if (m_syntax == ePathSyntaxWindows)
Greg Claytona0ca6602012-10-18 16:33:33 +00001387 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001388 if (directory.size() >= 2 && directory[1] == ':')
1389 return false;
1390 if (directory[0] == '/')
1391 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001392 return true;
1393 }
Zachary Turner270e99a2014-12-08 21:36:42 +00001394 else
1395 {
1396 // If the path doesn't start with '/' or '~', return true
1397 switch (directory[0])
1398 {
1399 case '/':
1400 case '~':
1401 return false;
1402 default:
1403 return true;
1404 }
1405 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001406 }
1407 else if (m_filename)
1408 {
1409 // No directory, just a basename, return true
1410 return true;
1411 }
1412 return false;
1413}