blob: a3f5e6d7c1019a856a37ab86ec0bf3a7d493b56c [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
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000030#include "lldb/Core/DataBufferHeap.h"
31#include "lldb/Core/DataBufferMemoryMap.h"
32#include "lldb/Core/RegularExpression.h"
33#include "lldb/Core/StreamString.h"
34#include "lldb/Core/Stream.h"
35#include "lldb/Host/File.h"
36#include "lldb/Host/FileSpec.h"
37#include "lldb/Host/FileSystem.h"
38#include "lldb/Host/Host.h"
39#include "lldb/Utility/CleanUp.h"
40
Caroline Tice391a9602010-09-12 00:10:52 +000041#include "llvm/ADT/StringRef.h"
Zachary Turner3f559742014-08-07 17:33:36 +000042#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000043#include "llvm/Support/Path.h"
44#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000045
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046using namespace lldb;
47using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048
49static bool
50GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
51{
52 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000053 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054 return ::stat (resolved_path, stats_ptr) == 0;
55 return false;
56}
57
Jim Inghamf818ca32010-07-01 01:48:53 +000058// Resolves the username part of a path of the form ~user/other/directories, and
Jim Inghamead45cc2014-09-12 23:50:36 +000059// writes the result into dst_path. This will also resolve "~" to the current user.
60// If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
Zachary Turner3f559742014-08-07 17:33:36 +000061void
62FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
Jim Inghamf818ca32010-07-01 01:48:53 +000063{
Zachary Turner3f559742014-08-07 17:33:36 +000064#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
65 if (path.empty() || path[0] != '~')
66 return;
Jim Inghamf818ca32010-07-01 01:48:53 +000067
Jason Molenda3bc66f12015-01-20 04:20:42 +000068 llvm::StringRef path_str(path.data(), path.size());
Zachary Turner3f559742014-08-07 17:33:36 +000069 size_t slash_pos = path_str.find_first_of("/", 1);
Jim Inghamead45cc2014-09-12 23:50:36 +000070 if (slash_pos == 1 || path.size() == 1)
Jim Inghamf818ca32010-07-01 01:48:53 +000071 {
Jim Ingham2f21bbc2014-09-12 23:04:40 +000072 // A path of ~/ resolves to the current user's home dir
Zachary Turner3f559742014-08-07 17:33:36 +000073 llvm::SmallString<64> home_dir;
74 if (!llvm::sys::path::home_directory(home_dir))
75 return;
76
77 // Overwrite the ~ with the first character of the homedir, and insert
78 // the rest. This way we only trigger one move, whereas an insert
79 // followed by a delete (or vice versa) would trigger two.
80 path[0] = home_dir[0];
81 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
82 return;
83 }
84
85 auto username_begin = path.begin()+1;
86 auto username_end = (slash_pos == llvm::StringRef::npos)
87 ? path.end()
88 : (path.begin() + slash_pos);
89 size_t replacement_length = std::distance(path.begin(), username_end);
90
91 llvm::SmallString<20> username(username_begin, username_end);
92 struct passwd *user_entry = ::getpwnam(username.c_str());
93 if (user_entry != nullptr)
94 {
95 // Copy over the first n characters of the path, where n is the smaller of the length
96 // of the home directory and the slash pos.
97 llvm::StringRef homedir(user_entry->pw_dir);
98 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
99 auto src_begin = homedir.begin();
100 auto src_end = src_begin + initial_copy_length;
101 std::copy(src_begin, src_end, path.begin());
102 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000103 {
Zachary Turner3f559742014-08-07 17:33:36 +0000104 // We copied the entire home directory, but the ~username portion of the path was
105 // longer, so there's characters that need to be removed.
106 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000107 }
Zachary Turner3f559742014-08-07 17:33:36 +0000108 else if (replacement_length < homedir.size())
109 {
110 // We copied all the way up to the slash in the destination, but there's still more
111 // characters that need to be inserted.
112 path.insert(username_end, src_end, homedir.end());
113 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000114 }
115 else
116 {
Zachary Turner3f559742014-08-07 17:33:36 +0000117 // Unable to resolve username (user doesn't exist?)
118 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000119 }
Zachary Turner3f559742014-08-07 17:33:36 +0000120#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000121}
122
Greg Claytonc982c762010-07-09 20:39:50 +0000123size_t
Jim Ingham84363072011-02-08 23:24:09 +0000124FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
125{
126#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
127 size_t extant_entries = matches.GetSize();
128
129 setpwent();
130 struct passwd *user_entry;
131 const char *name_start = partial_name + 1;
132 std::set<std::string> name_list;
133
134 while ((user_entry = getpwent()) != NULL)
135 {
136 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
137 {
138 std::string tmp_buf("~");
139 tmp_buf.append(user_entry->pw_name);
140 tmp_buf.push_back('/');
141 name_list.insert(tmp_buf);
142 }
143 }
144 std::set<std::string>::iterator pos, end = name_list.end();
145 for (pos = name_list.begin(); pos != end; pos++)
146 {
147 matches.AppendString((*pos).c_str());
148 }
149 return matches.GetSize() - extant_entries;
150#else
151 // Resolving home directories is not supported, just copy the path...
152 return 0;
153#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
154}
155
Zachary Turner3f559742014-08-07 17:33:36 +0000156void
157FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000158{
Zachary Turner3f559742014-08-07 17:33:36 +0000159 if (path.empty())
160 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000161
Greg Clayton45319462011-02-08 00:35:34 +0000162#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000163 if (path[0] == '~')
164 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000165#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000166
Jason Molenda671a29d2015-02-25 02:35:25 +0000167 // Save a copy of the original path that's passed in
168 llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end());
169
Zachary Turner3f559742014-08-07 17:33:36 +0000170 llvm::sys::fs::make_absolute(path);
Jason Molenda671a29d2015-02-25 02:35:25 +0000171
172
173 path.push_back(0); // Be sure we have a nul terminated string
174 path.pop_back();
175 struct stat file_stats;
176 if (::stat (path.data(), &file_stats) != 0)
177 {
178 path.clear();
179 path.append(original_path.begin(), original_path.end());
180 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000181}
182
Jason Molenda68c85212014-10-15 03:04:33 +0000183FileSpec::FileSpec() :
184 m_directory(),
185 m_filename(),
186 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000187{
188}
189
190//------------------------------------------------------------------
191// Default constructor that can take an optional full path to a
192// file on disk.
193//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000194FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000195 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000196 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000197 m_is_resolved(false),
198 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000199{
200 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000201 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000202}
203
204//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000205// Copy constructor
206//------------------------------------------------------------------
207FileSpec::FileSpec(const FileSpec& rhs) :
208 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000209 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000210 m_is_resolved (rhs.m_is_resolved),
211 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000212{
213}
214
215//------------------------------------------------------------------
216// Copy constructor
217//------------------------------------------------------------------
218FileSpec::FileSpec(const FileSpec* rhs) :
219 m_directory(),
220 m_filename()
221{
222 if (rhs)
223 *this = *rhs;
224}
225
226//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000227// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228//------------------------------------------------------------------
229FileSpec::~FileSpec()
230{
231}
232
233//------------------------------------------------------------------
234// Assignment operator.
235//------------------------------------------------------------------
236const FileSpec&
237FileSpec::operator= (const FileSpec& rhs)
238{
239 if (this != &rhs)
240 {
241 m_directory = rhs.m_directory;
242 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000243 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000244 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 }
246 return *this;
247}
248
Zachary Turner3f559742014-08-07 17:33:36 +0000249void FileSpec::Normalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000250{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000251 if (syntax == ePathSyntaxPosix ||
252 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000253 return;
254
Zachary Turner3f559742014-08-07 17:33:36 +0000255 std::replace(path.begin(), path.end(), '\\', '/');
Hafiz Abid Qadeer93ad6b32015-02-08 20:21:08 +0000256 // Windows path can have \\ slashes which can be changed by replace
257 // call above to //. Here we remove the duplicate.
258 auto iter = std::unique ( path.begin(), path.end(),
259 []( char &c1, char &c2 ){
260 return (c1 == '/' && c2 == '/');});
261 path.erase(iter, path.end());
Zachary Turnerdf62f202014-08-07 17:33:07 +0000262}
263
Zachary Turner3f559742014-08-07 17:33:36 +0000264void FileSpec::DeNormalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000265{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000266 if (syntax == ePathSyntaxPosix ||
267 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000268 return;
269
Zachary Turner3f559742014-08-07 17:33:36 +0000270 std::replace(path.begin(), path.end(), '/', '\\');
Zachary Turnerdf62f202014-08-07 17:33:07 +0000271}
272
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273//------------------------------------------------------------------
274// Update the contents of this object with a new path. The path will
275// be split up into a directory and filename and stored as uniqued
276// string values for quick comparison and efficient memory usage.
277//------------------------------------------------------------------
278void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000279FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000280{
281 m_filename.Clear();
282 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000283 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000284 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000285
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286 if (pathname == NULL || pathname[0] == '\0')
287 return;
288
Zachary Turner3f559742014-08-07 17:33:36 +0000289 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000290
Jim Ingham0909e5f2010-09-16 00:57:33 +0000291 if (resolve)
292 {
Zachary Turner3f559742014-08-07 17:33:36 +0000293 FileSpec::Resolve (normalized);
294 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000295 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000296
297 // Only normalize after resolving the path. Resolution will modify the path
298 // string, potentially adding wrong kinds of slashes to the path, that need
299 // to be re-normalized.
300 Normalize(normalized, syntax);
301
Zachary Turner3f559742014-08-07 17:33:36 +0000302 llvm::StringRef resolve_path_ref(normalized.c_str());
303 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
304 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000305 {
Zachary Turner3f559742014-08-07 17:33:36 +0000306 m_filename.SetString (filename_ref);
307 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
308 if (!directory_ref.empty())
309 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000310 }
Zachary Turner3f559742014-08-07 17:33:36 +0000311 else
312 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313}
314
315//----------------------------------------------------------------------
316// Convert to pointer operator. This allows code to check any FileSpec
317// objects to see if they contain anything valid using code such as:
318//
319// if (file_spec)
320// {}
321//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000322FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000324 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325}
326
327//----------------------------------------------------------------------
328// Logical NOT operator. This allows code to check any FileSpec
329// objects to see if they are invalid using code such as:
330//
331// if (!file_spec)
332// {}
333//----------------------------------------------------------------------
334bool
335FileSpec::operator!() const
336{
337 return !m_directory && !m_filename;
338}
339
340//------------------------------------------------------------------
341// Equal to operator
342//------------------------------------------------------------------
343bool
344FileSpec::operator== (const FileSpec& rhs) const
345{
Greg Clayton7481c202010-11-08 00:28:40 +0000346 if (m_filename == rhs.m_filename)
347 {
348 if (m_directory == rhs.m_directory)
349 return true;
350
351 // TODO: determine if we want to keep this code in here.
352 // The code below was added to handle a case where we were
353 // trying to set a file and line breakpoint and one path
354 // was resolved, and the other not and the directory was
355 // in a mount point that resolved to a more complete path:
356 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
357 // this out...
358 if (IsResolved() && rhs.IsResolved())
359 {
360 // Both paths are resolved, no need to look further...
361 return false;
362 }
363
364 FileSpec resolved_lhs(*this);
365
366 // If "this" isn't resolved, resolve it
367 if (!IsResolved())
368 {
369 if (resolved_lhs.ResolvePath())
370 {
371 // This path wasn't resolved but now it is. Check if the resolved
372 // directory is the same as our unresolved directory, and if so,
373 // we can mark this object as resolved to avoid more future resolves
374 m_is_resolved = (m_directory == resolved_lhs.m_directory);
375 }
376 else
377 return false;
378 }
379
380 FileSpec resolved_rhs(rhs);
381 if (!rhs.IsResolved())
382 {
383 if (resolved_rhs.ResolvePath())
384 {
385 // rhs's path wasn't resolved but now it is. Check if the resolved
386 // directory is the same as rhs's unresolved directory, and if so,
387 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000388 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000389 }
390 else
391 return false;
392 }
393
394 // If we reach this point in the code we were able to resolve both paths
395 // and since we only resolve the paths if the basenames are equal, then
396 // we can just check if both directories are equal...
397 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
398 }
399 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400}
401
402//------------------------------------------------------------------
403// Not equal to operator
404//------------------------------------------------------------------
405bool
406FileSpec::operator!= (const FileSpec& rhs) const
407{
Greg Clayton7481c202010-11-08 00:28:40 +0000408 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409}
410
411//------------------------------------------------------------------
412// Less than operator
413//------------------------------------------------------------------
414bool
415FileSpec::operator< (const FileSpec& rhs) const
416{
417 return FileSpec::Compare(*this, rhs, true) < 0;
418}
419
420//------------------------------------------------------------------
421// Dump a FileSpec object to a stream
422//------------------------------------------------------------------
423Stream&
424lldb_private::operator << (Stream &s, const FileSpec& f)
425{
426 f.Dump(&s);
427 return s;
428}
429
430//------------------------------------------------------------------
431// Clear this object by releasing both the directory and filename
432// string values and making them both the empty string.
433//------------------------------------------------------------------
434void
435FileSpec::Clear()
436{
437 m_directory.Clear();
438 m_filename.Clear();
439}
440
441//------------------------------------------------------------------
442// Compare two FileSpec objects. If "full" is true, then both
443// the directory and the filename must match. If "full" is false,
444// then the directory names for "a" and "b" are only compared if
445// they are both non-empty. This allows a FileSpec object to only
446// contain a filename and it can match FileSpec objects that have
447// matching filenames with different paths.
448//
449// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
450// and "1" if "a" is greater than "b".
451//------------------------------------------------------------------
452int
453FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
454{
455 int result = 0;
456
457 // If full is true, then we must compare both the directory and filename.
458
459 // If full is false, then if either directory is empty, then we match on
460 // the basename only, and if both directories have valid values, we still
461 // do a full compare. This allows for matching when we just have a filename
462 // in one of the FileSpec objects.
463
464 if (full || (a.m_directory && b.m_directory))
465 {
466 result = ConstString::Compare(a.m_directory, b.m_directory);
467 if (result)
468 return result;
469 }
470 return ConstString::Compare (a.m_filename, b.m_filename);
471}
472
473bool
Jim Ingham96a15962014-11-15 01:54:26 +0000474FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000475{
Jim Ingham87df91b2011-09-23 00:54:11 +0000476 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477 return a.m_filename == b.m_filename;
Jim Ingham96a15962014-11-15 01:54:26 +0000478 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000479 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000480 else
481 {
482 if (a.m_filename != b.m_filename)
483 return false;
484 if (a.m_directory == b.m_directory)
485 return true;
486 ConstString a_without_dots;
487 ConstString b_without_dots;
488
489 RemoveBackupDots (a.m_directory, a_without_dots);
490 RemoveBackupDots (b.m_directory, b_without_dots);
491 return a_without_dots == b_without_dots;
492 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493}
494
Jim Ingham96a15962014-11-15 01:54:26 +0000495void
496FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
497{
498 const char *input = input_const_str.GetCString();
499 result_const_str.Clear();
500 if (!input || input[0] == '\0')
501 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000502
Jim Ingham96a15962014-11-15 01:54:26 +0000503 const char win_sep = '\\';
504 const char unix_sep = '/';
505 char found_sep;
506 const char *win_backup = "\\..";
507 const char *unix_backup = "/..";
508
509 bool is_win = false;
510
511 // Determine the platform for the path (win or unix):
512
513 if (input[0] == win_sep)
514 is_win = true;
515 else if (input[0] == unix_sep)
516 is_win = false;
517 else if (input[1] == ':')
518 is_win = true;
519 else if (strchr(input, unix_sep) != nullptr)
520 is_win = false;
521 else if (strchr(input, win_sep) != nullptr)
522 is_win = true;
523 else
524 {
525 // No separators at all, no reason to do any work here.
526 result_const_str = input_const_str;
527 return;
528 }
529
530 llvm::StringRef backup_sep;
531 if (is_win)
532 {
533 found_sep = win_sep;
534 backup_sep = win_backup;
535 }
536 else
537 {
538 found_sep = unix_sep;
539 backup_sep = unix_backup;
540 }
541
542 llvm::StringRef input_ref(input);
543 llvm::StringRef curpos(input);
544
545 bool had_dots = false;
546 std::string result;
547
548 while (1)
549 {
550 // Start of loop
551 llvm::StringRef before_sep;
552 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
553
554 before_sep = around_sep.first;
555 curpos = around_sep.second;
556
557 if (curpos.empty())
558 {
559 if (had_dots)
560 {
561 if (!before_sep.empty())
562 {
563 result.append(before_sep.data(), before_sep.size());
564 }
565 }
566 break;
567 }
568 had_dots = true;
569
570 unsigned num_backups = 1;
571 while (curpos.startswith(backup_sep))
572 {
573 num_backups++;
574 curpos = curpos.slice(backup_sep.size(), curpos.size());
575 }
576
577 size_t end_pos = before_sep.size();
578 while (num_backups-- > 0)
579 {
580 end_pos = before_sep.rfind(found_sep, end_pos);
581 if (end_pos == llvm::StringRef::npos)
582 {
583 result_const_str = input_const_str;
584 return;
585 }
586 }
587 result.append(before_sep.data(), end_pos);
588 }
589
590 if (had_dots)
591 result_const_str.SetCString(result.c_str());
592 else
593 result_const_str = input_const_str;
594
595 return;
596}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597
598//------------------------------------------------------------------
599// Dump the object to the supplied stream. If the object contains
600// a valid directory name, it will be displayed followed by a
601// directory delimiter, and the filename.
602//------------------------------------------------------------------
603void
604FileSpec::Dump(Stream *s) const
605{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000606 static ConstString g_slash_only ("/");
Enrico Granata80fcdd42012-11-03 00:09:46 +0000607 if (s)
608 {
609 m_directory.Dump(s);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000610 if (m_directory && m_directory != g_slash_only)
Enrico Granata80fcdd42012-11-03 00:09:46 +0000611 s->PutChar('/');
612 m_filename.Dump(s);
613 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000614}
615
616//------------------------------------------------------------------
617// Returns true if the file exists.
618//------------------------------------------------------------------
619bool
620FileSpec::Exists () const
621{
622 struct stat file_stats;
623 return GetFileStats (this, &file_stats);
624}
625
Caroline Tice428a9a52010-09-10 04:48:55 +0000626bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000627FileSpec::Readable () const
628{
629 const uint32_t permissions = GetPermissions();
630 if (permissions & eFilePermissionsEveryoneR)
631 return true;
632 return false;
633}
634
635bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000636FileSpec::ResolveExecutableLocation ()
637{
Greg Clayton274060b2010-10-20 20:54:39 +0000638 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000639 {
Greg Clayton58f41712011-01-25 21:32:01 +0000640 const char *file_cstr = m_filename.GetCString();
641 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000642 {
Greg Clayton58f41712011-01-25 21:32:01 +0000643 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000644 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
645 if (!error_or_path)
646 return false;
647 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000648 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000649 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000650 {
Greg Clayton58f41712011-01-25 21:32:01 +0000651 // FindProgramByName returns "." if it can't find the file.
652 if (strcmp (".", dir_ref.data()) == 0)
653 return false;
654
655 m_directory.SetCString (dir_ref.data());
656 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000657 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000658 else
659 {
660 // If FindProgramByName found the file, it returns the directory + filename in its return results.
661 // We need to separate them.
662 FileSpec tmp_file (dir_ref.data(), false);
663 if (tmp_file.Exists())
664 {
665 m_directory = tmp_file.m_directory;
666 return true;
667 }
Caroline Tice391a9602010-09-12 00:10:52 +0000668 }
669 }
670 }
671 }
672
673 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000674}
675
Jim Ingham0909e5f2010-09-16 00:57:33 +0000676bool
677FileSpec::ResolvePath ()
678{
Greg Clayton7481c202010-11-08 00:28:40 +0000679 if (m_is_resolved)
680 return true; // We have already resolved this path
681
682 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000683 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000684 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000685 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000686 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000687 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000688}
689
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690uint64_t
691FileSpec::GetByteSize() const
692{
693 struct stat file_stats;
694 if (GetFileStats (this, &file_stats))
695 return file_stats.st_size;
696 return 0;
697}
698
Zachary Turnerdf62f202014-08-07 17:33:07 +0000699FileSpec::PathSyntax
700FileSpec::GetPathSyntax() const
701{
702 return m_syntax;
703}
704
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705FileSpec::FileType
706FileSpec::GetFileType () const
707{
708 struct stat file_stats;
709 if (GetFileStats (this, &file_stats))
710 {
711 mode_t file_type = file_stats.st_mode & S_IFMT;
712 switch (file_type)
713 {
714 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000716#ifndef _WIN32
717 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 case S_IFSOCK: return eFileTypeSocket;
719 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000720#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 default:
722 break;
723 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000724 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 }
726 return eFileTypeInvalid;
727}
728
Greg Claytonfbb76342013-11-20 21:07:01 +0000729uint32_t
730FileSpec::GetPermissions () const
731{
732 uint32_t file_permissions = 0;
733 if (*this)
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000734 FileSystem::GetFilePermissions(GetPath().c_str(), file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000735 return file_permissions;
736}
737
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738TimeValue
739FileSpec::GetModificationTime () const
740{
741 TimeValue mod_time;
742 struct stat file_stats;
743 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000744 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745 return mod_time;
746}
747
748//------------------------------------------------------------------
749// Directory string get accessor.
750//------------------------------------------------------------------
751ConstString &
752FileSpec::GetDirectory()
753{
754 return m_directory;
755}
756
757//------------------------------------------------------------------
758// Directory string const get accessor.
759//------------------------------------------------------------------
760const ConstString &
761FileSpec::GetDirectory() const
762{
763 return m_directory;
764}
765
766//------------------------------------------------------------------
767// Filename string get accessor.
768//------------------------------------------------------------------
769ConstString &
770FileSpec::GetFilename()
771{
772 return m_filename;
773}
774
775//------------------------------------------------------------------
776// Filename string const get accessor.
777//------------------------------------------------------------------
778const ConstString &
779FileSpec::GetFilename() const
780{
781 return m_filename;
782}
783
784//------------------------------------------------------------------
785// Extract the directory and path into a fixed buffer. This is
786// needed as the directory and path are stored in separate string
787// values.
788//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000789size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000790FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000792 if (!path)
793 return 0;
794
Zachary Turnerdf62f202014-08-07 17:33:07 +0000795 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000796 ::snprintf(path, path_max_len, "%s", result.c_str());
797 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798}
799
Greg Claytona44c1e62013-04-29 16:36:27 +0000800std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000801FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000802{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000803 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000804 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000805 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000806}
807
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000808void
809FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
810{
811 if (m_directory)
812 path.append(m_directory.GetCString(), m_directory.GetCString() + m_directory.GetLength());
813 if (m_filename)
814 llvm::sys::path::append(path, m_filename.GetCString());
815 Normalize(path, m_syntax);
816 if (denormalize && !path.empty())
817 DeNormalize(path, m_syntax);
818}
819
Enrico Granataa9dbf432011-10-17 21:45:27 +0000820ConstString
821FileSpec::GetFileNameExtension () const
822{
Greg Clayton1f746072012-08-29 21:13:06 +0000823 if (m_filename)
824 {
825 const char *filename = m_filename.GetCString();
826 const char* dot_pos = strrchr(filename, '.');
827 if (dot_pos && dot_pos[1] != '\0')
828 return ConstString(dot_pos+1);
829 }
830 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000831}
832
833ConstString
834FileSpec::GetFileNameStrippingExtension () const
835{
836 const char *filename = m_filename.GetCString();
837 if (filename == NULL)
838 return ConstString();
839
Johnny Chenf5df5372011-10-18 19:28:30 +0000840 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000841 if (dot_pos == NULL)
842 return m_filename;
843
844 return ConstString(filename, dot_pos-filename);
845}
846
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847//------------------------------------------------------------------
848// Returns a shared pointer to a data buffer that contains all or
849// part of the contents of a file. The data is memory mapped and
850// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000851// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852// file, and "file_size" bytes will be mapped. If "file_size" is
853// greater than the number of bytes available in the file starting
854// at "file_offset", the number of bytes will be appropriately
855// truncated. The final number of bytes that get mapped can be
856// verified using the DataBuffer::GetByteSize() function.
857//------------------------------------------------------------------
858DataBufferSP
859FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
860{
861 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000862 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000863 if (mmap_data.get())
864 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000865 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
866 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867 data_sp.reset(mmap_data.release());
868 }
869 return data_sp;
870}
871
Greg Clayton736888c2015-02-23 23:47:09 +0000872DataBufferSP
873FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
874{
875 if (FileSystem::IsLocal(*this))
876 return MemoryMapFileContents(file_offset, file_size);
877 else
878 return ReadFileContents(file_offset, file_size, NULL);
879}
880
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881
882//------------------------------------------------------------------
883// Return the size in bytes that this object takes in memory. This
884// returns the size in bytes of this object, not any shared string
885// values it may refer to.
886//------------------------------------------------------------------
887size_t
888FileSpec::MemorySize() const
889{
890 return m_filename.MemorySize() + m_directory.MemorySize();
891}
892
Greg Claytondda4f7b2010-06-30 23:03:03 +0000893
894size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000895FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000896{
Greg Clayton4017fa32012-01-06 02:01:06 +0000897 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000898 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000899 char resolved_path[PATH_MAX];
900 if (GetPath(resolved_path, sizeof(resolved_path)))
901 {
Greg Clayton96c09682012-01-04 22:56:43 +0000902 File file;
903 error = file.Open(resolved_path, File::eOpenOptionRead);
904 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Clayton96c09682012-01-04 22:56:43 +0000906 off_t file_offset_after_seek = file_offset;
907 bytes_read = dst_len;
908 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000909 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000910 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000911 else
912 {
913 error.SetErrorString("invalid file specification");
914 }
915 if (error_ptr)
916 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000917 return bytes_read;
918}
919
920//------------------------------------------------------------------
921// Returns a shared pointer to a data buffer that contains all or
922// part of the contents of a file. The data copies into a heap based
923// buffer that lives in the DataBuffer shared pointer object returned.
924// The data that is cached will start "file_offset" bytes into the
925// file, and "file_size" bytes will be mapped. If "file_size" is
926// greater than the number of bytes available in the file starting
927// at "file_offset", the number of bytes will be appropriately
928// truncated. The final number of bytes that get mapped can be
929// verified using the DataBuffer::GetByteSize() function.
930//------------------------------------------------------------------
931DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000932FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000933{
Greg Clayton4017fa32012-01-06 02:01:06 +0000934 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000935 DataBufferSP data_sp;
936 char resolved_path[PATH_MAX];
937 if (GetPath(resolved_path, sizeof(resolved_path)))
938 {
Greg Clayton96c09682012-01-04 22:56:43 +0000939 File file;
940 error = file.Open(resolved_path, File::eOpenOptionRead);
941 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000942 {
943 const bool null_terminate = false;
944 error = file.Read (file_size, file_offset, null_terminate, data_sp);
945 }
946 }
947 else
948 {
949 error.SetErrorString("invalid file specification");
950 }
951 if (error_ptr)
952 *error_ptr = error;
953 return data_sp;
954}
955
956DataBufferSP
957FileSpec::ReadFileContentsAsCString(Error *error_ptr)
958{
959 Error error;
960 DataBufferSP data_sp;
961 char resolved_path[PATH_MAX];
962 if (GetPath(resolved_path, sizeof(resolved_path)))
963 {
964 File file;
965 error = file.Open(resolved_path, File::eOpenOptionRead);
966 if (error.Success())
967 {
968 off_t offset = 0;
969 size_t length = SIZE_MAX;
970 const bool null_terminate = true;
971 error = file.Read (length, offset, null_terminate, data_sp);
972 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000974 else
975 {
976 error.SetErrorString("invalid file specification");
977 }
978 if (error_ptr)
979 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 return data_sp;
981}
982
Greg Clayton58fc50e2010-10-20 22:52:05 +0000983size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984FileSpec::ReadFileLines (STLStringArray &lines)
985{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000987 char path[PATH_MAX];
988 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000990 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
Greg Clayton58fc50e2010-10-20 22:52:05 +0000992 if (file_stream)
993 {
994 std::string line;
995 while (getline (file_stream, line))
996 lines.push_back (line);
997 }
998 }
999 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000}
Greg Clayton4272cc72011-02-02 02:24:04 +00001001
1002FileSpec::EnumerateDirectoryResult
1003FileSpec::EnumerateDirectory
1004(
1005 const char *dir_path,
1006 bool find_directories,
1007 bool find_files,
1008 bool find_other,
1009 EnumerateDirectoryCallbackType callback,
1010 void *callback_baton
1011)
1012{
1013 if (dir_path && dir_path[0])
1014 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001015#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001016 std::string szDir(dir_path);
1017 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001018
1019 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001020 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001021
1022 if (hFind == INVALID_HANDLE_VALUE)
1023 {
1024 return eEnumerateDirectoryResultNext;
1025 }
1026
1027 do
1028 {
1029 bool call_callback = false;
1030 FileSpec::FileType file_type = eFileTypeUnknown;
1031 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1032 {
1033 size_t len = strlen(ffd.cFileName);
1034
1035 if (len == 1 && ffd.cFileName[0] == '.')
1036 continue;
1037
1038 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1039 continue;
1040
1041 file_type = eFileTypeDirectory;
1042 call_callback = find_directories;
1043 }
1044 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1045 {
1046 file_type = eFileTypeOther;
1047 call_callback = find_other;
1048 }
1049 else
1050 {
1051 file_type = eFileTypeRegular;
1052 call_callback = find_files;
1053 }
1054 if (call_callback)
1055 {
1056 char child_path[MAX_PATH];
1057 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1058 if (child_path_len < (int)(sizeof(child_path) - 1))
1059 {
1060 // Don't resolve the file type or path
1061 FileSpec child_path_spec (child_path, false);
1062
1063 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1064
1065 switch (result)
1066 {
1067 case eEnumerateDirectoryResultNext:
1068 // Enumerate next entry in the current directory. We just
1069 // exit this switch and will continue enumerating the
1070 // current directory as we currently are...
1071 break;
1072
1073 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1074 if (FileSpec::EnumerateDirectory(child_path,
1075 find_directories,
1076 find_files,
1077 find_other,
1078 callback,
1079 callback_baton) == eEnumerateDirectoryResultQuit)
1080 {
1081 // The subdirectory returned Quit, which means to
1082 // stop all directory enumerations at all levels.
1083 return eEnumerateDirectoryResultQuit;
1084 }
1085 break;
1086
1087 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1088 // Exit from this directory level and tell parent to
1089 // keep enumerating.
1090 return eEnumerateDirectoryResultNext;
1091
1092 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1093 return eEnumerateDirectoryResultQuit;
1094 }
1095 }
1096 }
1097 } while (FindNextFile(hFind, &ffd) != 0);
1098
1099 FindClose(hFind);
1100#else
1101 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001102 if (dir_path_dir.is_valid())
1103 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001104 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1105
Jason Molenda14aef122013-04-04 03:19:27 +00001106 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1107#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1108 if (path_max < __DARWIN_MAXPATHLEN)
1109 path_max = __DARWIN_MAXPATHLEN;
1110#endif
1111 struct dirent *buf, *dp;
1112 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1113
1114 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001115 {
1116 // Only search directories
1117 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1118 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001119 size_t len = strlen(dp->d_name);
1120
1121 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001122 continue;
1123
Greg Claytone0f3c022011-02-07 17:41:11 +00001124 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001125 continue;
1126 }
1127
1128 bool call_callback = false;
1129 FileSpec::FileType file_type = eFileTypeUnknown;
1130
1131 switch (dp->d_type)
1132 {
1133 default:
1134 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1135 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1136 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1137 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1138 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1139 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1140 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1141 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001142#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001143 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001144#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001145 }
1146
1147 if (call_callback)
1148 {
1149 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001150
1151 // Don't make paths with "/foo//bar", that just confuses everybody.
1152 int child_path_len;
1153 if (dir_path_last_char == '/')
1154 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1155 else
1156 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1157
Johnny Chen44805302011-07-19 19:48:13 +00001158 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001159 {
1160 // Don't resolve the file type or path
1161 FileSpec child_path_spec (child_path, false);
1162
1163 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1164
1165 switch (result)
1166 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001167 case eEnumerateDirectoryResultNext:
1168 // Enumerate next entry in the current directory. We just
1169 // exit this switch and will continue enumerating the
1170 // current directory as we currently are...
1171 break;
1172
1173 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1174 if (FileSpec::EnumerateDirectory (child_path,
1175 find_directories,
1176 find_files,
1177 find_other,
1178 callback,
1179 callback_baton) == eEnumerateDirectoryResultQuit)
1180 {
1181 // The subdirectory returned Quit, which means to
1182 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001183 if (buf)
1184 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001185 return eEnumerateDirectoryResultQuit;
1186 }
1187 break;
1188
1189 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1190 // Exit from this directory level and tell parent to
1191 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001192 if (buf)
1193 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001194 return eEnumerateDirectoryResultNext;
1195
1196 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001197 if (buf)
1198 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001199 return eEnumerateDirectoryResultQuit;
1200 }
1201 }
1202 }
1203 }
Jason Molenda14aef122013-04-04 03:19:27 +00001204 if (buf)
1205 {
1206 free (buf);
1207 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001208 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001209#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001210 }
1211 // By default when exiting a directory, we tell the parent enumeration
1212 // to continue enumerating.
1213 return eEnumerateDirectoryResultNext;
1214}
1215
Daniel Maleae0f8f572013-08-26 23:57:52 +00001216FileSpec
1217FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1218{
1219 const bool resolve = false;
1220 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1221 return FileSpec(new_path,resolve);
1222 StreamString stream;
1223 if (m_filename.IsEmpty())
1224 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1225 else if (m_directory.IsEmpty())
1226 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1227 else
1228 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1229 return FileSpec(stream.GetData(),resolve);
1230}
1231
1232FileSpec
1233FileSpec::CopyByRemovingLastPathComponent () const
1234{
1235 const bool resolve = false;
1236 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1237 return FileSpec("",resolve);
1238 if (m_directory.IsEmpty())
1239 return FileSpec("",resolve);
1240 if (m_filename.IsEmpty())
1241 {
1242 const char* dir_cstr = m_directory.GetCString();
1243 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1244
1245 // check for obvious cases before doing the full thing
1246 if (!last_slash_ptr)
1247 return FileSpec("",resolve);
1248 if (last_slash_ptr == dir_cstr)
1249 return FileSpec("/",resolve);
1250
1251 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1252 ConstString new_path(dir_cstr,last_slash_pos);
1253 return FileSpec(new_path.GetCString(),resolve);
1254 }
1255 else
1256 return FileSpec(m_directory.GetCString(),resolve);
1257}
1258
Greg Claytonfbb76342013-11-20 21:07:01 +00001259ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001260FileSpec::GetLastPathComponent () const
1261{
Greg Claytonfbb76342013-11-20 21:07:01 +00001262 if (m_filename)
1263 return m_filename;
1264 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001265 {
1266 const char* dir_cstr = m_directory.GetCString();
1267 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1268 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001269 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001270 if (last_slash_ptr == dir_cstr)
1271 {
1272 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001273 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001274 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001275 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001276 }
1277 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001278 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001279 const char* penultimate_slash_ptr = last_slash_ptr;
1280 while (*penultimate_slash_ptr)
1281 {
1282 --penultimate_slash_ptr;
1283 if (penultimate_slash_ptr == dir_cstr)
1284 break;
1285 if (*penultimate_slash_ptr == '/')
1286 break;
1287 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001288 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1289 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001290 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001291 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001292}
1293
1294void
1295FileSpec::AppendPathComponent (const char *new_path)
1296{
1297 const bool resolve = false;
1298 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1299 {
1300 SetFile(new_path,resolve);
1301 return;
1302 }
1303 StreamString stream;
1304 if (m_filename.IsEmpty())
1305 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1306 else if (m_directory.IsEmpty())
1307 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1308 else
1309 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1310 SetFile(stream.GetData(), resolve);
1311}
1312
1313void
1314FileSpec::RemoveLastPathComponent ()
1315{
1316 const bool resolve = false;
1317 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1318 {
1319 SetFile("",resolve);
1320 return;
1321 }
1322 if (m_directory.IsEmpty())
1323 {
1324 SetFile("",resolve);
1325 return;
1326 }
1327 if (m_filename.IsEmpty())
1328 {
1329 const char* dir_cstr = m_directory.GetCString();
1330 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1331
1332 // check for obvious cases before doing the full thing
1333 if (!last_slash_ptr)
1334 {
1335 SetFile("",resolve);
1336 return;
1337 }
1338 if (last_slash_ptr == dir_cstr)
1339 {
1340 SetFile("/",resolve);
1341 return;
1342 }
1343 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1344 ConstString new_path(dir_cstr,last_slash_pos);
1345 SetFile(new_path.GetCString(),resolve);
1346 }
1347 else
1348 SetFile(m_directory.GetCString(),resolve);
1349}
Greg Clayton1f746072012-08-29 21:13:06 +00001350//------------------------------------------------------------------
1351/// Returns true if the filespec represents an implementation source
1352/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1353/// extension).
1354///
1355/// @return
1356/// \b true if the filespec represents an implementation source
1357/// file, \b false otherwise.
1358//------------------------------------------------------------------
1359bool
1360FileSpec::IsSourceImplementationFile () const
1361{
1362 ConstString extension (GetFileNameExtension());
1363 if (extension)
1364 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001365 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 +00001366 return g_source_file_regex.Execute (extension.GetCString());
1367 }
1368 return false;
1369}
1370
Greg Claytona0ca6602012-10-18 16:33:33 +00001371bool
1372FileSpec::IsRelativeToCurrentWorkingDirectory () const
1373{
Zachary Turner270e99a2014-12-08 21:36:42 +00001374 const char *dir = m_directory.GetCString();
1375 llvm::StringRef directory(dir ? dir : "");
1376
1377 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001378 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001379 if (m_syntax == ePathSyntaxWindows)
Greg Claytona0ca6602012-10-18 16:33:33 +00001380 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001381 if (directory.size() >= 2 && directory[1] == ':')
1382 return false;
1383 if (directory[0] == '/')
1384 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001385 return true;
1386 }
Zachary Turner270e99a2014-12-08 21:36:42 +00001387 else
1388 {
1389 // If the path doesn't start with '/' or '~', return true
1390 switch (directory[0])
1391 {
1392 case '/':
1393 case '~':
1394 return false;
1395 default:
1396 return true;
1397 }
1398 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001399 }
1400 else if (m_filename)
1401 {
1402 // No directory, just a basename, return true
1403 return true;
1404 }
1405 return false;
1406}