blob: 65d6543c86e5312b9d6a99a899291091d9fc2dac [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
Chaoren Lin1c614fe2015-05-28 17:02:45 +000050namespace {
51
52bool
53PathSyntaxIsPosix(FileSpec::PathSyntax syntax)
54{
55 return (syntax == FileSpec::ePathSyntaxPosix ||
56 (syntax == FileSpec::ePathSyntaxHostNative &&
57 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
58}
59
60char
61GetPathSeparator(FileSpec::PathSyntax syntax)
62{
63 return PathSyntaxIsPosix(syntax) ? '/' : '\\';
64}
65
66void
67Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
68{
69 if (PathSyntaxIsPosix(syntax)) return;
70
71 std::replace(path.begin(), path.end(), '\\', '/');
72 // Windows path can have \\ slashes which can be changed by replace
73 // call above to //. Here we remove the duplicate.
74 auto iter = std::unique ( path.begin(), path.end(),
75 []( char &c1, char &c2 ){
76 return (c1 == '/' && c2 == '/');});
77 path.erase(iter, path.end());
78}
79
80void
81Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
82{
83 if (PathSyntaxIsPosix(syntax)) return;
84
85 std::replace(path.begin(), path.end(), '/', '\\');
86}
87
88bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
90{
91 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000092 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093 return ::stat (resolved_path, stats_ptr) == 0;
94 return false;
95}
96
Chaoren Lin1c614fe2015-05-28 17:02:45 +000097}
98
Jim Inghamf818ca32010-07-01 01:48:53 +000099// Resolves the username part of a path of the form ~user/other/directories, and
Jim Inghamead45cc2014-09-12 23:50:36 +0000100// writes the result into dst_path. This will also resolve "~" to the current user.
101// If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
Zachary Turner3f559742014-08-07 17:33:36 +0000102void
103FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
Jim Inghamf818ca32010-07-01 01:48:53 +0000104{
Zachary Turner3f559742014-08-07 17:33:36 +0000105#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
106 if (path.empty() || path[0] != '~')
107 return;
Jim Inghamf818ca32010-07-01 01:48:53 +0000108
Jason Molenda3bc66f12015-01-20 04:20:42 +0000109 llvm::StringRef path_str(path.data(), path.size());
Zachary Turner3f559742014-08-07 17:33:36 +0000110 size_t slash_pos = path_str.find_first_of("/", 1);
Jim Inghamead45cc2014-09-12 23:50:36 +0000111 if (slash_pos == 1 || path.size() == 1)
Jim Inghamf818ca32010-07-01 01:48:53 +0000112 {
Jim Ingham2f21bbc2014-09-12 23:04:40 +0000113 // A path of ~/ resolves to the current user's home dir
Zachary Turner3f559742014-08-07 17:33:36 +0000114 llvm::SmallString<64> home_dir;
115 if (!llvm::sys::path::home_directory(home_dir))
116 return;
117
118 // Overwrite the ~ with the first character of the homedir, and insert
119 // the rest. This way we only trigger one move, whereas an insert
120 // followed by a delete (or vice versa) would trigger two.
121 path[0] = home_dir[0];
122 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
123 return;
124 }
125
126 auto username_begin = path.begin()+1;
127 auto username_end = (slash_pos == llvm::StringRef::npos)
128 ? path.end()
129 : (path.begin() + slash_pos);
130 size_t replacement_length = std::distance(path.begin(), username_end);
131
132 llvm::SmallString<20> username(username_begin, username_end);
133 struct passwd *user_entry = ::getpwnam(username.c_str());
134 if (user_entry != nullptr)
135 {
136 // Copy over the first n characters of the path, where n is the smaller of the length
137 // of the home directory and the slash pos.
138 llvm::StringRef homedir(user_entry->pw_dir);
139 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
140 auto src_begin = homedir.begin();
141 auto src_end = src_begin + initial_copy_length;
142 std::copy(src_begin, src_end, path.begin());
143 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000144 {
Zachary Turner3f559742014-08-07 17:33:36 +0000145 // We copied the entire home directory, but the ~username portion of the path was
146 // longer, so there's characters that need to be removed.
147 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000148 }
Zachary Turner3f559742014-08-07 17:33:36 +0000149 else if (replacement_length < homedir.size())
150 {
151 // We copied all the way up to the slash in the destination, but there's still more
152 // characters that need to be inserted.
153 path.insert(username_end, src_end, homedir.end());
154 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000155 }
156 else
157 {
Zachary Turner3f559742014-08-07 17:33:36 +0000158 // Unable to resolve username (user doesn't exist?)
159 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000160 }
Zachary Turner3f559742014-08-07 17:33:36 +0000161#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000162}
163
Greg Claytonc982c762010-07-09 20:39:50 +0000164size_t
Jim Ingham84363072011-02-08 23:24:09 +0000165FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
166{
167#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
168 size_t extant_entries = matches.GetSize();
169
170 setpwent();
171 struct passwd *user_entry;
172 const char *name_start = partial_name + 1;
173 std::set<std::string> name_list;
174
175 while ((user_entry = getpwent()) != NULL)
176 {
177 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
178 {
179 std::string tmp_buf("~");
180 tmp_buf.append(user_entry->pw_name);
181 tmp_buf.push_back('/');
182 name_list.insert(tmp_buf);
183 }
184 }
185 std::set<std::string>::iterator pos, end = name_list.end();
186 for (pos = name_list.begin(); pos != end; pos++)
187 {
188 matches.AppendString((*pos).c_str());
189 }
190 return matches.GetSize() - extant_entries;
191#else
192 // Resolving home directories is not supported, just copy the path...
193 return 0;
194#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
195}
196
Zachary Turner3f559742014-08-07 17:33:36 +0000197void
198FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199{
Zachary Turner3f559742014-08-07 17:33:36 +0000200 if (path.empty())
201 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202
Greg Clayton45319462011-02-08 00:35:34 +0000203#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000204 if (path[0] == '~')
205 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000206#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207
Jason Molenda671a29d2015-02-25 02:35:25 +0000208 // Save a copy of the original path that's passed in
209 llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end());
210
Zachary Turner3f559742014-08-07 17:33:36 +0000211 llvm::sys::fs::make_absolute(path);
Jason Molenda671a29d2015-02-25 02:35:25 +0000212
213
214 path.push_back(0); // Be sure we have a nul terminated string
215 path.pop_back();
216 struct stat file_stats;
217 if (::stat (path.data(), &file_stats) != 0)
218 {
219 path.clear();
220 path.append(original_path.begin(), original_path.end());
221 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000222}
223
Jason Molenda68c85212014-10-15 03:04:33 +0000224FileSpec::FileSpec() :
225 m_directory(),
226 m_filename(),
227 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228{
229}
230
231//------------------------------------------------------------------
232// Default constructor that can take an optional full path to a
233// file on disk.
234//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000235FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000236 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000237 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000238 m_is_resolved(false),
239 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000240{
241 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000242 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000243}
244
Chaoren Linf34f4102015-05-09 01:21:32 +0000245FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
Chaoren Lind3173f32015-05-29 19:52:29 +0000246 FileSpec{pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix}
247{
248}
249
250FileSpec::FileSpec(const std::string &path, bool resolve_path, PathSyntax syntax) :
251 FileSpec{path.c_str(), resolve_path, syntax}
252{
253}
254
255FileSpec::FileSpec(const std::string &path, bool resolve_path, ArchSpec arch) :
256 FileSpec{path.c_str(), resolve_path, arch}
Chaoren Linf34f4102015-05-09 01:21:32 +0000257{
258}
259
Jim Ingham0909e5f2010-09-16 00:57:33 +0000260//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261// Copy constructor
262//------------------------------------------------------------------
263FileSpec::FileSpec(const FileSpec& rhs) :
264 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000265 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000266 m_is_resolved (rhs.m_is_resolved),
267 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268{
269}
270
271//------------------------------------------------------------------
272// Copy constructor
273//------------------------------------------------------------------
274FileSpec::FileSpec(const FileSpec* rhs) :
275 m_directory(),
276 m_filename()
277{
278 if (rhs)
279 *this = *rhs;
280}
281
282//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000283// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284//------------------------------------------------------------------
285FileSpec::~FileSpec()
286{
287}
288
289//------------------------------------------------------------------
290// Assignment operator.
291//------------------------------------------------------------------
292const FileSpec&
293FileSpec::operator= (const FileSpec& rhs)
294{
295 if (this != &rhs)
296 {
297 m_directory = rhs.m_directory;
298 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000299 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000300 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000301 }
302 return *this;
303}
304
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000305//------------------------------------------------------------------
306// Update the contents of this object with a new path. The path will
307// be split up into a directory and filename and stored as uniqued
308// string values for quick comparison and efficient memory usage.
309//------------------------------------------------------------------
310void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000311FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312{
313 m_filename.Clear();
314 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000315 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000316 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000317
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 if (pathname == NULL || pathname[0] == '\0')
319 return;
320
Zachary Turner3f559742014-08-07 17:33:36 +0000321 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000322
Jim Ingham0909e5f2010-09-16 00:57:33 +0000323 if (resolve)
324 {
Zachary Turner3f559742014-08-07 17:33:36 +0000325 FileSpec::Resolve (normalized);
326 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000327 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000328
329 // Only normalize after resolving the path. Resolution will modify the path
330 // string, potentially adding wrong kinds of slashes to the path, that need
331 // to be re-normalized.
332 Normalize(normalized, syntax);
333
Zachary Turner3f559742014-08-07 17:33:36 +0000334 llvm::StringRef resolve_path_ref(normalized.c_str());
335 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
336 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337 {
Zachary Turner3f559742014-08-07 17:33:36 +0000338 m_filename.SetString (filename_ref);
339 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
340 if (!directory_ref.empty())
341 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000342 }
Zachary Turner3f559742014-08-07 17:33:36 +0000343 else
344 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000345}
346
Chaoren Lind3173f32015-05-29 19:52:29 +0000347void
348FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
349{
350 return SetFile(pathname.c_str(), resolve, syntax);
351}
352
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000353//----------------------------------------------------------------------
354// Convert to pointer operator. This allows code to check any FileSpec
355// objects to see if they contain anything valid using code such as:
356//
357// if (file_spec)
358// {}
359//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000360FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000361{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000362 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000363}
364
365//----------------------------------------------------------------------
366// Logical NOT operator. This allows code to check any FileSpec
367// objects to see if they are invalid using code such as:
368//
369// if (!file_spec)
370// {}
371//----------------------------------------------------------------------
372bool
373FileSpec::operator!() const
374{
375 return !m_directory && !m_filename;
376}
377
378//------------------------------------------------------------------
379// Equal to operator
380//------------------------------------------------------------------
381bool
382FileSpec::operator== (const FileSpec& rhs) const
383{
Greg Clayton7481c202010-11-08 00:28:40 +0000384 if (m_filename == rhs.m_filename)
385 {
386 if (m_directory == rhs.m_directory)
387 return true;
388
389 // TODO: determine if we want to keep this code in here.
390 // The code below was added to handle a case where we were
391 // trying to set a file and line breakpoint and one path
392 // was resolved, and the other not and the directory was
393 // in a mount point that resolved to a more complete path:
394 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
395 // this out...
396 if (IsResolved() && rhs.IsResolved())
397 {
398 // Both paths are resolved, no need to look further...
399 return false;
400 }
401
402 FileSpec resolved_lhs(*this);
403
404 // If "this" isn't resolved, resolve it
405 if (!IsResolved())
406 {
407 if (resolved_lhs.ResolvePath())
408 {
409 // This path wasn't resolved but now it is. Check if the resolved
410 // directory is the same as our unresolved directory, and if so,
411 // we can mark this object as resolved to avoid more future resolves
412 m_is_resolved = (m_directory == resolved_lhs.m_directory);
413 }
414 else
415 return false;
416 }
417
418 FileSpec resolved_rhs(rhs);
419 if (!rhs.IsResolved())
420 {
421 if (resolved_rhs.ResolvePath())
422 {
423 // rhs's path wasn't resolved but now it is. Check if the resolved
424 // directory is the same as rhs's unresolved directory, and if so,
425 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000426 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000427 }
428 else
429 return false;
430 }
431
432 // If we reach this point in the code we were able to resolve both paths
433 // and since we only resolve the paths if the basenames are equal, then
434 // we can just check if both directories are equal...
435 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
436 }
437 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438}
439
440//------------------------------------------------------------------
441// Not equal to operator
442//------------------------------------------------------------------
443bool
444FileSpec::operator!= (const FileSpec& rhs) const
445{
Greg Clayton7481c202010-11-08 00:28:40 +0000446 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447}
448
449//------------------------------------------------------------------
450// Less than operator
451//------------------------------------------------------------------
452bool
453FileSpec::operator< (const FileSpec& rhs) const
454{
455 return FileSpec::Compare(*this, rhs, true) < 0;
456}
457
458//------------------------------------------------------------------
459// Dump a FileSpec object to a stream
460//------------------------------------------------------------------
461Stream&
462lldb_private::operator << (Stream &s, const FileSpec& f)
463{
464 f.Dump(&s);
465 return s;
466}
467
468//------------------------------------------------------------------
469// Clear this object by releasing both the directory and filename
470// string values and making them both the empty string.
471//------------------------------------------------------------------
472void
473FileSpec::Clear()
474{
475 m_directory.Clear();
476 m_filename.Clear();
477}
478
479//------------------------------------------------------------------
480// Compare two FileSpec objects. If "full" is true, then both
481// the directory and the filename must match. If "full" is false,
482// then the directory names for "a" and "b" are only compared if
483// they are both non-empty. This allows a FileSpec object to only
484// contain a filename and it can match FileSpec objects that have
485// matching filenames with different paths.
486//
487// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
488// and "1" if "a" is greater than "b".
489//------------------------------------------------------------------
490int
491FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
492{
493 int result = 0;
494
495 // If full is true, then we must compare both the directory and filename.
496
497 // If full is false, then if either directory is empty, then we match on
498 // the basename only, and if both directories have valid values, we still
499 // do a full compare. This allows for matching when we just have a filename
500 // in one of the FileSpec objects.
501
502 if (full || (a.m_directory && b.m_directory))
503 {
504 result = ConstString::Compare(a.m_directory, b.m_directory);
505 if (result)
506 return result;
507 }
508 return ConstString::Compare (a.m_filename, b.m_filename);
509}
510
511bool
Jim Ingham96a15962014-11-15 01:54:26 +0000512FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000513{
Jim Ingham87df91b2011-09-23 00:54:11 +0000514 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000515 return a.m_filename == b.m_filename;
Jim Ingham96a15962014-11-15 01:54:26 +0000516 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000517 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000518 else
519 {
520 if (a.m_filename != b.m_filename)
521 return false;
522 if (a.m_directory == b.m_directory)
523 return true;
524 ConstString a_without_dots;
525 ConstString b_without_dots;
526
527 RemoveBackupDots (a.m_directory, a_without_dots);
528 RemoveBackupDots (b.m_directory, b_without_dots);
529 return a_without_dots == b_without_dots;
530 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531}
532
Jim Ingham96a15962014-11-15 01:54:26 +0000533void
534FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
535{
536 const char *input = input_const_str.GetCString();
537 result_const_str.Clear();
538 if (!input || input[0] == '\0')
539 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540
Jim Ingham96a15962014-11-15 01:54:26 +0000541 const char win_sep = '\\';
542 const char unix_sep = '/';
543 char found_sep;
544 const char *win_backup = "\\..";
545 const char *unix_backup = "/..";
546
547 bool is_win = false;
548
549 // Determine the platform for the path (win or unix):
550
551 if (input[0] == win_sep)
552 is_win = true;
553 else if (input[0] == unix_sep)
554 is_win = false;
555 else if (input[1] == ':')
556 is_win = true;
557 else if (strchr(input, unix_sep) != nullptr)
558 is_win = false;
559 else if (strchr(input, win_sep) != nullptr)
560 is_win = true;
561 else
562 {
563 // No separators at all, no reason to do any work here.
564 result_const_str = input_const_str;
565 return;
566 }
567
568 llvm::StringRef backup_sep;
569 if (is_win)
570 {
571 found_sep = win_sep;
572 backup_sep = win_backup;
573 }
574 else
575 {
576 found_sep = unix_sep;
577 backup_sep = unix_backup;
578 }
579
580 llvm::StringRef input_ref(input);
581 llvm::StringRef curpos(input);
582
583 bool had_dots = false;
584 std::string result;
585
586 while (1)
587 {
588 // Start of loop
589 llvm::StringRef before_sep;
590 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
591
592 before_sep = around_sep.first;
593 curpos = around_sep.second;
594
595 if (curpos.empty())
596 {
597 if (had_dots)
598 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000599 while (before_sep.startswith("//"))
600 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000601 if (!before_sep.empty())
602 {
603 result.append(before_sep.data(), before_sep.size());
604 }
605 }
606 break;
607 }
608 had_dots = true;
609
610 unsigned num_backups = 1;
611 while (curpos.startswith(backup_sep))
612 {
613 num_backups++;
614 curpos = curpos.slice(backup_sep.size(), curpos.size());
615 }
616
617 size_t end_pos = before_sep.size();
618 while (num_backups-- > 0)
619 {
620 end_pos = before_sep.rfind(found_sep, end_pos);
621 if (end_pos == llvm::StringRef::npos)
622 {
623 result_const_str = input_const_str;
624 return;
625 }
626 }
627 result.append(before_sep.data(), end_pos);
628 }
629
630 if (had_dots)
631 result_const_str.SetCString(result.c_str());
632 else
633 result_const_str = input_const_str;
634
635 return;
636}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637
638//------------------------------------------------------------------
639// Dump the object to the supplied stream. If the object contains
640// a valid directory name, it will be displayed followed by a
641// directory delimiter, and the filename.
642//------------------------------------------------------------------
643void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000644FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000645{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000646 if (s)
647 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000648 std::string path{GetPath(true)};
649 s->PutCString(path.c_str());
650 char path_separator = GetPathSeparator(m_syntax);
651 if (!m_filename && !path.empty() && path.back() != path_separator)
652 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000653 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654}
655
656//------------------------------------------------------------------
657// Returns true if the file exists.
658//------------------------------------------------------------------
659bool
660FileSpec::Exists () const
661{
662 struct stat file_stats;
663 return GetFileStats (this, &file_stats);
664}
665
Caroline Tice428a9a52010-09-10 04:48:55 +0000666bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000667FileSpec::Readable () const
668{
669 const uint32_t permissions = GetPermissions();
670 if (permissions & eFilePermissionsEveryoneR)
671 return true;
672 return false;
673}
674
675bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000676FileSpec::ResolveExecutableLocation ()
677{
Greg Clayton274060b2010-10-20 20:54:39 +0000678 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000679 {
Greg Clayton58f41712011-01-25 21:32:01 +0000680 const char *file_cstr = m_filename.GetCString();
681 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000682 {
Greg Clayton58f41712011-01-25 21:32:01 +0000683 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000684 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
685 if (!error_or_path)
686 return false;
687 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000688 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000689 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000690 {
Greg Clayton58f41712011-01-25 21:32:01 +0000691 // FindProgramByName returns "." if it can't find the file.
692 if (strcmp (".", dir_ref.data()) == 0)
693 return false;
694
695 m_directory.SetCString (dir_ref.data());
696 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000697 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000698 else
699 {
700 // If FindProgramByName found the file, it returns the directory + filename in its return results.
701 // We need to separate them.
702 FileSpec tmp_file (dir_ref.data(), false);
703 if (tmp_file.Exists())
704 {
705 m_directory = tmp_file.m_directory;
706 return true;
707 }
Caroline Tice391a9602010-09-12 00:10:52 +0000708 }
709 }
710 }
711 }
712
713 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000714}
715
Jim Ingham0909e5f2010-09-16 00:57:33 +0000716bool
717FileSpec::ResolvePath ()
718{
Greg Clayton7481c202010-11-08 00:28:40 +0000719 if (m_is_resolved)
720 return true; // We have already resolved this path
721
722 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000723 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000724 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000725 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000726 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000727 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000728}
729
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730uint64_t
731FileSpec::GetByteSize() const
732{
733 struct stat file_stats;
734 if (GetFileStats (this, &file_stats))
735 return file_stats.st_size;
736 return 0;
737}
738
Zachary Turnerdf62f202014-08-07 17:33:07 +0000739FileSpec::PathSyntax
740FileSpec::GetPathSyntax() const
741{
742 return m_syntax;
743}
744
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745FileSpec::FileType
746FileSpec::GetFileType () const
747{
748 struct stat file_stats;
749 if (GetFileStats (this, &file_stats))
750 {
751 mode_t file_type = file_stats.st_mode & S_IFMT;
752 switch (file_type)
753 {
754 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000756#ifndef _WIN32
757 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758 case S_IFSOCK: return eFileTypeSocket;
759 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000760#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 default:
762 break;
763 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000764 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765 }
766 return eFileTypeInvalid;
767}
768
Greg Claytonfbb76342013-11-20 21:07:01 +0000769uint32_t
770FileSpec::GetPermissions () const
771{
772 uint32_t file_permissions = 0;
773 if (*this)
Chaoren Lind3173f32015-05-29 19:52:29 +0000774 FileSystem::GetFilePermissions(*this, file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000775 return file_permissions;
776}
777
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778TimeValue
779FileSpec::GetModificationTime () const
780{
781 TimeValue mod_time;
782 struct stat file_stats;
783 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000784 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785 return mod_time;
786}
787
788//------------------------------------------------------------------
789// Directory string get accessor.
790//------------------------------------------------------------------
791ConstString &
792FileSpec::GetDirectory()
793{
794 return m_directory;
795}
796
797//------------------------------------------------------------------
798// Directory string const get accessor.
799//------------------------------------------------------------------
800const ConstString &
801FileSpec::GetDirectory() const
802{
803 return m_directory;
804}
805
806//------------------------------------------------------------------
807// Filename string get accessor.
808//------------------------------------------------------------------
809ConstString &
810FileSpec::GetFilename()
811{
812 return m_filename;
813}
814
815//------------------------------------------------------------------
816// Filename string const get accessor.
817//------------------------------------------------------------------
818const ConstString &
819FileSpec::GetFilename() const
820{
821 return m_filename;
822}
823
824//------------------------------------------------------------------
825// Extract the directory and path into a fixed buffer. This is
826// needed as the directory and path are stored in separate string
827// values.
828//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000829size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000830FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000832 if (!path)
833 return 0;
834
Zachary Turnerdf62f202014-08-07 17:33:07 +0000835 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000836 ::snprintf(path, path_max_len, "%s", result.c_str());
837 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838}
839
Greg Claytona44c1e62013-04-29 16:36:27 +0000840std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000841FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000842{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000843 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000844 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000845 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000846}
847
Chaoren Lind3173f32015-05-29 19:52:29 +0000848const char *
849FileSpec::GetCString(bool denormalize) const
850{
851 return ConstString{GetPath(denormalize)}.AsCString(NULL);
852}
853
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000854void
855FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
856{
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000857 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
858 if (m_directory)
859 path.insert(path.end(), '/');
860 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000861 Normalize(path, m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000862 if (path.size() > 1 && path.back() == '/') path.pop_back();
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000863 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000864 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000865}
866
Enrico Granataa9dbf432011-10-17 21:45:27 +0000867ConstString
868FileSpec::GetFileNameExtension () const
869{
Greg Clayton1f746072012-08-29 21:13:06 +0000870 if (m_filename)
871 {
872 const char *filename = m_filename.GetCString();
873 const char* dot_pos = strrchr(filename, '.');
874 if (dot_pos && dot_pos[1] != '\0')
875 return ConstString(dot_pos+1);
876 }
877 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000878}
879
880ConstString
881FileSpec::GetFileNameStrippingExtension () const
882{
883 const char *filename = m_filename.GetCString();
884 if (filename == NULL)
885 return ConstString();
886
Johnny Chenf5df5372011-10-18 19:28:30 +0000887 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000888 if (dot_pos == NULL)
889 return m_filename;
890
891 return ConstString(filename, dot_pos-filename);
892}
893
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894//------------------------------------------------------------------
895// Returns a shared pointer to a data buffer that contains all or
896// part of the contents of a file. The data is memory mapped and
897// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000898// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000899// file, and "file_size" bytes will be mapped. If "file_size" is
900// greater than the number of bytes available in the file starting
901// at "file_offset", the number of bytes will be appropriately
902// truncated. The final number of bytes that get mapped can be
903// verified using the DataBuffer::GetByteSize() function.
904//------------------------------------------------------------------
905DataBufferSP
906FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
907{
908 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000909 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 if (mmap_data.get())
911 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000912 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
913 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914 data_sp.reset(mmap_data.release());
915 }
916 return data_sp;
917}
918
Greg Clayton736888c2015-02-23 23:47:09 +0000919DataBufferSP
920FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
921{
922 if (FileSystem::IsLocal(*this))
923 return MemoryMapFileContents(file_offset, file_size);
924 else
925 return ReadFileContents(file_offset, file_size, NULL);
926}
927
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928
929//------------------------------------------------------------------
930// Return the size in bytes that this object takes in memory. This
931// returns the size in bytes of this object, not any shared string
932// values it may refer to.
933//------------------------------------------------------------------
934size_t
935FileSpec::MemorySize() const
936{
937 return m_filename.MemorySize() + m_directory.MemorySize();
938}
939
Greg Claytondda4f7b2010-06-30 23:03:03 +0000940
941size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000942FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943{
Greg Clayton4017fa32012-01-06 02:01:06 +0000944 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000945 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946 char resolved_path[PATH_MAX];
947 if (GetPath(resolved_path, sizeof(resolved_path)))
948 {
Greg Clayton96c09682012-01-04 22:56:43 +0000949 File file;
950 error = file.Open(resolved_path, File::eOpenOptionRead);
951 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952 {
Greg Clayton96c09682012-01-04 22:56:43 +0000953 off_t file_offset_after_seek = file_offset;
954 bytes_read = dst_len;
955 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000956 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000957 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000958 else
959 {
960 error.SetErrorString("invalid file specification");
961 }
962 if (error_ptr)
963 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000964 return bytes_read;
965}
966
967//------------------------------------------------------------------
968// Returns a shared pointer to a data buffer that contains all or
969// part of the contents of a file. The data copies into a heap based
970// buffer that lives in the DataBuffer shared pointer object returned.
971// The data that is cached will start "file_offset" bytes into the
972// file, and "file_size" bytes will be mapped. If "file_size" is
973// greater than the number of bytes available in the file starting
974// at "file_offset", the number of bytes will be appropriately
975// truncated. The final number of bytes that get mapped can be
976// verified using the DataBuffer::GetByteSize() function.
977//------------------------------------------------------------------
978DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000979FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000980{
Greg Clayton4017fa32012-01-06 02:01:06 +0000981 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000982 DataBufferSP data_sp;
983 char resolved_path[PATH_MAX];
984 if (GetPath(resolved_path, sizeof(resolved_path)))
985 {
Greg Clayton96c09682012-01-04 22:56:43 +0000986 File file;
987 error = file.Open(resolved_path, File::eOpenOptionRead);
988 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000989 {
990 const bool null_terminate = false;
991 error = file.Read (file_size, file_offset, null_terminate, data_sp);
992 }
993 }
994 else
995 {
996 error.SetErrorString("invalid file specification");
997 }
998 if (error_ptr)
999 *error_ptr = error;
1000 return data_sp;
1001}
1002
1003DataBufferSP
1004FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1005{
1006 Error error;
1007 DataBufferSP data_sp;
1008 char resolved_path[PATH_MAX];
1009 if (GetPath(resolved_path, sizeof(resolved_path)))
1010 {
1011 File file;
1012 error = file.Open(resolved_path, File::eOpenOptionRead);
1013 if (error.Success())
1014 {
1015 off_t offset = 0;
1016 size_t length = SIZE_MAX;
1017 const bool null_terminate = true;
1018 error = file.Read (length, offset, null_terminate, data_sp);
1019 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001021 else
1022 {
1023 error.SetErrorString("invalid file specification");
1024 }
1025 if (error_ptr)
1026 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 return data_sp;
1028}
1029
Greg Clayton58fc50e2010-10-20 22:52:05 +00001030size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001031FileSpec::ReadFileLines (STLStringArray &lines)
1032{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001034 char path[PATH_MAX];
1035 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001037 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038
Greg Clayton58fc50e2010-10-20 22:52:05 +00001039 if (file_stream)
1040 {
1041 std::string line;
1042 while (getline (file_stream, line))
1043 lines.push_back (line);
1044 }
1045 }
1046 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047}
Greg Clayton4272cc72011-02-02 02:24:04 +00001048
1049FileSpec::EnumerateDirectoryResult
1050FileSpec::EnumerateDirectory
1051(
1052 const char *dir_path,
1053 bool find_directories,
1054 bool find_files,
1055 bool find_other,
1056 EnumerateDirectoryCallbackType callback,
1057 void *callback_baton
1058)
1059{
1060 if (dir_path && dir_path[0])
1061 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001062#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001063 std::string szDir(dir_path);
1064 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001065
1066 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001067 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001068
1069 if (hFind == INVALID_HANDLE_VALUE)
1070 {
1071 return eEnumerateDirectoryResultNext;
1072 }
1073
1074 do
1075 {
1076 bool call_callback = false;
1077 FileSpec::FileType file_type = eFileTypeUnknown;
1078 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1079 {
1080 size_t len = strlen(ffd.cFileName);
1081
1082 if (len == 1 && ffd.cFileName[0] == '.')
1083 continue;
1084
1085 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1086 continue;
1087
1088 file_type = eFileTypeDirectory;
1089 call_callback = find_directories;
1090 }
1091 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1092 {
1093 file_type = eFileTypeOther;
1094 call_callback = find_other;
1095 }
1096 else
1097 {
1098 file_type = eFileTypeRegular;
1099 call_callback = find_files;
1100 }
1101 if (call_callback)
1102 {
1103 char child_path[MAX_PATH];
1104 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1105 if (child_path_len < (int)(sizeof(child_path) - 1))
1106 {
1107 // Don't resolve the file type or path
1108 FileSpec child_path_spec (child_path, false);
1109
1110 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1111
1112 switch (result)
1113 {
1114 case eEnumerateDirectoryResultNext:
1115 // Enumerate next entry in the current directory. We just
1116 // exit this switch and will continue enumerating the
1117 // current directory as we currently are...
1118 break;
1119
1120 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1121 if (FileSpec::EnumerateDirectory(child_path,
1122 find_directories,
1123 find_files,
1124 find_other,
1125 callback,
1126 callback_baton) == eEnumerateDirectoryResultQuit)
1127 {
1128 // The subdirectory returned Quit, which means to
1129 // stop all directory enumerations at all levels.
1130 return eEnumerateDirectoryResultQuit;
1131 }
1132 break;
1133
1134 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1135 // Exit from this directory level and tell parent to
1136 // keep enumerating.
1137 return eEnumerateDirectoryResultNext;
1138
1139 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1140 return eEnumerateDirectoryResultQuit;
1141 }
1142 }
1143 }
1144 } while (FindNextFile(hFind, &ffd) != 0);
1145
1146 FindClose(hFind);
1147#else
1148 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 if (dir_path_dir.is_valid())
1150 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001151 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1152
Jason Molenda14aef122013-04-04 03:19:27 +00001153 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1154#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1155 if (path_max < __DARWIN_MAXPATHLEN)
1156 path_max = __DARWIN_MAXPATHLEN;
1157#endif
1158 struct dirent *buf, *dp;
1159 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1160
1161 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001162 {
1163 // Only search directories
1164 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1165 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001166 size_t len = strlen(dp->d_name);
1167
1168 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001169 continue;
1170
Greg Claytone0f3c022011-02-07 17:41:11 +00001171 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001172 continue;
1173 }
1174
1175 bool call_callback = false;
1176 FileSpec::FileType file_type = eFileTypeUnknown;
1177
1178 switch (dp->d_type)
1179 {
1180 default:
1181 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1182 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1183 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1184 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1185 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1186 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1187 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1188 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001189#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001190 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001191#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001192 }
1193
1194 if (call_callback)
1195 {
1196 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001197
1198 // Don't make paths with "/foo//bar", that just confuses everybody.
1199 int child_path_len;
1200 if (dir_path_last_char == '/')
1201 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1202 else
1203 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1204
Johnny Chen44805302011-07-19 19:48:13 +00001205 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001206 {
1207 // Don't resolve the file type or path
1208 FileSpec child_path_spec (child_path, false);
1209
1210 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1211
1212 switch (result)
1213 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001214 case eEnumerateDirectoryResultNext:
1215 // Enumerate next entry in the current directory. We just
1216 // exit this switch and will continue enumerating the
1217 // current directory as we currently are...
1218 break;
1219
1220 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1221 if (FileSpec::EnumerateDirectory (child_path,
1222 find_directories,
1223 find_files,
1224 find_other,
1225 callback,
1226 callback_baton) == eEnumerateDirectoryResultQuit)
1227 {
1228 // The subdirectory returned Quit, which means to
1229 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001230 if (buf)
1231 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001232 return eEnumerateDirectoryResultQuit;
1233 }
1234 break;
1235
1236 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1237 // Exit from this directory level and tell parent to
1238 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001239 if (buf)
1240 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001241 return eEnumerateDirectoryResultNext;
1242
1243 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001244 if (buf)
1245 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001246 return eEnumerateDirectoryResultQuit;
1247 }
1248 }
1249 }
1250 }
Jason Molenda14aef122013-04-04 03:19:27 +00001251 if (buf)
1252 {
1253 free (buf);
1254 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001255 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001256#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001257 }
1258 // By default when exiting a directory, we tell the parent enumeration
1259 // to continue enumerating.
1260 return eEnumerateDirectoryResultNext;
1261}
1262
Daniel Maleae0f8f572013-08-26 23:57:52 +00001263FileSpec
1264FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1265{
1266 const bool resolve = false;
1267 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1268 return FileSpec(new_path,resolve);
1269 StreamString stream;
1270 if (m_filename.IsEmpty())
1271 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1272 else if (m_directory.IsEmpty())
1273 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1274 else
1275 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1276 return FileSpec(stream.GetData(),resolve);
1277}
1278
1279FileSpec
1280FileSpec::CopyByRemovingLastPathComponent () const
1281{
1282 const bool resolve = false;
1283 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1284 return FileSpec("",resolve);
1285 if (m_directory.IsEmpty())
1286 return FileSpec("",resolve);
1287 if (m_filename.IsEmpty())
1288 {
1289 const char* dir_cstr = m_directory.GetCString();
1290 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1291
1292 // check for obvious cases before doing the full thing
1293 if (!last_slash_ptr)
1294 return FileSpec("",resolve);
1295 if (last_slash_ptr == dir_cstr)
1296 return FileSpec("/",resolve);
1297
1298 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1299 ConstString new_path(dir_cstr,last_slash_pos);
1300 return FileSpec(new_path.GetCString(),resolve);
1301 }
1302 else
1303 return FileSpec(m_directory.GetCString(),resolve);
1304}
1305
Greg Claytonfbb76342013-11-20 21:07:01 +00001306ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001307FileSpec::GetLastPathComponent () const
1308{
Greg Claytonfbb76342013-11-20 21:07:01 +00001309 if (m_filename)
1310 return m_filename;
1311 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001312 {
1313 const char* dir_cstr = m_directory.GetCString();
1314 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1315 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001316 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001317 if (last_slash_ptr == dir_cstr)
1318 {
1319 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001320 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001321 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001322 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001323 }
1324 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001325 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001326 const char* penultimate_slash_ptr = last_slash_ptr;
1327 while (*penultimate_slash_ptr)
1328 {
1329 --penultimate_slash_ptr;
1330 if (penultimate_slash_ptr == dir_cstr)
1331 break;
1332 if (*penultimate_slash_ptr == '/')
1333 break;
1334 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001335 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1336 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001337 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001338 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001339}
1340
1341void
1342FileSpec::AppendPathComponent (const char *new_path)
1343{
1344 const bool resolve = false;
1345 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1346 {
1347 SetFile(new_path,resolve);
1348 return;
1349 }
1350 StreamString stream;
1351 if (m_filename.IsEmpty())
1352 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1353 else if (m_directory.IsEmpty())
1354 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1355 else
1356 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1357 SetFile(stream.GetData(), resolve);
1358}
1359
1360void
Chaoren Lind3173f32015-05-29 19:52:29 +00001361FileSpec::AppendPathComponent(const std::string &new_path)
1362{
1363 return AppendPathComponent(new_path.c_str());
1364}
1365
1366void
Daniel Maleae0f8f572013-08-26 23:57:52 +00001367FileSpec::RemoveLastPathComponent ()
1368{
1369 const bool resolve = false;
1370 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1371 {
1372 SetFile("",resolve);
1373 return;
1374 }
1375 if (m_directory.IsEmpty())
1376 {
1377 SetFile("",resolve);
1378 return;
1379 }
1380 if (m_filename.IsEmpty())
1381 {
1382 const char* dir_cstr = m_directory.GetCString();
1383 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1384
1385 // check for obvious cases before doing the full thing
1386 if (!last_slash_ptr)
1387 {
1388 SetFile("",resolve);
1389 return;
1390 }
1391 if (last_slash_ptr == dir_cstr)
1392 {
1393 SetFile("/",resolve);
1394 return;
1395 }
1396 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1397 ConstString new_path(dir_cstr,last_slash_pos);
1398 SetFile(new_path.GetCString(),resolve);
1399 }
1400 else
1401 SetFile(m_directory.GetCString(),resolve);
1402}
Greg Clayton1f746072012-08-29 21:13:06 +00001403//------------------------------------------------------------------
1404/// Returns true if the filespec represents an implementation source
1405/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1406/// extension).
1407///
1408/// @return
1409/// \b true if the filespec represents an implementation source
1410/// file, \b false otherwise.
1411//------------------------------------------------------------------
1412bool
1413FileSpec::IsSourceImplementationFile () const
1414{
1415 ConstString extension (GetFileNameExtension());
1416 if (extension)
1417 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001418 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 +00001419 return g_source_file_regex.Execute (extension.GetCString());
1420 }
1421 return false;
1422}
1423
Greg Claytona0ca6602012-10-18 16:33:33 +00001424bool
1425FileSpec::IsRelativeToCurrentWorkingDirectory () const
1426{
Zachary Turner270e99a2014-12-08 21:36:42 +00001427 const char *dir = m_directory.GetCString();
1428 llvm::StringRef directory(dir ? dir : "");
1429
1430 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001431 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001432 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001433 {
1434 // If the path doesn't start with '/' or '~', return true
1435 switch (directory[0])
1436 {
1437 case '/':
1438 case '~':
1439 return false;
1440 default:
1441 return true;
1442 }
1443 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001444 else
1445 {
1446 if (directory.size() >= 2 && directory[1] == ':')
1447 return false;
1448 if (directory[0] == '/')
1449 return false;
1450 return true;
1451 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001452 }
1453 else if (m_filename)
1454 {
1455 // No directory, just a basename, return true
1456 return true;
1457 }
1458 return false;
1459}