blob: 19f3b93f087adbeb070928ee31cb7cc4bfe1abe3 [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
Zachary Turner3f559742014-08-07 17:33:36 +0000167 llvm::sys::fs::make_absolute(path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168}
169
Jason Molenda68c85212014-10-15 03:04:33 +0000170FileSpec::FileSpec() :
171 m_directory(),
172 m_filename(),
173 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000174{
175}
176
177//------------------------------------------------------------------
178// Default constructor that can take an optional full path to a
179// file on disk.
180//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000181FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000182 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000183 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000184 m_is_resolved(false),
185 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000186{
187 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000188 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000189}
190
191//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192// Copy constructor
193//------------------------------------------------------------------
194FileSpec::FileSpec(const FileSpec& rhs) :
195 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000196 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000197 m_is_resolved (rhs.m_is_resolved),
198 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199{
200}
201
202//------------------------------------------------------------------
203// Copy constructor
204//------------------------------------------------------------------
205FileSpec::FileSpec(const FileSpec* rhs) :
206 m_directory(),
207 m_filename()
208{
209 if (rhs)
210 *this = *rhs;
211}
212
213//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000214// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000215//------------------------------------------------------------------
216FileSpec::~FileSpec()
217{
218}
219
220//------------------------------------------------------------------
221// Assignment operator.
222//------------------------------------------------------------------
223const FileSpec&
224FileSpec::operator= (const FileSpec& rhs)
225{
226 if (this != &rhs)
227 {
228 m_directory = rhs.m_directory;
229 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000230 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000231 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232 }
233 return *this;
234}
235
Zachary Turner3f559742014-08-07 17:33:36 +0000236void FileSpec::Normalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000237{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000238 if (syntax == ePathSyntaxPosix ||
239 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000240 return;
241
Zachary Turner3f559742014-08-07 17:33:36 +0000242 std::replace(path.begin(), path.end(), '\\', '/');
Hafiz Abid Qadeer93ad6b32015-02-08 20:21:08 +0000243 // Windows path can have \\ slashes which can be changed by replace
244 // call above to //. Here we remove the duplicate.
245 auto iter = std::unique ( path.begin(), path.end(),
246 []( char &c1, char &c2 ){
247 return (c1 == '/' && c2 == '/');});
248 path.erase(iter, path.end());
Zachary Turnerdf62f202014-08-07 17:33:07 +0000249}
250
Zachary Turner3f559742014-08-07 17:33:36 +0000251void FileSpec::DeNormalize(llvm::SmallVectorImpl<char> &path, PathSyntax syntax)
Zachary Turnerdf62f202014-08-07 17:33:07 +0000252{
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000253 if (syntax == ePathSyntaxPosix ||
254 (syntax == ePathSyntaxHostNative && FileSystem::GetNativePathSyntax() == ePathSyntaxPosix))
Zachary Turnerdf62f202014-08-07 17:33:07 +0000255 return;
256
Zachary Turner3f559742014-08-07 17:33:36 +0000257 std::replace(path.begin(), path.end(), '/', '\\');
Zachary Turnerdf62f202014-08-07 17:33:07 +0000258}
259
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000260//------------------------------------------------------------------
261// Update the contents of this object with a new path. The path will
262// be split up into a directory and filename and stored as uniqued
263// string values for quick comparison and efficient memory usage.
264//------------------------------------------------------------------
265void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000266FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267{
268 m_filename.Clear();
269 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000270 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000271 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000272
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273 if (pathname == NULL || pathname[0] == '\0')
274 return;
275
Zachary Turner3f559742014-08-07 17:33:36 +0000276 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000277
Jim Ingham0909e5f2010-09-16 00:57:33 +0000278 if (resolve)
279 {
Zachary Turner3f559742014-08-07 17:33:36 +0000280 FileSpec::Resolve (normalized);
281 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000282 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000283
284 // Only normalize after resolving the path. Resolution will modify the path
285 // string, potentially adding wrong kinds of slashes to the path, that need
286 // to be re-normalized.
287 Normalize(normalized, syntax);
288
Zachary Turner3f559742014-08-07 17:33:36 +0000289 llvm::StringRef resolve_path_ref(normalized.c_str());
290 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
291 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292 {
Zachary Turner3f559742014-08-07 17:33:36 +0000293 m_filename.SetString (filename_ref);
294 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
295 if (!directory_ref.empty())
296 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297 }
Zachary Turner3f559742014-08-07 17:33:36 +0000298 else
299 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300}
301
302//----------------------------------------------------------------------
303// Convert to pointer operator. This allows code to check any FileSpec
304// objects to see if they contain anything valid using code such as:
305//
306// if (file_spec)
307// {}
308//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000309FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000310{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000311 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
314//----------------------------------------------------------------------
315// Logical NOT operator. This allows code to check any FileSpec
316// objects to see if they are invalid using code such as:
317//
318// if (!file_spec)
319// {}
320//----------------------------------------------------------------------
321bool
322FileSpec::operator!() const
323{
324 return !m_directory && !m_filename;
325}
326
327//------------------------------------------------------------------
328// Equal to operator
329//------------------------------------------------------------------
330bool
331FileSpec::operator== (const FileSpec& rhs) const
332{
Greg Clayton7481c202010-11-08 00:28:40 +0000333 if (m_filename == rhs.m_filename)
334 {
335 if (m_directory == rhs.m_directory)
336 return true;
337
338 // TODO: determine if we want to keep this code in here.
339 // The code below was added to handle a case where we were
340 // trying to set a file and line breakpoint and one path
341 // was resolved, and the other not and the directory was
342 // in a mount point that resolved to a more complete path:
343 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
344 // this out...
345 if (IsResolved() && rhs.IsResolved())
346 {
347 // Both paths are resolved, no need to look further...
348 return false;
349 }
350
351 FileSpec resolved_lhs(*this);
352
353 // If "this" isn't resolved, resolve it
354 if (!IsResolved())
355 {
356 if (resolved_lhs.ResolvePath())
357 {
358 // This path wasn't resolved but now it is. Check if the resolved
359 // directory is the same as our unresolved directory, and if so,
360 // we can mark this object as resolved to avoid more future resolves
361 m_is_resolved = (m_directory == resolved_lhs.m_directory);
362 }
363 else
364 return false;
365 }
366
367 FileSpec resolved_rhs(rhs);
368 if (!rhs.IsResolved())
369 {
370 if (resolved_rhs.ResolvePath())
371 {
372 // rhs's path wasn't resolved but now it is. Check if the resolved
373 // directory is the same as rhs's unresolved directory, and if so,
374 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000375 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000376 }
377 else
378 return false;
379 }
380
381 // If we reach this point in the code we were able to resolve both paths
382 // and since we only resolve the paths if the basenames are equal, then
383 // we can just check if both directories are equal...
384 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
385 }
386 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387}
388
389//------------------------------------------------------------------
390// Not equal to operator
391//------------------------------------------------------------------
392bool
393FileSpec::operator!= (const FileSpec& rhs) const
394{
Greg Clayton7481c202010-11-08 00:28:40 +0000395 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396}
397
398//------------------------------------------------------------------
399// Less than operator
400//------------------------------------------------------------------
401bool
402FileSpec::operator< (const FileSpec& rhs) const
403{
404 return FileSpec::Compare(*this, rhs, true) < 0;
405}
406
407//------------------------------------------------------------------
408// Dump a FileSpec object to a stream
409//------------------------------------------------------------------
410Stream&
411lldb_private::operator << (Stream &s, const FileSpec& f)
412{
413 f.Dump(&s);
414 return s;
415}
416
417//------------------------------------------------------------------
418// Clear this object by releasing both the directory and filename
419// string values and making them both the empty string.
420//------------------------------------------------------------------
421void
422FileSpec::Clear()
423{
424 m_directory.Clear();
425 m_filename.Clear();
426}
427
428//------------------------------------------------------------------
429// Compare two FileSpec objects. If "full" is true, then both
430// the directory and the filename must match. If "full" is false,
431// then the directory names for "a" and "b" are only compared if
432// they are both non-empty. This allows a FileSpec object to only
433// contain a filename and it can match FileSpec objects that have
434// matching filenames with different paths.
435//
436// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
437// and "1" if "a" is greater than "b".
438//------------------------------------------------------------------
439int
440FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
441{
442 int result = 0;
443
444 // If full is true, then we must compare both the directory and filename.
445
446 // If full is false, then if either directory is empty, then we match on
447 // the basename only, and if both directories have valid values, we still
448 // do a full compare. This allows for matching when we just have a filename
449 // in one of the FileSpec objects.
450
451 if (full || (a.m_directory && b.m_directory))
452 {
453 result = ConstString::Compare(a.m_directory, b.m_directory);
454 if (result)
455 return result;
456 }
457 return ConstString::Compare (a.m_filename, b.m_filename);
458}
459
460bool
Jim Ingham96a15962014-11-15 01:54:26 +0000461FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462{
Jim Ingham87df91b2011-09-23 00:54:11 +0000463 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464 return a.m_filename == b.m_filename;
Jim Ingham96a15962014-11-15 01:54:26 +0000465 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000466 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000467 else
468 {
469 if (a.m_filename != b.m_filename)
470 return false;
471 if (a.m_directory == b.m_directory)
472 return true;
473 ConstString a_without_dots;
474 ConstString b_without_dots;
475
476 RemoveBackupDots (a.m_directory, a_without_dots);
477 RemoveBackupDots (b.m_directory, b_without_dots);
478 return a_without_dots == b_without_dots;
479 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000480}
481
Jim Ingham96a15962014-11-15 01:54:26 +0000482void
483FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
484{
485 const char *input = input_const_str.GetCString();
486 result_const_str.Clear();
487 if (!input || input[0] == '\0')
488 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489
Jim Ingham96a15962014-11-15 01:54:26 +0000490 const char win_sep = '\\';
491 const char unix_sep = '/';
492 char found_sep;
493 const char *win_backup = "\\..";
494 const char *unix_backup = "/..";
495
496 bool is_win = false;
497
498 // Determine the platform for the path (win or unix):
499
500 if (input[0] == win_sep)
501 is_win = true;
502 else if (input[0] == unix_sep)
503 is_win = false;
504 else if (input[1] == ':')
505 is_win = true;
506 else if (strchr(input, unix_sep) != nullptr)
507 is_win = false;
508 else if (strchr(input, win_sep) != nullptr)
509 is_win = true;
510 else
511 {
512 // No separators at all, no reason to do any work here.
513 result_const_str = input_const_str;
514 return;
515 }
516
517 llvm::StringRef backup_sep;
518 if (is_win)
519 {
520 found_sep = win_sep;
521 backup_sep = win_backup;
522 }
523 else
524 {
525 found_sep = unix_sep;
526 backup_sep = unix_backup;
527 }
528
529 llvm::StringRef input_ref(input);
530 llvm::StringRef curpos(input);
531
532 bool had_dots = false;
533 std::string result;
534
535 while (1)
536 {
537 // Start of loop
538 llvm::StringRef before_sep;
539 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
540
541 before_sep = around_sep.first;
542 curpos = around_sep.second;
543
544 if (curpos.empty())
545 {
546 if (had_dots)
547 {
548 if (!before_sep.empty())
549 {
550 result.append(before_sep.data(), before_sep.size());
551 }
552 }
553 break;
554 }
555 had_dots = true;
556
557 unsigned num_backups = 1;
558 while (curpos.startswith(backup_sep))
559 {
560 num_backups++;
561 curpos = curpos.slice(backup_sep.size(), curpos.size());
562 }
563
564 size_t end_pos = before_sep.size();
565 while (num_backups-- > 0)
566 {
567 end_pos = before_sep.rfind(found_sep, end_pos);
568 if (end_pos == llvm::StringRef::npos)
569 {
570 result_const_str = input_const_str;
571 return;
572 }
573 }
574 result.append(before_sep.data(), end_pos);
575 }
576
577 if (had_dots)
578 result_const_str.SetCString(result.c_str());
579 else
580 result_const_str = input_const_str;
581
582 return;
583}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584
585//------------------------------------------------------------------
586// Dump the object to the supplied stream. If the object contains
587// a valid directory name, it will be displayed followed by a
588// directory delimiter, and the filename.
589//------------------------------------------------------------------
590void
591FileSpec::Dump(Stream *s) const
592{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000593 static ConstString g_slash_only ("/");
Enrico Granata80fcdd42012-11-03 00:09:46 +0000594 if (s)
595 {
596 m_directory.Dump(s);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000597 if (m_directory && m_directory != g_slash_only)
Enrico Granata80fcdd42012-11-03 00:09:46 +0000598 s->PutChar('/');
599 m_filename.Dump(s);
600 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601}
602
603//------------------------------------------------------------------
604// Returns true if the file exists.
605//------------------------------------------------------------------
606bool
607FileSpec::Exists () const
608{
609 struct stat file_stats;
610 return GetFileStats (this, &file_stats);
611}
612
Caroline Tice428a9a52010-09-10 04:48:55 +0000613bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000614FileSpec::Readable () const
615{
616 const uint32_t permissions = GetPermissions();
617 if (permissions & eFilePermissionsEveryoneR)
618 return true;
619 return false;
620}
621
622bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000623FileSpec::ResolveExecutableLocation ()
624{
Greg Clayton274060b2010-10-20 20:54:39 +0000625 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000626 {
Greg Clayton58f41712011-01-25 21:32:01 +0000627 const char *file_cstr = m_filename.GetCString();
628 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000629 {
Greg Clayton58f41712011-01-25 21:32:01 +0000630 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000631 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
632 if (!error_or_path)
633 return false;
634 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000635 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000636 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000637 {
Greg Clayton58f41712011-01-25 21:32:01 +0000638 // FindProgramByName returns "." if it can't find the file.
639 if (strcmp (".", dir_ref.data()) == 0)
640 return false;
641
642 m_directory.SetCString (dir_ref.data());
643 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000644 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000645 else
646 {
647 // If FindProgramByName found the file, it returns the directory + filename in its return results.
648 // We need to separate them.
649 FileSpec tmp_file (dir_ref.data(), false);
650 if (tmp_file.Exists())
651 {
652 m_directory = tmp_file.m_directory;
653 return true;
654 }
Caroline Tice391a9602010-09-12 00:10:52 +0000655 }
656 }
657 }
658 }
659
660 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000661}
662
Jim Ingham0909e5f2010-09-16 00:57:33 +0000663bool
664FileSpec::ResolvePath ()
665{
Greg Clayton7481c202010-11-08 00:28:40 +0000666 if (m_is_resolved)
667 return true; // We have already resolved this path
668
669 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000670 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000671 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000672 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000673 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000674 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000675}
676
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677uint64_t
678FileSpec::GetByteSize() const
679{
680 struct stat file_stats;
681 if (GetFileStats (this, &file_stats))
682 return file_stats.st_size;
683 return 0;
684}
685
Zachary Turnerdf62f202014-08-07 17:33:07 +0000686FileSpec::PathSyntax
687FileSpec::GetPathSyntax() const
688{
689 return m_syntax;
690}
691
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692FileSpec::FileType
693FileSpec::GetFileType () const
694{
695 struct stat file_stats;
696 if (GetFileStats (this, &file_stats))
697 {
698 mode_t file_type = file_stats.st_mode & S_IFMT;
699 switch (file_type)
700 {
701 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000703#ifndef _WIN32
704 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 case S_IFSOCK: return eFileTypeSocket;
706 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000707#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 default:
709 break;
710 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000711 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 }
713 return eFileTypeInvalid;
714}
715
Greg Claytonfbb76342013-11-20 21:07:01 +0000716uint32_t
717FileSpec::GetPermissions () const
718{
719 uint32_t file_permissions = 0;
720 if (*this)
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000721 FileSystem::GetFilePermissions(GetPath().c_str(), file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000722 return file_permissions;
723}
724
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725TimeValue
726FileSpec::GetModificationTime () const
727{
728 TimeValue mod_time;
729 struct stat file_stats;
730 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000731 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 return mod_time;
733}
734
735//------------------------------------------------------------------
736// Directory string get accessor.
737//------------------------------------------------------------------
738ConstString &
739FileSpec::GetDirectory()
740{
741 return m_directory;
742}
743
744//------------------------------------------------------------------
745// Directory string const get accessor.
746//------------------------------------------------------------------
747const ConstString &
748FileSpec::GetDirectory() const
749{
750 return m_directory;
751}
752
753//------------------------------------------------------------------
754// Filename string get accessor.
755//------------------------------------------------------------------
756ConstString &
757FileSpec::GetFilename()
758{
759 return m_filename;
760}
761
762//------------------------------------------------------------------
763// Filename string const get accessor.
764//------------------------------------------------------------------
765const ConstString &
766FileSpec::GetFilename() const
767{
768 return m_filename;
769}
770
771//------------------------------------------------------------------
772// Extract the directory and path into a fixed buffer. This is
773// needed as the directory and path are stored in separate string
774// values.
775//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000776size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000777FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000779 if (!path)
780 return 0;
781
Zachary Turnerdf62f202014-08-07 17:33:07 +0000782 std::string result = GetPath(denormalize);
783
784 size_t result_length = std::min(path_max_len-1, result.length());
785 ::strncpy(path, result.c_str(), result_length + 1);
786 return result_length;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787}
788
Greg Claytona44c1e62013-04-29 16:36:27 +0000789std::string
Zachary Turnerdf62f202014-08-07 17:33:07 +0000790FileSpec::GetPath (bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000791{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000792 llvm::SmallString<64> result;
793 if (m_directory)
794 result.append(m_directory.GetCString());
795 if (m_filename)
796 llvm::sys::path::append(result, m_filename.GetCString());
797 if (denormalize && !result.empty())
Zachary Turner3f559742014-08-07 17:33:36 +0000798 DeNormalize(result, m_syntax);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000799
800 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000801}
802
Enrico Granataa9dbf432011-10-17 21:45:27 +0000803ConstString
804FileSpec::GetFileNameExtension () const
805{
Greg Clayton1f746072012-08-29 21:13:06 +0000806 if (m_filename)
807 {
808 const char *filename = m_filename.GetCString();
809 const char* dot_pos = strrchr(filename, '.');
810 if (dot_pos && dot_pos[1] != '\0')
811 return ConstString(dot_pos+1);
812 }
813 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000814}
815
816ConstString
817FileSpec::GetFileNameStrippingExtension () const
818{
819 const char *filename = m_filename.GetCString();
820 if (filename == NULL)
821 return ConstString();
822
Johnny Chenf5df5372011-10-18 19:28:30 +0000823 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000824 if (dot_pos == NULL)
825 return m_filename;
826
827 return ConstString(filename, dot_pos-filename);
828}
829
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830//------------------------------------------------------------------
831// Returns a shared pointer to a data buffer that contains all or
832// part of the contents of a file. The data is memory mapped and
833// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000834// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835// file, and "file_size" bytes will be mapped. If "file_size" is
836// greater than the number of bytes available in the file starting
837// at "file_offset", the number of bytes will be appropriately
838// truncated. The final number of bytes that get mapped can be
839// verified using the DataBuffer::GetByteSize() function.
840//------------------------------------------------------------------
841DataBufferSP
842FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
843{
844 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000845 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846 if (mmap_data.get())
847 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000848 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
849 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850 data_sp.reset(mmap_data.release());
851 }
852 return data_sp;
853}
854
Greg Clayton736888c2015-02-23 23:47:09 +0000855DataBufferSP
856FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
857{
858 if (FileSystem::IsLocal(*this))
859 return MemoryMapFileContents(file_offset, file_size);
860 else
861 return ReadFileContents(file_offset, file_size, NULL);
862}
863
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864
865//------------------------------------------------------------------
866// Return the size in bytes that this object takes in memory. This
867// returns the size in bytes of this object, not any shared string
868// values it may refer to.
869//------------------------------------------------------------------
870size_t
871FileSpec::MemorySize() const
872{
873 return m_filename.MemorySize() + m_directory.MemorySize();
874}
875
Greg Claytondda4f7b2010-06-30 23:03:03 +0000876
877size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000878FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879{
Greg Clayton4017fa32012-01-06 02:01:06 +0000880 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000881 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882 char resolved_path[PATH_MAX];
883 if (GetPath(resolved_path, sizeof(resolved_path)))
884 {
Greg Clayton96c09682012-01-04 22:56:43 +0000885 File file;
886 error = file.Open(resolved_path, File::eOpenOptionRead);
887 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888 {
Greg Clayton96c09682012-01-04 22:56:43 +0000889 off_t file_offset_after_seek = file_offset;
890 bytes_read = dst_len;
891 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000892 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000893 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000894 else
895 {
896 error.SetErrorString("invalid file specification");
897 }
898 if (error_ptr)
899 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000900 return bytes_read;
901}
902
903//------------------------------------------------------------------
904// Returns a shared pointer to a data buffer that contains all or
905// part of the contents of a file. The data copies into a heap based
906// buffer that lives in the DataBuffer shared pointer object returned.
907// The data that is cached will start "file_offset" bytes into the
908// file, and "file_size" bytes will be mapped. If "file_size" is
909// greater than the number of bytes available in the file starting
910// at "file_offset", the number of bytes will be appropriately
911// truncated. The final number of bytes that get mapped can be
912// verified using the DataBuffer::GetByteSize() function.
913//------------------------------------------------------------------
914DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000915FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000916{
Greg Clayton4017fa32012-01-06 02:01:06 +0000917 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000918 DataBufferSP data_sp;
919 char resolved_path[PATH_MAX];
920 if (GetPath(resolved_path, sizeof(resolved_path)))
921 {
Greg Clayton96c09682012-01-04 22:56:43 +0000922 File file;
923 error = file.Open(resolved_path, File::eOpenOptionRead);
924 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000925 {
926 const bool null_terminate = false;
927 error = file.Read (file_size, file_offset, null_terminate, data_sp);
928 }
929 }
930 else
931 {
932 error.SetErrorString("invalid file specification");
933 }
934 if (error_ptr)
935 *error_ptr = error;
936 return data_sp;
937}
938
939DataBufferSP
940FileSpec::ReadFileContentsAsCString(Error *error_ptr)
941{
942 Error error;
943 DataBufferSP data_sp;
944 char resolved_path[PATH_MAX];
945 if (GetPath(resolved_path, sizeof(resolved_path)))
946 {
947 File file;
948 error = file.Open(resolved_path, File::eOpenOptionRead);
949 if (error.Success())
950 {
951 off_t offset = 0;
952 size_t length = SIZE_MAX;
953 const bool null_terminate = true;
954 error = file.Read (length, offset, null_terminate, data_sp);
955 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000957 else
958 {
959 error.SetErrorString("invalid file specification");
960 }
961 if (error_ptr)
962 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 return data_sp;
964}
965
Greg Clayton58fc50e2010-10-20 22:52:05 +0000966size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967FileSpec::ReadFileLines (STLStringArray &lines)
968{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000970 char path[PATH_MAX];
971 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000972 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000973 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974
Greg Clayton58fc50e2010-10-20 22:52:05 +0000975 if (file_stream)
976 {
977 std::string line;
978 while (getline (file_stream, line))
979 lines.push_back (line);
980 }
981 }
982 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983}
Greg Clayton4272cc72011-02-02 02:24:04 +0000984
985FileSpec::EnumerateDirectoryResult
986FileSpec::EnumerateDirectory
987(
988 const char *dir_path,
989 bool find_directories,
990 bool find_files,
991 bool find_other,
992 EnumerateDirectoryCallbackType callback,
993 void *callback_baton
994)
995{
996 if (dir_path && dir_path[0])
997 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000998#if _WIN32
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +0000999 std::string szDir(dir_path);
1000 szDir += "\\*";
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001001
1002 WIN32_FIND_DATA ffd;
Hafiz Abid Qadeer487767c2014-03-12 10:53:50 +00001003 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001004
1005 if (hFind == INVALID_HANDLE_VALUE)
1006 {
1007 return eEnumerateDirectoryResultNext;
1008 }
1009
1010 do
1011 {
1012 bool call_callback = false;
1013 FileSpec::FileType file_type = eFileTypeUnknown;
1014 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1015 {
1016 size_t len = strlen(ffd.cFileName);
1017
1018 if (len == 1 && ffd.cFileName[0] == '.')
1019 continue;
1020
1021 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1022 continue;
1023
1024 file_type = eFileTypeDirectory;
1025 call_callback = find_directories;
1026 }
1027 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1028 {
1029 file_type = eFileTypeOther;
1030 call_callback = find_other;
1031 }
1032 else
1033 {
1034 file_type = eFileTypeRegular;
1035 call_callback = find_files;
1036 }
1037 if (call_callback)
1038 {
1039 char child_path[MAX_PATH];
1040 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1041 if (child_path_len < (int)(sizeof(child_path) - 1))
1042 {
1043 // Don't resolve the file type or path
1044 FileSpec child_path_spec (child_path, false);
1045
1046 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1047
1048 switch (result)
1049 {
1050 case eEnumerateDirectoryResultNext:
1051 // Enumerate next entry in the current directory. We just
1052 // exit this switch and will continue enumerating the
1053 // current directory as we currently are...
1054 break;
1055
1056 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1057 if (FileSpec::EnumerateDirectory(child_path,
1058 find_directories,
1059 find_files,
1060 find_other,
1061 callback,
1062 callback_baton) == eEnumerateDirectoryResultQuit)
1063 {
1064 // The subdirectory returned Quit, which means to
1065 // stop all directory enumerations at all levels.
1066 return eEnumerateDirectoryResultQuit;
1067 }
1068 break;
1069
1070 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1071 // Exit from this directory level and tell parent to
1072 // keep enumerating.
1073 return eEnumerateDirectoryResultNext;
1074
1075 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1076 return eEnumerateDirectoryResultQuit;
1077 }
1078 }
1079 }
1080 } while (FindNextFile(hFind, &ffd) != 0);
1081
1082 FindClose(hFind);
1083#else
1084 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001085 if (dir_path_dir.is_valid())
1086 {
Jim Ingham1adba8b2014-09-12 23:39:38 +00001087 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1088
Jason Molenda14aef122013-04-04 03:19:27 +00001089 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1090#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1091 if (path_max < __DARWIN_MAXPATHLEN)
1092 path_max = __DARWIN_MAXPATHLEN;
1093#endif
1094 struct dirent *buf, *dp;
1095 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1096
1097 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001098 {
1099 // Only search directories
1100 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1101 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001102 size_t len = strlen(dp->d_name);
1103
1104 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001105 continue;
1106
Greg Claytone0f3c022011-02-07 17:41:11 +00001107 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001108 continue;
1109 }
1110
1111 bool call_callback = false;
1112 FileSpec::FileType file_type = eFileTypeUnknown;
1113
1114 switch (dp->d_type)
1115 {
1116 default:
1117 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1118 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1119 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1120 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1121 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1122 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1123 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1124 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001125#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001126 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001127#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001128 }
1129
1130 if (call_callback)
1131 {
1132 char child_path[PATH_MAX];
Jim Ingham1adba8b2014-09-12 23:39:38 +00001133
1134 // Don't make paths with "/foo//bar", that just confuses everybody.
1135 int child_path_len;
1136 if (dir_path_last_char == '/')
1137 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1138 else
1139 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1140
Johnny Chen44805302011-07-19 19:48:13 +00001141 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001142 {
1143 // Don't resolve the file type or path
1144 FileSpec child_path_spec (child_path, false);
1145
1146 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1147
1148 switch (result)
1149 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001150 case eEnumerateDirectoryResultNext:
1151 // Enumerate next entry in the current directory. We just
1152 // exit this switch and will continue enumerating the
1153 // current directory as we currently are...
1154 break;
1155
1156 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1157 if (FileSpec::EnumerateDirectory (child_path,
1158 find_directories,
1159 find_files,
1160 find_other,
1161 callback,
1162 callback_baton) == eEnumerateDirectoryResultQuit)
1163 {
1164 // The subdirectory returned Quit, which means to
1165 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001166 if (buf)
1167 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001168 return eEnumerateDirectoryResultQuit;
1169 }
1170 break;
1171
1172 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1173 // Exit from this directory level and tell parent to
1174 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001175 if (buf)
1176 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001177 return eEnumerateDirectoryResultNext;
1178
1179 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001180 if (buf)
1181 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001182 return eEnumerateDirectoryResultQuit;
1183 }
1184 }
1185 }
1186 }
Jason Molenda14aef122013-04-04 03:19:27 +00001187 if (buf)
1188 {
1189 free (buf);
1190 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001191 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001192#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001193 }
1194 // By default when exiting a directory, we tell the parent enumeration
1195 // to continue enumerating.
1196 return eEnumerateDirectoryResultNext;
1197}
1198
Daniel Maleae0f8f572013-08-26 23:57:52 +00001199FileSpec
1200FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1201{
1202 const bool resolve = false;
1203 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1204 return FileSpec(new_path,resolve);
1205 StreamString stream;
1206 if (m_filename.IsEmpty())
1207 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1208 else if (m_directory.IsEmpty())
1209 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1210 else
1211 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1212 return FileSpec(stream.GetData(),resolve);
1213}
1214
1215FileSpec
1216FileSpec::CopyByRemovingLastPathComponent () const
1217{
1218 const bool resolve = false;
1219 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1220 return FileSpec("",resolve);
1221 if (m_directory.IsEmpty())
1222 return FileSpec("",resolve);
1223 if (m_filename.IsEmpty())
1224 {
1225 const char* dir_cstr = m_directory.GetCString();
1226 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1227
1228 // check for obvious cases before doing the full thing
1229 if (!last_slash_ptr)
1230 return FileSpec("",resolve);
1231 if (last_slash_ptr == dir_cstr)
1232 return FileSpec("/",resolve);
1233
1234 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1235 ConstString new_path(dir_cstr,last_slash_pos);
1236 return FileSpec(new_path.GetCString(),resolve);
1237 }
1238 else
1239 return FileSpec(m_directory.GetCString(),resolve);
1240}
1241
Greg Claytonfbb76342013-11-20 21:07:01 +00001242ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001243FileSpec::GetLastPathComponent () const
1244{
Greg Claytonfbb76342013-11-20 21:07:01 +00001245 if (m_filename)
1246 return m_filename;
1247 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001248 {
1249 const char* dir_cstr = m_directory.GetCString();
1250 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1251 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001252 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001253 if (last_slash_ptr == dir_cstr)
1254 {
1255 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001256 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001257 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001258 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001259 }
1260 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001261 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001262 const char* penultimate_slash_ptr = last_slash_ptr;
1263 while (*penultimate_slash_ptr)
1264 {
1265 --penultimate_slash_ptr;
1266 if (penultimate_slash_ptr == dir_cstr)
1267 break;
1268 if (*penultimate_slash_ptr == '/')
1269 break;
1270 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001271 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1272 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001273 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001274 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001275}
1276
1277void
1278FileSpec::AppendPathComponent (const char *new_path)
1279{
1280 const bool resolve = false;
1281 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1282 {
1283 SetFile(new_path,resolve);
1284 return;
1285 }
1286 StreamString stream;
1287 if (m_filename.IsEmpty())
1288 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1289 else if (m_directory.IsEmpty())
1290 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1291 else
1292 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1293 SetFile(stream.GetData(), resolve);
1294}
1295
1296void
1297FileSpec::RemoveLastPathComponent ()
1298{
1299 const bool resolve = false;
1300 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1301 {
1302 SetFile("",resolve);
1303 return;
1304 }
1305 if (m_directory.IsEmpty())
1306 {
1307 SetFile("",resolve);
1308 return;
1309 }
1310 if (m_filename.IsEmpty())
1311 {
1312 const char* dir_cstr = m_directory.GetCString();
1313 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1314
1315 // check for obvious cases before doing the full thing
1316 if (!last_slash_ptr)
1317 {
1318 SetFile("",resolve);
1319 return;
1320 }
1321 if (last_slash_ptr == dir_cstr)
1322 {
1323 SetFile("/",resolve);
1324 return;
1325 }
1326 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1327 ConstString new_path(dir_cstr,last_slash_pos);
1328 SetFile(new_path.GetCString(),resolve);
1329 }
1330 else
1331 SetFile(m_directory.GetCString(),resolve);
1332}
Greg Clayton1f746072012-08-29 21:13:06 +00001333//------------------------------------------------------------------
1334/// Returns true if the filespec represents an implementation source
1335/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1336/// extension).
1337///
1338/// @return
1339/// \b true if the filespec represents an implementation source
1340/// file, \b false otherwise.
1341//------------------------------------------------------------------
1342bool
1343FileSpec::IsSourceImplementationFile () const
1344{
1345 ConstString extension (GetFileNameExtension());
1346 if (extension)
1347 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001348 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 +00001349 return g_source_file_regex.Execute (extension.GetCString());
1350 }
1351 return false;
1352}
1353
Greg Claytona0ca6602012-10-18 16:33:33 +00001354bool
1355FileSpec::IsRelativeToCurrentWorkingDirectory () const
1356{
Zachary Turner270e99a2014-12-08 21:36:42 +00001357 const char *dir = m_directory.GetCString();
1358 llvm::StringRef directory(dir ? dir : "");
1359
1360 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001361 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001362 if (m_syntax == ePathSyntaxWindows)
Greg Claytona0ca6602012-10-18 16:33:33 +00001363 {
Zachary Turner270e99a2014-12-08 21:36:42 +00001364 if (directory.size() >= 2 && directory[1] == ':')
1365 return false;
1366 if (directory[0] == '/')
1367 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001368 return true;
1369 }
Zachary Turner270e99a2014-12-08 21:36:42 +00001370 else
1371 {
1372 // If the path doesn't start with '/' or '~', return true
1373 switch (directory[0])
1374 {
1375 case '/':
1376 case '~':
1377 return false;
1378 default:
1379 return true;
1380 }
1381 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001382 }
1383 else if (m_filename)
1384 {
1385 // No directory, just a basename, return true
1386 return true;
1387 }
1388 return false;
1389}