blob: 062cdcd98b4bae778fc7007e73fc0d06c7a0f5aa [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
612FileSpec::Dump(Stream *s) const
613{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000614 if (s)
615 {
616 m_directory.Dump(s);
Chaoren Linf34f4102015-05-09 01:21:32 +0000617 if (m_directory && m_directory.GetStringRef().back() != '/')
Enrico Granata80fcdd42012-11-03 00:09:46 +0000618 s->PutChar('/');
619 m_filename.Dump(s);
620 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621}
622
623//------------------------------------------------------------------
624// Returns true if the file exists.
625//------------------------------------------------------------------
626bool
627FileSpec::Exists () const
628{
629 struct stat file_stats;
630 return GetFileStats (this, &file_stats);
631}
632
Caroline Tice428a9a52010-09-10 04:48:55 +0000633bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000634FileSpec::Readable () const
635{
636 const uint32_t permissions = GetPermissions();
637 if (permissions & eFilePermissionsEveryoneR)
638 return true;
639 return false;
640}
641
642bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000643FileSpec::ResolveExecutableLocation ()
644{
Greg Clayton274060b2010-10-20 20:54:39 +0000645 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000646 {
Greg Clayton58f41712011-01-25 21:32:01 +0000647 const char *file_cstr = m_filename.GetCString();
648 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000649 {
Greg Clayton58f41712011-01-25 21:32:01 +0000650 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000651 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
652 if (!error_or_path)
653 return false;
654 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000655 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000656 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000657 {
Greg Clayton58f41712011-01-25 21:32:01 +0000658 // FindProgramByName returns "." if it can't find the file.
659 if (strcmp (".", dir_ref.data()) == 0)
660 return false;
661
662 m_directory.SetCString (dir_ref.data());
663 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000664 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000665 else
666 {
667 // If FindProgramByName found the file, it returns the directory + filename in its return results.
668 // We need to separate them.
669 FileSpec tmp_file (dir_ref.data(), false);
670 if (tmp_file.Exists())
671 {
672 m_directory = tmp_file.m_directory;
673 return true;
674 }
Caroline Tice391a9602010-09-12 00:10:52 +0000675 }
676 }
677 }
678 }
679
680 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000681}
682
Jim Ingham0909e5f2010-09-16 00:57:33 +0000683bool
684FileSpec::ResolvePath ()
685{
Greg Clayton7481c202010-11-08 00:28:40 +0000686 if (m_is_resolved)
687 return true; // We have already resolved this path
688
689 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000690 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000691 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000692 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000693 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000694 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000695}
696
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697uint64_t
698FileSpec::GetByteSize() const
699{
700 struct stat file_stats;
701 if (GetFileStats (this, &file_stats))
702 return file_stats.st_size;
703 return 0;
704}
705
Zachary Turnerdf62f202014-08-07 17:33:07 +0000706FileSpec::PathSyntax
707FileSpec::GetPathSyntax() const
708{
709 return m_syntax;
710}
711
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712FileSpec::FileType
713FileSpec::GetFileType () const
714{
715 struct stat file_stats;
716 if (GetFileStats (this, &file_stats))
717 {
718 mode_t file_type = file_stats.st_mode & S_IFMT;
719 switch (file_type)
720 {
721 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000723#ifndef _WIN32
724 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 case S_IFSOCK: return eFileTypeSocket;
726 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000727#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728 default:
729 break;
730 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000731 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 }
733 return eFileTypeInvalid;
734}
735
Greg Claytonfbb76342013-11-20 21:07:01 +0000736uint32_t
737FileSpec::GetPermissions () const
738{
739 uint32_t file_permissions = 0;
740 if (*this)
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000741 FileSystem::GetFilePermissions(GetPath().c_str(), file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000742 return file_permissions;
743}
744
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745TimeValue
746FileSpec::GetModificationTime () const
747{
748 TimeValue mod_time;
749 struct stat file_stats;
750 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000751 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752 return mod_time;
753}
754
755//------------------------------------------------------------------
756// Directory string get accessor.
757//------------------------------------------------------------------
758ConstString &
759FileSpec::GetDirectory()
760{
761 return m_directory;
762}
763
764//------------------------------------------------------------------
765// Directory string const get accessor.
766//------------------------------------------------------------------
767const ConstString &
768FileSpec::GetDirectory() const
769{
770 return m_directory;
771}
772
773//------------------------------------------------------------------
774// Filename string get accessor.
775//------------------------------------------------------------------
776ConstString &
777FileSpec::GetFilename()
778{
779 return m_filename;
780}
781
782//------------------------------------------------------------------
783// Filename string const get accessor.
784//------------------------------------------------------------------
785const ConstString &
786FileSpec::GetFilename() const
787{
788 return m_filename;
789}
790
791//------------------------------------------------------------------
792// Extract the directory and path into a fixed buffer. This is
793// needed as the directory and path are stored in separate string
794// values.
795//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000796size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000797FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000799 if (!path)
800 return 0;
801
Zachary Turnerdf62f202014-08-07 17:33:07 +0000802 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000803 ::snprintf(path, path_max_len, "%s", result.c_str());
804 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805}
806
Greg Claytona44c1e62013-04-29 16:36:27 +0000807std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000808FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000809{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000810 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000811 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000812 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000813}
814
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000815void
816FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
817{
Chaoren Linf34f4102015-05-09 01:21:32 +0000818 StreamString stream;
819 Dump(&stream);
820 path.append(stream.GetString().begin(), stream.GetString().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000821 Normalize(path, m_syntax);
822 if (denormalize && !path.empty())
823 DeNormalize(path, m_syntax);
824}
825
Enrico Granataa9dbf432011-10-17 21:45:27 +0000826ConstString
827FileSpec::GetFileNameExtension () const
828{
Greg Clayton1f746072012-08-29 21:13:06 +0000829 if (m_filename)
830 {
831 const char *filename = m_filename.GetCString();
832 const char* dot_pos = strrchr(filename, '.');
833 if (dot_pos && dot_pos[1] != '\0')
834 return ConstString(dot_pos+1);
835 }
836 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000837}
838
839ConstString
840FileSpec::GetFileNameStrippingExtension () const
841{
842 const char *filename = m_filename.GetCString();
843 if (filename == NULL)
844 return ConstString();
845
Johnny Chenf5df5372011-10-18 19:28:30 +0000846 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000847 if (dot_pos == NULL)
848 return m_filename;
849
850 return ConstString(filename, dot_pos-filename);
851}
852
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853//------------------------------------------------------------------
854// Returns a shared pointer to a data buffer that contains all or
855// part of the contents of a file. The data is memory mapped and
856// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000857// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858// file, and "file_size" bytes will be mapped. If "file_size" is
859// greater than the number of bytes available in the file starting
860// at "file_offset", the number of bytes will be appropriately
861// truncated. The final number of bytes that get mapped can be
862// verified using the DataBuffer::GetByteSize() function.
863//------------------------------------------------------------------
864DataBufferSP
865FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
866{
867 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000868 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 if (mmap_data.get())
870 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000871 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
872 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873 data_sp.reset(mmap_data.release());
874 }
875 return data_sp;
876}
877
Greg Clayton736888c2015-02-23 23:47:09 +0000878DataBufferSP
879FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
880{
881 if (FileSystem::IsLocal(*this))
882 return MemoryMapFileContents(file_offset, file_size);
883 else
884 return ReadFileContents(file_offset, file_size, NULL);
885}
886
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887
888//------------------------------------------------------------------
889// Return the size in bytes that this object takes in memory. This
890// returns the size in bytes of this object, not any shared string
891// values it may refer to.
892//------------------------------------------------------------------
893size_t
894FileSpec::MemorySize() const
895{
896 return m_filename.MemorySize() + m_directory.MemorySize();
897}
898
Greg Claytondda4f7b2010-06-30 23:03:03 +0000899
900size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000901FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000902{
Greg Clayton4017fa32012-01-06 02:01:06 +0000903 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000904 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 char resolved_path[PATH_MAX];
906 if (GetPath(resolved_path, sizeof(resolved_path)))
907 {
Greg Clayton96c09682012-01-04 22:56:43 +0000908 File file;
909 error = file.Open(resolved_path, File::eOpenOptionRead);
910 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000911 {
Greg Clayton96c09682012-01-04 22:56:43 +0000912 off_t file_offset_after_seek = file_offset;
913 bytes_read = dst_len;
914 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000915 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000916 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000917 else
918 {
919 error.SetErrorString("invalid file specification");
920 }
921 if (error_ptr)
922 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000923 return bytes_read;
924}
925
926//------------------------------------------------------------------
927// Returns a shared pointer to a data buffer that contains all or
928// part of the contents of a file. The data copies into a heap based
929// buffer that lives in the DataBuffer shared pointer object returned.
930// The data that is cached will start "file_offset" bytes into the
931// file, and "file_size" bytes will be mapped. If "file_size" is
932// greater than the number of bytes available in the file starting
933// at "file_offset", the number of bytes will be appropriately
934// truncated. The final number of bytes that get mapped can be
935// verified using the DataBuffer::GetByteSize() function.
936//------------------------------------------------------------------
937DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000938FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000939{
Greg Clayton4017fa32012-01-06 02:01:06 +0000940 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000941 DataBufferSP data_sp;
942 char resolved_path[PATH_MAX];
943 if (GetPath(resolved_path, sizeof(resolved_path)))
944 {
Greg Clayton96c09682012-01-04 22:56:43 +0000945 File file;
946 error = file.Open(resolved_path, File::eOpenOptionRead);
947 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000948 {
949 const bool null_terminate = false;
950 error = file.Read (file_size, file_offset, null_terminate, data_sp);
951 }
952 }
953 else
954 {
955 error.SetErrorString("invalid file specification");
956 }
957 if (error_ptr)
958 *error_ptr = error;
959 return data_sp;
960}
961
962DataBufferSP
963FileSpec::ReadFileContentsAsCString(Error *error_ptr)
964{
965 Error error;
966 DataBufferSP data_sp;
967 char resolved_path[PATH_MAX];
968 if (GetPath(resolved_path, sizeof(resolved_path)))
969 {
970 File file;
971 error = file.Open(resolved_path, File::eOpenOptionRead);
972 if (error.Success())
973 {
974 off_t offset = 0;
975 size_t length = SIZE_MAX;
976 const bool null_terminate = true;
977 error = file.Read (length, offset, null_terminate, data_sp);
978 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000980 else
981 {
982 error.SetErrorString("invalid file specification");
983 }
984 if (error_ptr)
985 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986 return data_sp;
987}
988
Greg Clayton58fc50e2010-10-20 22:52:05 +0000989size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990FileSpec::ReadFileLines (STLStringArray &lines)
991{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000993 char path[PATH_MAX];
994 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000996 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997
Greg Clayton58fc50e2010-10-20 22:52:05 +0000998 if (file_stream)
999 {
1000 std::string line;
1001 while (getline (file_stream, line))
1002 lines.push_back (line);
1003 }
1004 }
1005 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006}
Greg Clayton4272cc72011-02-02 02:24:04 +00001007
1008FileSpec::EnumerateDirectoryResult
1009FileSpec::EnumerateDirectory
1010(
1011 const char *dir_path,
1012 bool find_directories,
1013 bool find_files,
1014 bool find_other,
1015 EnumerateDirectoryCallbackType callback,
1016 void *callback_baton
1017)
1018{
1019 if (dir_path && dir_path[0])
1020 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001021#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001022 std::string szDir(dir_path);
1023 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001024
1025 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001026 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001027
1028 if (hFind == INVALID_HANDLE_VALUE)
1029 {
1030 return eEnumerateDirectoryResultNext;
1031 }
1032
1033 do
1034 {
1035 bool call_callback = false;
1036 FileSpec::FileType file_type = eFileTypeUnknown;
1037 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1038 {
1039 size_t len = strlen(ffd.cFileName);
1040
1041 if (len == 1 && ffd.cFileName[0] == '.')
1042 continue;
1043
1044 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1045 continue;
1046
1047 file_type = eFileTypeDirectory;
1048 call_callback = find_directories;
1049 }
1050 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1051 {
1052 file_type = eFileTypeOther;
1053 call_callback = find_other;
1054 }
1055 else
1056 {
1057 file_type = eFileTypeRegular;
1058 call_callback = find_files;
1059 }
1060 if (call_callback)
1061 {
1062 char child_path[MAX_PATH];
1063 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1064 if (child_path_len < (int)(sizeof(child_path) - 1))
1065 {
1066 // Don't resolve the file type or path
1067 FileSpec child_path_spec (child_path, false);
1068
1069 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1070
1071 switch (result)
1072 {
1073 case eEnumerateDirectoryResultNext:
1074 // Enumerate next entry in the current directory. We just
1075 // exit this switch and will continue enumerating the
1076 // current directory as we currently are...
1077 break;
1078
1079 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1080 if (FileSpec::EnumerateDirectory(child_path,
1081 find_directories,
1082 find_files,
1083 find_other,
1084 callback,
1085 callback_baton) == eEnumerateDirectoryResultQuit)
1086 {
1087 // The subdirectory returned Quit, which means to
1088 // stop all directory enumerations at all levels.
1089 return eEnumerateDirectoryResultQuit;
1090 }
1091 break;
1092
1093 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1094 // Exit from this directory level and tell parent to
1095 // keep enumerating.
1096 return eEnumerateDirectoryResultNext;
1097
1098 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1099 return eEnumerateDirectoryResultQuit;
1100 }
1101 }
1102 }
1103 } while (FindNextFile(hFind, &ffd) != 0);
1104
1105 FindClose(hFind);
1106#else
1107 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001108 if (dir_path_dir.is_valid())
1109 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001110 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1111
Jason Molenda14aef122013-04-04 03:19:27 +00001112 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1113#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1114 if (path_max < __DARWIN_MAXPATHLEN)
1115 path_max = __DARWIN_MAXPATHLEN;
1116#endif
1117 struct dirent *buf, *dp;
1118 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1119
1120 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001121 {
1122 // Only search directories
1123 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1124 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001125 size_t len = strlen(dp->d_name);
1126
1127 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001128 continue;
1129
Greg Claytone0f3c022011-02-07 17:41:11 +00001130 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001131 continue;
1132 }
1133
1134 bool call_callback = false;
1135 FileSpec::FileType file_type = eFileTypeUnknown;
1136
1137 switch (dp->d_type)
1138 {
1139 default:
1140 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1141 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1142 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1143 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1144 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1145 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1146 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1147 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001148#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001150#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001151 }
1152
1153 if (call_callback)
1154 {
1155 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001156
1157 // Don't make paths with "/foo//bar", that just confuses everybody.
1158 int child_path_len;
1159 if (dir_path_last_char == '/')
1160 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1161 else
1162 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1163
Johnny Chen44805302011-07-19 19:48:13 +00001164 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001165 {
1166 // Don't resolve the file type or path
1167 FileSpec child_path_spec (child_path, false);
1168
1169 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1170
1171 switch (result)
1172 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001173 case eEnumerateDirectoryResultNext:
1174 // Enumerate next entry in the current directory. We just
1175 // exit this switch and will continue enumerating the
1176 // current directory as we currently are...
1177 break;
1178
1179 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1180 if (FileSpec::EnumerateDirectory (child_path,
1181 find_directories,
1182 find_files,
1183 find_other,
1184 callback,
1185 callback_baton) == eEnumerateDirectoryResultQuit)
1186 {
1187 // The subdirectory returned Quit, which means to
1188 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001189 if (buf)
1190 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001191 return eEnumerateDirectoryResultQuit;
1192 }
1193 break;
1194
1195 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1196 // Exit from this directory level and tell parent to
1197 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001198 if (buf)
1199 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001200 return eEnumerateDirectoryResultNext;
1201
1202 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001203 if (buf)
1204 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001205 return eEnumerateDirectoryResultQuit;
1206 }
1207 }
1208 }
1209 }
Jason Molenda14aef122013-04-04 03:19:27 +00001210 if (buf)
1211 {
1212 free (buf);
1213 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001214 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001215#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001216 }
1217 // By default when exiting a directory, we tell the parent enumeration
1218 // to continue enumerating.
1219 return eEnumerateDirectoryResultNext;
1220}
1221
Daniel Maleae0f8f572013-08-26 23:57:52 +00001222FileSpec
1223FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1224{
1225 const bool resolve = false;
1226 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1227 return FileSpec(new_path,resolve);
1228 StreamString stream;
1229 if (m_filename.IsEmpty())
1230 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1231 else if (m_directory.IsEmpty())
1232 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1233 else
1234 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1235 return FileSpec(stream.GetData(),resolve);
1236}
1237
1238FileSpec
1239FileSpec::CopyByRemovingLastPathComponent () const
1240{
1241 const bool resolve = false;
1242 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1243 return FileSpec("",resolve);
1244 if (m_directory.IsEmpty())
1245 return FileSpec("",resolve);
1246 if (m_filename.IsEmpty())
1247 {
1248 const char* dir_cstr = m_directory.GetCString();
1249 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1250
1251 // check for obvious cases before doing the full thing
1252 if (!last_slash_ptr)
1253 return FileSpec("",resolve);
1254 if (last_slash_ptr == dir_cstr)
1255 return FileSpec("/",resolve);
1256
1257 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1258 ConstString new_path(dir_cstr,last_slash_pos);
1259 return FileSpec(new_path.GetCString(),resolve);
1260 }
1261 else
1262 return FileSpec(m_directory.GetCString(),resolve);
1263}
1264
Greg Claytonfbb76342013-11-20 21:07:01 +00001265ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001266FileSpec::GetLastPathComponent () const
1267{
Greg Claytonfbb76342013-11-20 21:07:01 +00001268 if (m_filename)
1269 return m_filename;
1270 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001271 {
1272 const char* dir_cstr = m_directory.GetCString();
1273 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1274 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001275 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001276 if (last_slash_ptr == dir_cstr)
1277 {
1278 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001279 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001280 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001281 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001282 }
1283 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001284 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001285 const char* penultimate_slash_ptr = last_slash_ptr;
1286 while (*penultimate_slash_ptr)
1287 {
1288 --penultimate_slash_ptr;
1289 if (penultimate_slash_ptr == dir_cstr)
1290 break;
1291 if (*penultimate_slash_ptr == '/')
1292 break;
1293 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001294 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1295 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001296 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001297 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001298}
1299
1300void
1301FileSpec::AppendPathComponent (const char *new_path)
1302{
1303 const bool resolve = false;
1304 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1305 {
1306 SetFile(new_path,resolve);
1307 return;
1308 }
1309 StreamString stream;
1310 if (m_filename.IsEmpty())
1311 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1312 else if (m_directory.IsEmpty())
1313 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1314 else
1315 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1316 SetFile(stream.GetData(), resolve);
1317}
1318
1319void
1320FileSpec::RemoveLastPathComponent ()
1321{
1322 const bool resolve = false;
1323 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1324 {
1325 SetFile("",resolve);
1326 return;
1327 }
1328 if (m_directory.IsEmpty())
1329 {
1330 SetFile("",resolve);
1331 return;
1332 }
1333 if (m_filename.IsEmpty())
1334 {
1335 const char* dir_cstr = m_directory.GetCString();
1336 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1337
1338 // check for obvious cases before doing the full thing
1339 if (!last_slash_ptr)
1340 {
1341 SetFile("",resolve);
1342 return;
1343 }
1344 if (last_slash_ptr == dir_cstr)
1345 {
1346 SetFile("/",resolve);
1347 return;
1348 }
1349 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1350 ConstString new_path(dir_cstr,last_slash_pos);
1351 SetFile(new_path.GetCString(),resolve);
1352 }
1353 else
1354 SetFile(m_directory.GetCString(),resolve);
1355}
Greg Clayton1f746072012-08-29 21:13:06 +00001356//------------------------------------------------------------------
1357/// Returns true if the filespec represents an implementation source
1358/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1359/// extension).
1360///
1361/// @return
1362/// \b true if the filespec represents an implementation source
1363/// file, \b false otherwise.
1364//------------------------------------------------------------------
1365bool
1366FileSpec::IsSourceImplementationFile () const
1367{
1368 ConstString extension (GetFileNameExtension());
1369 if (extension)
1370 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001371 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 +00001372 return g_source_file_regex.Execute (extension.GetCString());
1373 }
1374 return false;
1375}
1376
Greg Claytona0ca6602012-10-18 16:33:33 +00001377bool
1378FileSpec::IsRelativeToCurrentWorkingDirectory () const
1379{
Zachary Turner270e99a2014-12-08 21:36:42 +00001380 const char *dir = m_directory.GetCString();
1381 llvm::StringRef directory(dir ? dir : "");
1382
1383 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001384 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001385 if (m_syntax == ePathSyntaxWindows)
Greg Claytona0ca6602012-10-18 16:33:33 +00001386 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001387 if (directory.size() >= 2 && directory[1] == ':')
1388 return false;
1389 if (directory[0] == '/')
1390 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001391 return true;
1392 }
Zachary Turner270e99a2014-12-08 21:36:42 +00001393 else
1394 {
1395 // If the path doesn't start with '/' or '~', return true
1396 switch (directory[0])
1397 {
1398 case '/':
1399 case '~':
1400 return false;
1401 default:
1402 return true;
1403 }
1404 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001405 }
1406 else if (m_filename)
1407 {
1408 // No directory, just a basename, return true
1409 return true;
1410 }
1411 return false;
1412}