blob: c0efa71aad1eda329695ce098fa067664c1faa57 [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) :
246 FileSpec(pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix)
247{
248}
249
Jim Ingham0909e5f2010-09-16 00:57:33 +0000250//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251// Copy constructor
252//------------------------------------------------------------------
253FileSpec::FileSpec(const FileSpec& rhs) :
254 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000255 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000256 m_is_resolved (rhs.m_is_resolved),
257 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000258{
259}
260
261//------------------------------------------------------------------
262// Copy constructor
263//------------------------------------------------------------------
264FileSpec::FileSpec(const FileSpec* rhs) :
265 m_directory(),
266 m_filename()
267{
268 if (rhs)
269 *this = *rhs;
270}
271
272//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000273// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274//------------------------------------------------------------------
275FileSpec::~FileSpec()
276{
277}
278
279//------------------------------------------------------------------
280// Assignment operator.
281//------------------------------------------------------------------
282const FileSpec&
283FileSpec::operator= (const FileSpec& rhs)
284{
285 if (this != &rhs)
286 {
287 m_directory = rhs.m_directory;
288 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000289 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000290 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000291 }
292 return *this;
293}
294
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295//------------------------------------------------------------------
296// Update the contents of this object with a new path. The path will
297// be split up into a directory and filename and stored as uniqued
298// string values for quick comparison and efficient memory usage.
299//------------------------------------------------------------------
300void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000301FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302{
303 m_filename.Clear();
304 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000305 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000306 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000307
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308 if (pathname == NULL || pathname[0] == '\0')
309 return;
310
Zachary Turner3f559742014-08-07 17:33:36 +0000311 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000312
Jim Ingham0909e5f2010-09-16 00:57:33 +0000313 if (resolve)
314 {
Zachary Turner3f559742014-08-07 17:33:36 +0000315 FileSpec::Resolve (normalized);
316 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000317 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000318
319 // Only normalize after resolving the path. Resolution will modify the path
320 // string, potentially adding wrong kinds of slashes to the path, that need
321 // to be re-normalized.
322 Normalize(normalized, syntax);
323
Zachary Turner3f559742014-08-07 17:33:36 +0000324 llvm::StringRef resolve_path_ref(normalized.c_str());
325 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
326 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327 {
Zachary Turner3f559742014-08-07 17:33:36 +0000328 m_filename.SetString (filename_ref);
329 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
330 if (!directory_ref.empty())
331 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332 }
Zachary Turner3f559742014-08-07 17:33:36 +0000333 else
334 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000335}
336
337//----------------------------------------------------------------------
338// Convert to pointer operator. This allows code to check any FileSpec
339// objects to see if they contain anything valid using code such as:
340//
341// if (file_spec)
342// {}
343//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000344FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000345{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000346 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000347}
348
349//----------------------------------------------------------------------
350// Logical NOT operator. This allows code to check any FileSpec
351// objects to see if they are invalid using code such as:
352//
353// if (!file_spec)
354// {}
355//----------------------------------------------------------------------
356bool
357FileSpec::operator!() const
358{
359 return !m_directory && !m_filename;
360}
361
362//------------------------------------------------------------------
363// Equal to operator
364//------------------------------------------------------------------
365bool
366FileSpec::operator== (const FileSpec& rhs) const
367{
Greg Clayton7481c202010-11-08 00:28:40 +0000368 if (m_filename == rhs.m_filename)
369 {
370 if (m_directory == rhs.m_directory)
371 return true;
372
373 // TODO: determine if we want to keep this code in here.
374 // The code below was added to handle a case where we were
375 // trying to set a file and line breakpoint and one path
376 // was resolved, and the other not and the directory was
377 // in a mount point that resolved to a more complete path:
378 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
379 // this out...
380 if (IsResolved() && rhs.IsResolved())
381 {
382 // Both paths are resolved, no need to look further...
383 return false;
384 }
385
386 FileSpec resolved_lhs(*this);
387
388 // If "this" isn't resolved, resolve it
389 if (!IsResolved())
390 {
391 if (resolved_lhs.ResolvePath())
392 {
393 // This path wasn't resolved but now it is. Check if the resolved
394 // directory is the same as our unresolved directory, and if so,
395 // we can mark this object as resolved to avoid more future resolves
396 m_is_resolved = (m_directory == resolved_lhs.m_directory);
397 }
398 else
399 return false;
400 }
401
402 FileSpec resolved_rhs(rhs);
403 if (!rhs.IsResolved())
404 {
405 if (resolved_rhs.ResolvePath())
406 {
407 // rhs's path wasn't resolved but now it is. Check if the resolved
408 // directory is the same as rhs's unresolved directory, and if so,
409 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000410 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000411 }
412 else
413 return false;
414 }
415
416 // If we reach this point in the code we were able to resolve both paths
417 // and since we only resolve the paths if the basenames are equal, then
418 // we can just check if both directories are equal...
419 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
420 }
421 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422}
423
424//------------------------------------------------------------------
425// Not equal to operator
426//------------------------------------------------------------------
427bool
428FileSpec::operator!= (const FileSpec& rhs) const
429{
Greg Clayton7481c202010-11-08 00:28:40 +0000430 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000431}
432
433//------------------------------------------------------------------
434// Less than operator
435//------------------------------------------------------------------
436bool
437FileSpec::operator< (const FileSpec& rhs) const
438{
439 return FileSpec::Compare(*this, rhs, true) < 0;
440}
441
442//------------------------------------------------------------------
443// Dump a FileSpec object to a stream
444//------------------------------------------------------------------
445Stream&
446lldb_private::operator << (Stream &s, const FileSpec& f)
447{
448 f.Dump(&s);
449 return s;
450}
451
452//------------------------------------------------------------------
453// Clear this object by releasing both the directory and filename
454// string values and making them both the empty string.
455//------------------------------------------------------------------
456void
457FileSpec::Clear()
458{
459 m_directory.Clear();
460 m_filename.Clear();
461}
462
463//------------------------------------------------------------------
464// Compare two FileSpec objects. If "full" is true, then both
465// the directory and the filename must match. If "full" is false,
466// then the directory names for "a" and "b" are only compared if
467// they are both non-empty. This allows a FileSpec object to only
468// contain a filename and it can match FileSpec objects that have
469// matching filenames with different paths.
470//
471// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
472// and "1" if "a" is greater than "b".
473//------------------------------------------------------------------
474int
475FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
476{
477 int result = 0;
478
479 // If full is true, then we must compare both the directory and filename.
480
481 // If full is false, then if either directory is empty, then we match on
482 // the basename only, and if both directories have valid values, we still
483 // do a full compare. This allows for matching when we just have a filename
484 // in one of the FileSpec objects.
485
486 if (full || (a.m_directory && b.m_directory))
487 {
488 result = ConstString::Compare(a.m_directory, b.m_directory);
489 if (result)
490 return result;
491 }
492 return ConstString::Compare (a.m_filename, b.m_filename);
493}
494
495bool
Jim Ingham96a15962014-11-15 01:54:26 +0000496FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497{
Jim Ingham87df91b2011-09-23 00:54:11 +0000498 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000499 return a.m_filename == b.m_filename;
Jim Ingham96a15962014-11-15 01:54:26 +0000500 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000501 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000502 else
503 {
504 if (a.m_filename != b.m_filename)
505 return false;
506 if (a.m_directory == b.m_directory)
507 return true;
508 ConstString a_without_dots;
509 ConstString b_without_dots;
510
511 RemoveBackupDots (a.m_directory, a_without_dots);
512 RemoveBackupDots (b.m_directory, b_without_dots);
513 return a_without_dots == b_without_dots;
514 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000515}
516
Jim Ingham96a15962014-11-15 01:54:26 +0000517void
518FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
519{
520 const char *input = input_const_str.GetCString();
521 result_const_str.Clear();
522 if (!input || input[0] == '\0')
523 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000524
Jim Ingham96a15962014-11-15 01:54:26 +0000525 const char win_sep = '\\';
526 const char unix_sep = '/';
527 char found_sep;
528 const char *win_backup = "\\..";
529 const char *unix_backup = "/..";
530
531 bool is_win = false;
532
533 // Determine the platform for the path (win or unix):
534
535 if (input[0] == win_sep)
536 is_win = true;
537 else if (input[0] == unix_sep)
538 is_win = false;
539 else if (input[1] == ':')
540 is_win = true;
541 else if (strchr(input, unix_sep) != nullptr)
542 is_win = false;
543 else if (strchr(input, win_sep) != nullptr)
544 is_win = true;
545 else
546 {
547 // No separators at all, no reason to do any work here.
548 result_const_str = input_const_str;
549 return;
550 }
551
552 llvm::StringRef backup_sep;
553 if (is_win)
554 {
555 found_sep = win_sep;
556 backup_sep = win_backup;
557 }
558 else
559 {
560 found_sep = unix_sep;
561 backup_sep = unix_backup;
562 }
563
564 llvm::StringRef input_ref(input);
565 llvm::StringRef curpos(input);
566
567 bool had_dots = false;
568 std::string result;
569
570 while (1)
571 {
572 // Start of loop
573 llvm::StringRef before_sep;
574 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
575
576 before_sep = around_sep.first;
577 curpos = around_sep.second;
578
579 if (curpos.empty())
580 {
581 if (had_dots)
582 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000583 while (before_sep.startswith("//"))
584 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000585 if (!before_sep.empty())
586 {
587 result.append(before_sep.data(), before_sep.size());
588 }
589 }
590 break;
591 }
592 had_dots = true;
593
594 unsigned num_backups = 1;
595 while (curpos.startswith(backup_sep))
596 {
597 num_backups++;
598 curpos = curpos.slice(backup_sep.size(), curpos.size());
599 }
600
601 size_t end_pos = before_sep.size();
602 while (num_backups-- > 0)
603 {
604 end_pos = before_sep.rfind(found_sep, end_pos);
605 if (end_pos == llvm::StringRef::npos)
606 {
607 result_const_str = input_const_str;
608 return;
609 }
610 }
611 result.append(before_sep.data(), end_pos);
612 }
613
614 if (had_dots)
615 result_const_str.SetCString(result.c_str());
616 else
617 result_const_str = input_const_str;
618
619 return;
620}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621
622//------------------------------------------------------------------
623// Dump the object to the supplied stream. If the object contains
624// a valid directory name, it will be displayed followed by a
625// directory delimiter, and the filename.
626//------------------------------------------------------------------
627void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000628FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000630 if (s)
631 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000632 std::string path{GetPath(true)};
633 s->PutCString(path.c_str());
634 char path_separator = GetPathSeparator(m_syntax);
635 if (!m_filename && !path.empty() && path.back() != path_separator)
636 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000637 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638}
639
640//------------------------------------------------------------------
641// Returns true if the file exists.
642//------------------------------------------------------------------
643bool
644FileSpec::Exists () const
645{
646 struct stat file_stats;
647 return GetFileStats (this, &file_stats);
648}
649
Caroline Tice428a9a52010-09-10 04:48:55 +0000650bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000651FileSpec::Readable () const
652{
653 const uint32_t permissions = GetPermissions();
654 if (permissions & eFilePermissionsEveryoneR)
655 return true;
656 return false;
657}
658
659bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000660FileSpec::ResolveExecutableLocation ()
661{
Greg Clayton274060b2010-10-20 20:54:39 +0000662 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000663 {
Greg Clayton58f41712011-01-25 21:32:01 +0000664 const char *file_cstr = m_filename.GetCString();
665 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000666 {
Greg Clayton58f41712011-01-25 21:32:01 +0000667 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000668 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
669 if (!error_or_path)
670 return false;
671 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000672 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000673 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000674 {
Greg Clayton58f41712011-01-25 21:32:01 +0000675 // FindProgramByName returns "." if it can't find the file.
676 if (strcmp (".", dir_ref.data()) == 0)
677 return false;
678
679 m_directory.SetCString (dir_ref.data());
680 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000681 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000682 else
683 {
684 // If FindProgramByName found the file, it returns the directory + filename in its return results.
685 // We need to separate them.
686 FileSpec tmp_file (dir_ref.data(), false);
687 if (tmp_file.Exists())
688 {
689 m_directory = tmp_file.m_directory;
690 return true;
691 }
Caroline Tice391a9602010-09-12 00:10:52 +0000692 }
693 }
694 }
695 }
696
697 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000698}
699
Jim Ingham0909e5f2010-09-16 00:57:33 +0000700bool
701FileSpec::ResolvePath ()
702{
Greg Clayton7481c202010-11-08 00:28:40 +0000703 if (m_is_resolved)
704 return true; // We have already resolved this path
705
706 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000707 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000708 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000709 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000710 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000711 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000712}
713
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714uint64_t
715FileSpec::GetByteSize() const
716{
717 struct stat file_stats;
718 if (GetFileStats (this, &file_stats))
719 return file_stats.st_size;
720 return 0;
721}
722
Zachary Turnerdf62f202014-08-07 17:33:07 +0000723FileSpec::PathSyntax
724FileSpec::GetPathSyntax() const
725{
726 return m_syntax;
727}
728
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729FileSpec::FileType
730FileSpec::GetFileType () const
731{
732 struct stat file_stats;
733 if (GetFileStats (this, &file_stats))
734 {
735 mode_t file_type = file_stats.st_mode & S_IFMT;
736 switch (file_type)
737 {
738 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000740#ifndef _WIN32
741 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 case S_IFSOCK: return eFileTypeSocket;
743 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000744#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745 default:
746 break;
747 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000748 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749 }
750 return eFileTypeInvalid;
751}
752
Greg Claytonfbb76342013-11-20 21:07:01 +0000753uint32_t
754FileSpec::GetPermissions () const
755{
756 uint32_t file_permissions = 0;
757 if (*this)
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000758 FileSystem::GetFilePermissions(GetPath().c_str(), file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000759 return file_permissions;
760}
761
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762TimeValue
763FileSpec::GetModificationTime () const
764{
765 TimeValue mod_time;
766 struct stat file_stats;
767 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000768 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 return mod_time;
770}
771
772//------------------------------------------------------------------
773// Directory string get accessor.
774//------------------------------------------------------------------
775ConstString &
776FileSpec::GetDirectory()
777{
778 return m_directory;
779}
780
781//------------------------------------------------------------------
782// Directory string const get accessor.
783//------------------------------------------------------------------
784const ConstString &
785FileSpec::GetDirectory() const
786{
787 return m_directory;
788}
789
790//------------------------------------------------------------------
791// Filename string get accessor.
792//------------------------------------------------------------------
793ConstString &
794FileSpec::GetFilename()
795{
796 return m_filename;
797}
798
799//------------------------------------------------------------------
800// Filename string const get accessor.
801//------------------------------------------------------------------
802const ConstString &
803FileSpec::GetFilename() const
804{
805 return m_filename;
806}
807
808//------------------------------------------------------------------
809// Extract the directory and path into a fixed buffer. This is
810// needed as the directory and path are stored in separate string
811// values.
812//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000813size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000814FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000816 if (!path)
817 return 0;
818
Zachary Turnerdf62f202014-08-07 17:33:07 +0000819 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000820 ::snprintf(path, path_max_len, "%s", result.c_str());
821 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822}
823
Greg Claytona44c1e62013-04-29 16:36:27 +0000824std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000825FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000826{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000827 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000828 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000829 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000830}
831
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000832void
833FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
834{
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000835 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
836 if (m_directory)
837 path.insert(path.end(), '/');
838 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000839 Normalize(path, m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000840 if (path.size() > 1 && path.back() == '/') path.pop_back();
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000841 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000842 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000843}
844
Enrico Granataa9dbf432011-10-17 21:45:27 +0000845ConstString
846FileSpec::GetFileNameExtension () const
847{
Greg Clayton1f746072012-08-29 21:13:06 +0000848 if (m_filename)
849 {
850 const char *filename = m_filename.GetCString();
851 const char* dot_pos = strrchr(filename, '.');
852 if (dot_pos && dot_pos[1] != '\0')
853 return ConstString(dot_pos+1);
854 }
855 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000856}
857
858ConstString
859FileSpec::GetFileNameStrippingExtension () const
860{
861 const char *filename = m_filename.GetCString();
862 if (filename == NULL)
863 return ConstString();
864
Johnny Chenf5df5372011-10-18 19:28:30 +0000865 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000866 if (dot_pos == NULL)
867 return m_filename;
868
869 return ConstString(filename, dot_pos-filename);
870}
871
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872//------------------------------------------------------------------
873// Returns a shared pointer to a data buffer that contains all or
874// part of the contents of a file. The data is memory mapped and
875// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000876// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877// file, and "file_size" bytes will be mapped. If "file_size" is
878// greater than the number of bytes available in the file starting
879// at "file_offset", the number of bytes will be appropriately
880// truncated. The final number of bytes that get mapped can be
881// verified using the DataBuffer::GetByteSize() function.
882//------------------------------------------------------------------
883DataBufferSP
884FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
885{
886 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000887 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888 if (mmap_data.get())
889 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000890 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
891 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 data_sp.reset(mmap_data.release());
893 }
894 return data_sp;
895}
896
Greg Clayton736888c2015-02-23 23:47:09 +0000897DataBufferSP
898FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
899{
900 if (FileSystem::IsLocal(*this))
901 return MemoryMapFileContents(file_offset, file_size);
902 else
903 return ReadFileContents(file_offset, file_size, NULL);
904}
905
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906
907//------------------------------------------------------------------
908// Return the size in bytes that this object takes in memory. This
909// returns the size in bytes of this object, not any shared string
910// values it may refer to.
911//------------------------------------------------------------------
912size_t
913FileSpec::MemorySize() const
914{
915 return m_filename.MemorySize() + m_directory.MemorySize();
916}
917
Greg Claytondda4f7b2010-06-30 23:03:03 +0000918
919size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000920FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921{
Greg Clayton4017fa32012-01-06 02:01:06 +0000922 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000923 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000924 char resolved_path[PATH_MAX];
925 if (GetPath(resolved_path, sizeof(resolved_path)))
926 {
Greg Clayton96c09682012-01-04 22:56:43 +0000927 File file;
928 error = file.Open(resolved_path, File::eOpenOptionRead);
929 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 {
Greg Clayton96c09682012-01-04 22:56:43 +0000931 off_t file_offset_after_seek = file_offset;
932 bytes_read = dst_len;
933 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000934 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000935 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000936 else
937 {
938 error.SetErrorString("invalid file specification");
939 }
940 if (error_ptr)
941 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000942 return bytes_read;
943}
944
945//------------------------------------------------------------------
946// Returns a shared pointer to a data buffer that contains all or
947// part of the contents of a file. The data copies into a heap based
948// buffer that lives in the DataBuffer shared pointer object returned.
949// The data that is cached will start "file_offset" bytes into the
950// file, and "file_size" bytes will be mapped. If "file_size" is
951// greater than the number of bytes available in the file starting
952// at "file_offset", the number of bytes will be appropriately
953// truncated. The final number of bytes that get mapped can be
954// verified using the DataBuffer::GetByteSize() function.
955//------------------------------------------------------------------
956DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000957FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000958{
Greg Clayton4017fa32012-01-06 02:01:06 +0000959 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000960 DataBufferSP data_sp;
961 char resolved_path[PATH_MAX];
962 if (GetPath(resolved_path, sizeof(resolved_path)))
963 {
Greg Clayton96c09682012-01-04 22:56:43 +0000964 File file;
965 error = file.Open(resolved_path, File::eOpenOptionRead);
966 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000967 {
968 const bool null_terminate = false;
969 error = file.Read (file_size, file_offset, null_terminate, data_sp);
970 }
971 }
972 else
973 {
974 error.SetErrorString("invalid file specification");
975 }
976 if (error_ptr)
977 *error_ptr = error;
978 return data_sp;
979}
980
981DataBufferSP
982FileSpec::ReadFileContentsAsCString(Error *error_ptr)
983{
984 Error error;
985 DataBufferSP data_sp;
986 char resolved_path[PATH_MAX];
987 if (GetPath(resolved_path, sizeof(resolved_path)))
988 {
989 File file;
990 error = file.Open(resolved_path, File::eOpenOptionRead);
991 if (error.Success())
992 {
993 off_t offset = 0;
994 size_t length = SIZE_MAX;
995 const bool null_terminate = true;
996 error = file.Read (length, offset, null_terminate, data_sp);
997 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000999 else
1000 {
1001 error.SetErrorString("invalid file specification");
1002 }
1003 if (error_ptr)
1004 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 return data_sp;
1006}
1007
Greg Clayton58fc50e2010-10-20 22:52:05 +00001008size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009FileSpec::ReadFileLines (STLStringArray &lines)
1010{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001012 char path[PATH_MAX];
1013 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001015 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016
Greg Clayton58fc50e2010-10-20 22:52:05 +00001017 if (file_stream)
1018 {
1019 std::string line;
1020 while (getline (file_stream, line))
1021 lines.push_back (line);
1022 }
1023 }
1024 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025}
Greg Clayton4272cc72011-02-02 02:24:04 +00001026
1027FileSpec::EnumerateDirectoryResult
1028FileSpec::EnumerateDirectory
1029(
1030 const char *dir_path,
1031 bool find_directories,
1032 bool find_files,
1033 bool find_other,
1034 EnumerateDirectoryCallbackType callback,
1035 void *callback_baton
1036)
1037{
1038 if (dir_path && dir_path[0])
1039 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001040#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001041 std::string szDir(dir_path);
1042 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001043
1044 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001045 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001046
1047 if (hFind == INVALID_HANDLE_VALUE)
1048 {
1049 return eEnumerateDirectoryResultNext;
1050 }
1051
1052 do
1053 {
1054 bool call_callback = false;
1055 FileSpec::FileType file_type = eFileTypeUnknown;
1056 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1057 {
1058 size_t len = strlen(ffd.cFileName);
1059
1060 if (len == 1 && ffd.cFileName[0] == '.')
1061 continue;
1062
1063 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1064 continue;
1065
1066 file_type = eFileTypeDirectory;
1067 call_callback = find_directories;
1068 }
1069 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1070 {
1071 file_type = eFileTypeOther;
1072 call_callback = find_other;
1073 }
1074 else
1075 {
1076 file_type = eFileTypeRegular;
1077 call_callback = find_files;
1078 }
1079 if (call_callback)
1080 {
1081 char child_path[MAX_PATH];
1082 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1083 if (child_path_len < (int)(sizeof(child_path) - 1))
1084 {
1085 // Don't resolve the file type or path
1086 FileSpec child_path_spec (child_path, false);
1087
1088 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1089
1090 switch (result)
1091 {
1092 case eEnumerateDirectoryResultNext:
1093 // Enumerate next entry in the current directory. We just
1094 // exit this switch and will continue enumerating the
1095 // current directory as we currently are...
1096 break;
1097
1098 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1099 if (FileSpec::EnumerateDirectory(child_path,
1100 find_directories,
1101 find_files,
1102 find_other,
1103 callback,
1104 callback_baton) == eEnumerateDirectoryResultQuit)
1105 {
1106 // The subdirectory returned Quit, which means to
1107 // stop all directory enumerations at all levels.
1108 return eEnumerateDirectoryResultQuit;
1109 }
1110 break;
1111
1112 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1113 // Exit from this directory level and tell parent to
1114 // keep enumerating.
1115 return eEnumerateDirectoryResultNext;
1116
1117 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1118 return eEnumerateDirectoryResultQuit;
1119 }
1120 }
1121 }
1122 } while (FindNextFile(hFind, &ffd) != 0);
1123
1124 FindClose(hFind);
1125#else
1126 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001127 if (dir_path_dir.is_valid())
1128 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001129 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1130
Jason Molenda14aef122013-04-04 03:19:27 +00001131 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1132#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1133 if (path_max < __DARWIN_MAXPATHLEN)
1134 path_max = __DARWIN_MAXPATHLEN;
1135#endif
1136 struct dirent *buf, *dp;
1137 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1138
1139 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001140 {
1141 // Only search directories
1142 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1143 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001144 size_t len = strlen(dp->d_name);
1145
1146 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001147 continue;
1148
Greg Claytone0f3c022011-02-07 17:41:11 +00001149 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001150 continue;
1151 }
1152
1153 bool call_callback = false;
1154 FileSpec::FileType file_type = eFileTypeUnknown;
1155
1156 switch (dp->d_type)
1157 {
1158 default:
1159 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1160 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1161 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1162 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1163 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1164 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1165 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1166 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001167#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001168 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001169#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001170 }
1171
1172 if (call_callback)
1173 {
1174 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001175
1176 // Don't make paths with "/foo//bar", that just confuses everybody.
1177 int child_path_len;
1178 if (dir_path_last_char == '/')
1179 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1180 else
1181 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1182
Johnny Chen44805302011-07-19 19:48:13 +00001183 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001184 {
1185 // Don't resolve the file type or path
1186 FileSpec child_path_spec (child_path, false);
1187
1188 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1189
1190 switch (result)
1191 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001192 case eEnumerateDirectoryResultNext:
1193 // Enumerate next entry in the current directory. We just
1194 // exit this switch and will continue enumerating the
1195 // current directory as we currently are...
1196 break;
1197
1198 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1199 if (FileSpec::EnumerateDirectory (child_path,
1200 find_directories,
1201 find_files,
1202 find_other,
1203 callback,
1204 callback_baton) == eEnumerateDirectoryResultQuit)
1205 {
1206 // The subdirectory returned Quit, which means to
1207 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001208 if (buf)
1209 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001210 return eEnumerateDirectoryResultQuit;
1211 }
1212 break;
1213
1214 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1215 // Exit from this directory level and tell parent to
1216 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001217 if (buf)
1218 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001219 return eEnumerateDirectoryResultNext;
1220
1221 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001222 if (buf)
1223 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001224 return eEnumerateDirectoryResultQuit;
1225 }
1226 }
1227 }
1228 }
Jason Molenda14aef122013-04-04 03:19:27 +00001229 if (buf)
1230 {
1231 free (buf);
1232 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001233 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001234#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001235 }
1236 // By default when exiting a directory, we tell the parent enumeration
1237 // to continue enumerating.
1238 return eEnumerateDirectoryResultNext;
1239}
1240
Daniel Maleae0f8f572013-08-26 23:57:52 +00001241FileSpec
1242FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1243{
1244 const bool resolve = false;
1245 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1246 return FileSpec(new_path,resolve);
1247 StreamString stream;
1248 if (m_filename.IsEmpty())
1249 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1250 else if (m_directory.IsEmpty())
1251 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1252 else
1253 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1254 return FileSpec(stream.GetData(),resolve);
1255}
1256
1257FileSpec
1258FileSpec::CopyByRemovingLastPathComponent () const
1259{
1260 const bool resolve = false;
1261 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1262 return FileSpec("",resolve);
1263 if (m_directory.IsEmpty())
1264 return FileSpec("",resolve);
1265 if (m_filename.IsEmpty())
1266 {
1267 const char* dir_cstr = m_directory.GetCString();
1268 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1269
1270 // check for obvious cases before doing the full thing
1271 if (!last_slash_ptr)
1272 return FileSpec("",resolve);
1273 if (last_slash_ptr == dir_cstr)
1274 return FileSpec("/",resolve);
1275
1276 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1277 ConstString new_path(dir_cstr,last_slash_pos);
1278 return FileSpec(new_path.GetCString(),resolve);
1279 }
1280 else
1281 return FileSpec(m_directory.GetCString(),resolve);
1282}
1283
Greg Claytonfbb76342013-11-20 21:07:01 +00001284ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001285FileSpec::GetLastPathComponent () const
1286{
Greg Claytonfbb76342013-11-20 21:07:01 +00001287 if (m_filename)
1288 return m_filename;
1289 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001290 {
1291 const char* dir_cstr = m_directory.GetCString();
1292 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1293 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001294 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001295 if (last_slash_ptr == dir_cstr)
1296 {
1297 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001298 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001299 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001300 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001301 }
1302 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001303 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001304 const char* penultimate_slash_ptr = last_slash_ptr;
1305 while (*penultimate_slash_ptr)
1306 {
1307 --penultimate_slash_ptr;
1308 if (penultimate_slash_ptr == dir_cstr)
1309 break;
1310 if (*penultimate_slash_ptr == '/')
1311 break;
1312 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001313 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1314 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001315 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001316 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001317}
1318
1319void
1320FileSpec::AppendPathComponent (const char *new_path)
1321{
1322 const bool resolve = false;
1323 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1324 {
1325 SetFile(new_path,resolve);
1326 return;
1327 }
1328 StreamString stream;
1329 if (m_filename.IsEmpty())
1330 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1331 else if (m_directory.IsEmpty())
1332 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1333 else
1334 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1335 SetFile(stream.GetData(), resolve);
1336}
1337
1338void
1339FileSpec::RemoveLastPathComponent ()
1340{
1341 const bool resolve = false;
1342 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1343 {
1344 SetFile("",resolve);
1345 return;
1346 }
1347 if (m_directory.IsEmpty())
1348 {
1349 SetFile("",resolve);
1350 return;
1351 }
1352 if (m_filename.IsEmpty())
1353 {
1354 const char* dir_cstr = m_directory.GetCString();
1355 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1356
1357 // check for obvious cases before doing the full thing
1358 if (!last_slash_ptr)
1359 {
1360 SetFile("",resolve);
1361 return;
1362 }
1363 if (last_slash_ptr == dir_cstr)
1364 {
1365 SetFile("/",resolve);
1366 return;
1367 }
1368 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1369 ConstString new_path(dir_cstr,last_slash_pos);
1370 SetFile(new_path.GetCString(),resolve);
1371 }
1372 else
1373 SetFile(m_directory.GetCString(),resolve);
1374}
Greg Clayton1f746072012-08-29 21:13:06 +00001375//------------------------------------------------------------------
1376/// Returns true if the filespec represents an implementation source
1377/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1378/// extension).
1379///
1380/// @return
1381/// \b true if the filespec represents an implementation source
1382/// file, \b false otherwise.
1383//------------------------------------------------------------------
1384bool
1385FileSpec::IsSourceImplementationFile () const
1386{
1387 ConstString extension (GetFileNameExtension());
1388 if (extension)
1389 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001390 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 +00001391 return g_source_file_regex.Execute (extension.GetCString());
1392 }
1393 return false;
1394}
1395
Greg Claytona0ca6602012-10-18 16:33:33 +00001396bool
1397FileSpec::IsRelativeToCurrentWorkingDirectory () const
1398{
Zachary Turner270e99a2014-12-08 21:36:42 +00001399 const char *dir = m_directory.GetCString();
1400 llvm::StringRef directory(dir ? dir : "");
1401
1402 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001403 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001404 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001405 {
1406 // If the path doesn't start with '/' or '~', return true
1407 switch (directory[0])
1408 {
1409 case '/':
1410 case '~':
1411 return false;
1412 default:
1413 return true;
1414 }
1415 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001416 else
1417 {
1418 if (directory.size() >= 2 && directory[1] == ':')
1419 return false;
1420 if (directory[0] == '/')
1421 return false;
1422 return true;
1423 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001424 }
1425 else if (m_filename)
1426 {
1427 // No directory, just a basename, return true
1428 return true;
1429 }
1430 return false;
1431}