blob: d17b907f7128315344ddd9b481699f656cf85c81 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- FileSpec.cpp --------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#ifndef _WIN32
Greg Clayton4272cc72011-02-02 02:24:04 +000012#include <dirent.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000013#else
14#include "lldb/Host/windows/windows.h"
15#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include <fcntl.h>
Virgile Bello69571952013-09-20 22:35:22 +000017#ifndef _MSC_VER
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include <libgen.h>
Virgile Bello69571952013-09-20 22:35:22 +000019#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Rafael Espindola09079162013-06-13 20:10:23 +000021#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000022#include <string.h>
Jim Ingham9035e7c2011-02-07 19:42:39 +000023#include <fstream>
Greg Claytonfd184262011-02-05 02:27:52 +000024
Jim Ingham9035e7c2011-02-07 19:42:39 +000025#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000026#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000027#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000028#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029
Chaoren Linf34f4102015-05-09 01:21:32 +000030#include "lldb/Core/ArchSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000031#include "lldb/Core/DataBufferHeap.h"
32#include "lldb/Core/DataBufferMemoryMap.h"
33#include "lldb/Core/RegularExpression.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Stream.h"
36#include "lldb/Host/File.h"
37#include "lldb/Host/FileSpec.h"
38#include "lldb/Host/FileSystem.h"
39#include "lldb/Host/Host.h"
40#include "lldb/Utility/CleanUp.h"
41
Caroline Tice391a9602010-09-12 00:10:52 +000042#include "llvm/ADT/StringRef.h"
Zachary Turner3f559742014-08-07 17:33:36 +000043#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000046
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047using namespace lldb;
48using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049
Chaoren Lin1c614fe2015-05-28 17:02:45 +000050namespace {
51
52bool
53PathSyntaxIsPosix(FileSpec::PathSyntax syntax)
54{
55 return (syntax == FileSpec::ePathSyntaxPosix ||
56 (syntax == FileSpec::ePathSyntaxHostNative &&
57 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
58}
59
60char
61GetPathSeparator(FileSpec::PathSyntax syntax)
62{
63 return PathSyntaxIsPosix(syntax) ? '/' : '\\';
64}
65
66void
67Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
68{
69 if (PathSyntaxIsPosix(syntax)) return;
70
71 std::replace(path.begin(), path.end(), '\\', '/');
72 // Windows path can have \\ slashes which can be changed by replace
73 // call above to //. Here we remove the duplicate.
74 auto iter = std::unique ( path.begin(), path.end(),
75 []( char &c1, char &c2 ){
76 return (c1 == '/' && c2 == '/');});
77 path.erase(iter, path.end());
78}
79
80void
81Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
82{
83 if (PathSyntaxIsPosix(syntax)) return;
84
85 std::replace(path.begin(), path.end(), '/', '\\');
86}
87
88bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
90{
91 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000092 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093 return ::stat (resolved_path, stats_ptr) == 0;
94 return false;
95}
96
Chaoren Lin1c614fe2015-05-28 17:02:45 +000097}
98
Jim Inghamf818ca32010-07-01 01:48:53 +000099// Resolves the username part of a path of the form ~user/other/directories, and
Jim Inghamead45cc2014-09-12 23:50:36 +0000100// writes the result into dst_path. This will also resolve "~" to the current user.
101// If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
Zachary Turner3f559742014-08-07 17:33:36 +0000102void
103FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
Jim Inghamf818ca32010-07-01 01:48:53 +0000104{
Zachary Turner3f559742014-08-07 17:33:36 +0000105#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
106 if (path.empty() || path[0] != '~')
107 return;
Jim Inghamf818ca32010-07-01 01:48:53 +0000108
Jason Molenda3bc66f12015-01-20 04:20:42 +0000109 llvm::StringRef path_str(path.data(), path.size());
Bruce Mitchenere8433cc2015-09-01 23:57:17 +0000110 size_t slash_pos = path_str.find('/', 1);
Jim Inghamead45cc2014-09-12 23:50:36 +0000111 if (slash_pos == 1 || path.size() == 1)
Jim Inghamf818ca32010-07-01 01:48:53 +0000112 {
Jim Ingham2f21bbc2014-09-12 23:04:40 +0000113 // A path of ~/ resolves to the current user's home dir
Zachary Turner3f559742014-08-07 17:33:36 +0000114 llvm::SmallString<64> home_dir;
115 if (!llvm::sys::path::home_directory(home_dir))
116 return;
117
118 // Overwrite the ~ with the first character of the homedir, and insert
119 // the rest. This way we only trigger one move, whereas an insert
120 // followed by a delete (or vice versa) would trigger two.
121 path[0] = home_dir[0];
122 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
123 return;
124 }
125
126 auto username_begin = path.begin()+1;
127 auto username_end = (slash_pos == llvm::StringRef::npos)
128 ? path.end()
129 : (path.begin() + slash_pos);
130 size_t replacement_length = std::distance(path.begin(), username_end);
131
132 llvm::SmallString<20> username(username_begin, username_end);
133 struct passwd *user_entry = ::getpwnam(username.c_str());
134 if (user_entry != nullptr)
135 {
136 // Copy over the first n characters of the path, where n is the smaller of the length
137 // of the home directory and the slash pos.
138 llvm::StringRef homedir(user_entry->pw_dir);
139 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
140 auto src_begin = homedir.begin();
141 auto src_end = src_begin + initial_copy_length;
142 std::copy(src_begin, src_end, path.begin());
143 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000144 {
Zachary Turner3f559742014-08-07 17:33:36 +0000145 // We copied the entire home directory, but the ~username portion of the path was
146 // longer, so there's characters that need to be removed.
147 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000148 }
Zachary Turner3f559742014-08-07 17:33:36 +0000149 else if (replacement_length < homedir.size())
150 {
151 // We copied all the way up to the slash in the destination, but there's still more
152 // characters that need to be inserted.
153 path.insert(username_end, src_end, homedir.end());
154 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000155 }
156 else
157 {
Zachary Turner3f559742014-08-07 17:33:36 +0000158 // Unable to resolve username (user doesn't exist?)
159 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000160 }
Zachary Turner3f559742014-08-07 17:33:36 +0000161#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000162}
163
Greg Claytonc982c762010-07-09 20:39:50 +0000164size_t
Jim Ingham84363072011-02-08 23:24:09 +0000165FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
166{
167#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
168 size_t extant_entries = matches.GetSize();
169
170 setpwent();
171 struct passwd *user_entry;
172 const char *name_start = partial_name + 1;
173 std::set<std::string> name_list;
174
175 while ((user_entry = getpwent()) != NULL)
176 {
177 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
178 {
179 std::string tmp_buf("~");
180 tmp_buf.append(user_entry->pw_name);
181 tmp_buf.push_back('/');
182 name_list.insert(tmp_buf);
183 }
184 }
185 std::set<std::string>::iterator pos, end = name_list.end();
186 for (pos = name_list.begin(); pos != end; pos++)
187 {
188 matches.AppendString((*pos).c_str());
189 }
190 return matches.GetSize() - extant_entries;
191#else
192 // Resolving home directories is not supported, just copy the path...
193 return 0;
194#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
195}
196
Zachary Turner3f559742014-08-07 17:33:36 +0000197void
198FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199{
Zachary Turner3f559742014-08-07 17:33:36 +0000200 if (path.empty())
201 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202
Greg Clayton45319462011-02-08 00:35:34 +0000203#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000204 if (path[0] == '~')
205 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000206#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207
Jason Molenda671a29d2015-02-25 02:35:25 +0000208 // Save a copy of the original path that's passed in
209 llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end());
210
Zachary Turner3f559742014-08-07 17:33:36 +0000211 llvm::sys::fs::make_absolute(path);
Jason Molenda671a29d2015-02-25 02:35:25 +0000212
213
214 path.push_back(0); // Be sure we have a nul terminated string
215 path.pop_back();
216 struct stat file_stats;
217 if (::stat (path.data(), &file_stats) != 0)
218 {
219 path.clear();
220 path.append(original_path.begin(), original_path.end());
221 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000222}
223
Jason Molenda68c85212014-10-15 03:04:33 +0000224FileSpec::FileSpec() :
225 m_directory(),
226 m_filename(),
227 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228{
229}
230
231//------------------------------------------------------------------
232// Default constructor that can take an optional full path to a
233// file on disk.
234//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000235FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000236 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000237 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000238 m_is_resolved(false),
239 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000240{
241 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000242 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000243}
244
Chaoren Linf34f4102015-05-09 01:21:32 +0000245FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
Chaoren Lind3173f32015-05-29 19:52:29 +0000246 FileSpec{pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix}
247{
248}
249
250FileSpec::FileSpec(const std::string &path, bool resolve_path, PathSyntax syntax) :
251 FileSpec{path.c_str(), resolve_path, syntax}
252{
253}
254
255FileSpec::FileSpec(const std::string &path, bool resolve_path, ArchSpec arch) :
256 FileSpec{path.c_str(), resolve_path, arch}
Chaoren Linf34f4102015-05-09 01:21:32 +0000257{
258}
259
Jim Ingham0909e5f2010-09-16 00:57:33 +0000260//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261// Copy constructor
262//------------------------------------------------------------------
263FileSpec::FileSpec(const FileSpec& rhs) :
264 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000265 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000266 m_is_resolved (rhs.m_is_resolved),
267 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268{
269}
270
271//------------------------------------------------------------------
272// Copy constructor
273//------------------------------------------------------------------
274FileSpec::FileSpec(const FileSpec* rhs) :
275 m_directory(),
276 m_filename()
277{
278 if (rhs)
279 *this = *rhs;
280}
281
282//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000283// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284//------------------------------------------------------------------
285FileSpec::~FileSpec()
286{
287}
288
289//------------------------------------------------------------------
290// Assignment operator.
291//------------------------------------------------------------------
292const FileSpec&
293FileSpec::operator= (const FileSpec& rhs)
294{
295 if (this != &rhs)
296 {
297 m_directory = rhs.m_directory;
298 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000299 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000300 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000301 }
302 return *this;
303}
304
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000305//------------------------------------------------------------------
306// Update the contents of this object with a new path. The path will
307// be split up into a directory and filename and stored as uniqued
308// string values for quick comparison and efficient memory usage.
309//------------------------------------------------------------------
310void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000311FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312{
313 m_filename.Clear();
314 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000315 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000316 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000317
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 if (pathname == NULL || pathname[0] == '\0')
319 return;
320
Zachary Turner3f559742014-08-07 17:33:36 +0000321 llvm::SmallString<64> normalized(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000322
Jim Ingham0909e5f2010-09-16 00:57:33 +0000323 if (resolve)
324 {
Zachary Turner3f559742014-08-07 17:33:36 +0000325 FileSpec::Resolve (normalized);
326 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000327 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000328
329 // Only normalize after resolving the path. Resolution will modify the path
330 // string, potentially adding wrong kinds of slashes to the path, that need
331 // to be re-normalized.
332 Normalize(normalized, syntax);
333
Zachary Turner3f559742014-08-07 17:33:36 +0000334 llvm::StringRef resolve_path_ref(normalized.c_str());
335 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
336 if (!filename_ref.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337 {
Zachary Turner3f559742014-08-07 17:33:36 +0000338 m_filename.SetString (filename_ref);
339 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
340 if (!directory_ref.empty())
341 m_directory.SetString(directory_ref);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000342 }
Zachary Turner3f559742014-08-07 17:33:36 +0000343 else
344 m_directory.SetCString(normalized.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000345}
346
Chaoren Lind3173f32015-05-29 19:52:29 +0000347void
Chaoren Lin44145d72015-05-29 19:52:37 +0000348FileSpec::SetFile(const char *pathname, bool resolve, ArchSpec arch)
349{
350 return SetFile(pathname, resolve,
351 arch.GetTriple().isOSWindows()
352 ? ePathSyntaxWindows
353 : ePathSyntaxPosix);
354}
355
356void
Chaoren Lind3173f32015-05-29 19:52:29 +0000357FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
358{
359 return SetFile(pathname.c_str(), resolve, syntax);
360}
361
Chaoren Lin44145d72015-05-29 19:52:37 +0000362void
363FileSpec::SetFile(const std::string &pathname, bool resolve, ArchSpec arch)
364{
365 return SetFile(pathname.c_str(), resolve, arch);
366}
367
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368//----------------------------------------------------------------------
369// Convert to pointer operator. This allows code to check any FileSpec
370// objects to see if they contain anything valid using code such as:
371//
372// if (file_spec)
373// {}
374//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000375FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000377 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378}
379
380//----------------------------------------------------------------------
381// Logical NOT operator. This allows code to check any FileSpec
382// objects to see if they are invalid using code such as:
383//
384// if (!file_spec)
385// {}
386//----------------------------------------------------------------------
387bool
388FileSpec::operator!() const
389{
390 return !m_directory && !m_filename;
391}
392
Zachary Turner74e08ca2016-03-02 22:05:52 +0000393bool
394FileSpec::DirectoryEquals(const FileSpec &rhs) const
395{
396 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
397 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
398}
399
400bool
401FileSpec::FileEquals(const FileSpec &rhs) const
402{
403 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
404 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
405}
406
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407//------------------------------------------------------------------
408// Equal to operator
409//------------------------------------------------------------------
410bool
411FileSpec::operator== (const FileSpec& rhs) const
412{
Zachary Turner74e08ca2016-03-02 22:05:52 +0000413 if (!FileEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000414 return false;
Zachary Turner74e08ca2016-03-02 22:05:52 +0000415 if (DirectoryEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000416 return true;
417
418 // TODO: determine if we want to keep this code in here.
419 // The code below was added to handle a case where we were
420 // trying to set a file and line breakpoint and one path
421 // was resolved, and the other not and the directory was
422 // in a mount point that resolved to a more complete path:
423 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
424 // this out...
425 if (IsResolved() && rhs.IsResolved())
Greg Clayton7481c202010-11-08 00:28:40 +0000426 {
Zachary Turner47c03462016-02-24 21:26:47 +0000427 // Both paths are resolved, no need to look further...
428 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000429 }
Zachary Turner47c03462016-02-24 21:26:47 +0000430
431 FileSpec resolved_lhs(*this);
432
433 // If "this" isn't resolved, resolve it
434 if (!IsResolved())
435 {
436 if (resolved_lhs.ResolvePath())
437 {
438 // This path wasn't resolved but now it is. Check if the resolved
439 // directory is the same as our unresolved directory, and if so,
440 // we can mark this object as resolved to avoid more future resolves
441 m_is_resolved = (m_directory == resolved_lhs.m_directory);
442 }
443 else
444 return false;
445 }
446
447 FileSpec resolved_rhs(rhs);
448 if (!rhs.IsResolved())
449 {
450 if (resolved_rhs.ResolvePath())
451 {
452 // rhs's path wasn't resolved but now it is. Check if the resolved
453 // directory is the same as rhs's unresolved directory, and if so,
454 // we can mark this object as resolved to avoid more future resolves
455 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
456 }
457 else
458 return false;
459 }
460
461 // If we reach this point in the code we were able to resolve both paths
462 // and since we only resolve the paths if the basenames are equal, then
463 // we can just check if both directories are equal...
Zachary Turner74e08ca2016-03-02 22:05:52 +0000464 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465}
466
467//------------------------------------------------------------------
468// Not equal to operator
469//------------------------------------------------------------------
470bool
471FileSpec::operator!= (const FileSpec& rhs) const
472{
Greg Clayton7481c202010-11-08 00:28:40 +0000473 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474}
475
476//------------------------------------------------------------------
477// Less than operator
478//------------------------------------------------------------------
479bool
480FileSpec::operator< (const FileSpec& rhs) const
481{
482 return FileSpec::Compare(*this, rhs, true) < 0;
483}
484
485//------------------------------------------------------------------
486// Dump a FileSpec object to a stream
487//------------------------------------------------------------------
488Stream&
489lldb_private::operator << (Stream &s, const FileSpec& f)
490{
491 f.Dump(&s);
492 return s;
493}
494
495//------------------------------------------------------------------
496// Clear this object by releasing both the directory and filename
497// string values and making them both the empty string.
498//------------------------------------------------------------------
499void
500FileSpec::Clear()
501{
502 m_directory.Clear();
503 m_filename.Clear();
504}
505
506//------------------------------------------------------------------
507// Compare two FileSpec objects. If "full" is true, then both
508// the directory and the filename must match. If "full" is false,
509// then the directory names for "a" and "b" are only compared if
510// they are both non-empty. This allows a FileSpec object to only
511// contain a filename and it can match FileSpec objects that have
512// matching filenames with different paths.
513//
514// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
515// and "1" if "a" is greater than "b".
516//------------------------------------------------------------------
517int
518FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
519{
520 int result = 0;
521
Zachary Turner47c03462016-02-24 21:26:47 +0000522 // case sensitivity of compare
523 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
524
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525 // If full is true, then we must compare both the directory and filename.
526
527 // If full is false, then if either directory is empty, then we match on
528 // the basename only, and if both directories have valid values, we still
529 // do a full compare. This allows for matching when we just have a filename
530 // in one of the FileSpec objects.
531
532 if (full || (a.m_directory && b.m_directory))
533 {
Zachary Turner47c03462016-02-24 21:26:47 +0000534 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000535 if (result)
536 return result;
537 }
Zachary Turner47c03462016-02-24 21:26:47 +0000538 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000539}
540
541bool
Jim Ingham96a15962014-11-15 01:54:26 +0000542FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543{
Zachary Turner47c03462016-02-24 21:26:47 +0000544 // case sensitivity of equality test
545 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
546
Jim Ingham87df91b2011-09-23 00:54:11 +0000547 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Zachary Turner47c03462016-02-24 21:26:47 +0000548 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000549 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000550 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000551 else
552 {
Zachary Turner47c03462016-02-24 21:26:47 +0000553 if (!ConstString::Equals(a.m_filename, b.m_filename, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000554 return false;
Zachary Turner47c03462016-02-24 21:26:47 +0000555 if (ConstString::Equals(a.m_directory, b.m_directory, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000556 return true;
557 ConstString a_without_dots;
558 ConstString b_without_dots;
559
560 RemoveBackupDots (a.m_directory, a_without_dots);
561 RemoveBackupDots (b.m_directory, b_without_dots);
Zachary Turner47c03462016-02-24 21:26:47 +0000562 return ConstString::Equals(a_without_dots, b_without_dots, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000563 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000564}
565
Jim Ingham96a15962014-11-15 01:54:26 +0000566void
Greg Clayton5a271952015-06-02 22:43:29 +0000567FileSpec::NormalizePath ()
568{
569 ConstString normalized_directory;
570 FileSpec::RemoveBackupDots(m_directory, normalized_directory);
571 m_directory = normalized_directory;
572}
573
574void
Jim Ingham96a15962014-11-15 01:54:26 +0000575FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
576{
577 const char *input = input_const_str.GetCString();
578 result_const_str.Clear();
579 if (!input || input[0] == '\0')
580 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000581
Jim Ingham96a15962014-11-15 01:54:26 +0000582 const char win_sep = '\\';
583 const char unix_sep = '/';
584 char found_sep;
585 const char *win_backup = "\\..";
586 const char *unix_backup = "/..";
587
588 bool is_win = false;
589
590 // Determine the platform for the path (win or unix):
591
592 if (input[0] == win_sep)
593 is_win = true;
594 else if (input[0] == unix_sep)
595 is_win = false;
596 else if (input[1] == ':')
597 is_win = true;
598 else if (strchr(input, unix_sep) != nullptr)
599 is_win = false;
600 else if (strchr(input, win_sep) != nullptr)
601 is_win = true;
602 else
603 {
604 // No separators at all, no reason to do any work here.
605 result_const_str = input_const_str;
606 return;
607 }
608
609 llvm::StringRef backup_sep;
610 if (is_win)
611 {
612 found_sep = win_sep;
613 backup_sep = win_backup;
614 }
615 else
616 {
617 found_sep = unix_sep;
618 backup_sep = unix_backup;
619 }
620
621 llvm::StringRef input_ref(input);
622 llvm::StringRef curpos(input);
623
624 bool had_dots = false;
625 std::string result;
626
627 while (1)
628 {
629 // Start of loop
630 llvm::StringRef before_sep;
631 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
632
633 before_sep = around_sep.first;
634 curpos = around_sep.second;
635
636 if (curpos.empty())
637 {
638 if (had_dots)
639 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000640 while (before_sep.startswith("//"))
641 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000642 if (!before_sep.empty())
643 {
644 result.append(before_sep.data(), before_sep.size());
645 }
646 }
647 break;
648 }
649 had_dots = true;
650
651 unsigned num_backups = 1;
652 while (curpos.startswith(backup_sep))
653 {
654 num_backups++;
655 curpos = curpos.slice(backup_sep.size(), curpos.size());
656 }
657
658 size_t end_pos = before_sep.size();
659 while (num_backups-- > 0)
660 {
661 end_pos = before_sep.rfind(found_sep, end_pos);
662 if (end_pos == llvm::StringRef::npos)
663 {
664 result_const_str = input_const_str;
665 return;
666 }
667 }
668 result.append(before_sep.data(), end_pos);
669 }
670
671 if (had_dots)
672 result_const_str.SetCString(result.c_str());
673 else
674 result_const_str = input_const_str;
675
676 return;
677}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678
679//------------------------------------------------------------------
680// Dump the object to the supplied stream. If the object contains
681// a valid directory name, it will be displayed followed by a
682// directory delimiter, and the filename.
683//------------------------------------------------------------------
684void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000685FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000687 if (s)
688 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000689 std::string path{GetPath(true)};
690 s->PutCString(path.c_str());
691 char path_separator = GetPathSeparator(m_syntax);
692 if (!m_filename && !path.empty() && path.back() != path_separator)
693 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000694 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000695}
696
697//------------------------------------------------------------------
698// Returns true if the file exists.
699//------------------------------------------------------------------
700bool
701FileSpec::Exists () const
702{
703 struct stat file_stats;
704 return GetFileStats (this, &file_stats);
705}
706
Caroline Tice428a9a52010-09-10 04:48:55 +0000707bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000708FileSpec::Readable () const
709{
710 const uint32_t permissions = GetPermissions();
711 if (permissions & eFilePermissionsEveryoneR)
712 return true;
713 return false;
714}
715
716bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000717FileSpec::ResolveExecutableLocation ()
718{
Greg Clayton274060b2010-10-20 20:54:39 +0000719 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000720 {
Greg Clayton58f41712011-01-25 21:32:01 +0000721 const char *file_cstr = m_filename.GetCString();
722 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000723 {
Greg Clayton58f41712011-01-25 21:32:01 +0000724 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000725 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
726 if (!error_or_path)
727 return false;
728 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000729 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000730 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000731 {
Greg Clayton58f41712011-01-25 21:32:01 +0000732 // FindProgramByName returns "." if it can't find the file.
733 if (strcmp (".", dir_ref.data()) == 0)
734 return false;
735
736 m_directory.SetCString (dir_ref.data());
737 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000738 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000739 else
740 {
741 // If FindProgramByName found the file, it returns the directory + filename in its return results.
742 // We need to separate them.
743 FileSpec tmp_file (dir_ref.data(), false);
744 if (tmp_file.Exists())
745 {
746 m_directory = tmp_file.m_directory;
747 return true;
748 }
Caroline Tice391a9602010-09-12 00:10:52 +0000749 }
750 }
751 }
752 }
753
754 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000755}
756
Jim Ingham0909e5f2010-09-16 00:57:33 +0000757bool
758FileSpec::ResolvePath ()
759{
Greg Clayton7481c202010-11-08 00:28:40 +0000760 if (m_is_resolved)
761 return true; // We have already resolved this path
762
763 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000764 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000765 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000766 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000767 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000768 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000769}
770
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771uint64_t
772FileSpec::GetByteSize() const
773{
774 struct stat file_stats;
775 if (GetFileStats (this, &file_stats))
776 return file_stats.st_size;
777 return 0;
778}
779
Zachary Turnerdf62f202014-08-07 17:33:07 +0000780FileSpec::PathSyntax
781FileSpec::GetPathSyntax() const
782{
783 return m_syntax;
784}
785
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786FileSpec::FileType
787FileSpec::GetFileType () const
788{
789 struct stat file_stats;
790 if (GetFileStats (this, &file_stats))
791 {
792 mode_t file_type = file_stats.st_mode & S_IFMT;
793 switch (file_type)
794 {
795 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000797#ifndef _WIN32
798 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 case S_IFSOCK: return eFileTypeSocket;
800 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000801#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000802 default:
803 break;
804 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000805 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806 }
807 return eFileTypeInvalid;
808}
809
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000810bool
811FileSpec::IsSymbolicLink () const
812{
813 char resolved_path[PATH_MAX];
814 if (!GetPath (resolved_path, sizeof (resolved_path)))
815 return false;
816
817#ifdef _WIN32
818 auto attrs = ::GetFileAttributes (resolved_path);
819 if (attrs == INVALID_FILE_ATTRIBUTES)
820 return false;
821
822 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
823#else
824 struct stat file_stats;
825 if (::lstat (resolved_path, &file_stats) != 0)
826 return false;
827
828 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
829#endif
830}
831
Greg Claytonfbb76342013-11-20 21:07:01 +0000832uint32_t
833FileSpec::GetPermissions () const
834{
835 uint32_t file_permissions = 0;
836 if (*this)
Chaoren Lind3173f32015-05-29 19:52:29 +0000837 FileSystem::GetFilePermissions(*this, file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000838 return file_permissions;
839}
840
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841TimeValue
842FileSpec::GetModificationTime () const
843{
844 TimeValue mod_time;
845 struct stat file_stats;
846 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000847 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848 return mod_time;
849}
850
851//------------------------------------------------------------------
852// Directory string get accessor.
853//------------------------------------------------------------------
854ConstString &
855FileSpec::GetDirectory()
856{
857 return m_directory;
858}
859
860//------------------------------------------------------------------
861// Directory string const get accessor.
862//------------------------------------------------------------------
863const ConstString &
864FileSpec::GetDirectory() const
865{
866 return m_directory;
867}
868
869//------------------------------------------------------------------
870// Filename string get accessor.
871//------------------------------------------------------------------
872ConstString &
873FileSpec::GetFilename()
874{
875 return m_filename;
876}
877
878//------------------------------------------------------------------
879// Filename string const get accessor.
880//------------------------------------------------------------------
881const ConstString &
882FileSpec::GetFilename() const
883{
884 return m_filename;
885}
886
887//------------------------------------------------------------------
888// Extract the directory and path into a fixed buffer. This is
889// needed as the directory and path are stored in separate string
890// values.
891//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000892size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000893FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000895 if (!path)
896 return 0;
897
Zachary Turnerdf62f202014-08-07 17:33:07 +0000898 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000899 ::snprintf(path, path_max_len, "%s", result.c_str());
900 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901}
902
Greg Claytona44c1e62013-04-29 16:36:27 +0000903std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000904FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000905{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000906 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000907 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000908 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000909}
910
Chaoren Lind3173f32015-05-29 19:52:29 +0000911const char *
912FileSpec::GetCString(bool denormalize) const
913{
914 return ConstString{GetPath(denormalize)}.AsCString(NULL);
915}
916
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000917void
918FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
919{
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000920 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
Pavel Labathcc0e87c2016-03-11 08:44:44 +0000921 if (m_directory && !(m_directory.GetLength() == 1 && m_directory.GetCString()[0] == '/'))
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000922 path.insert(path.end(), '/');
923 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000924 Normalize(path, m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000925 if (path.size() > 1 && path.back() == '/') path.pop_back();
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000926 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000927 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000928}
929
Enrico Granataa9dbf432011-10-17 21:45:27 +0000930ConstString
931FileSpec::GetFileNameExtension () const
932{
Greg Clayton1f746072012-08-29 21:13:06 +0000933 if (m_filename)
934 {
935 const char *filename = m_filename.GetCString();
936 const char* dot_pos = strrchr(filename, '.');
937 if (dot_pos && dot_pos[1] != '\0')
938 return ConstString(dot_pos+1);
939 }
940 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000941}
942
943ConstString
944FileSpec::GetFileNameStrippingExtension () const
945{
946 const char *filename = m_filename.GetCString();
947 if (filename == NULL)
948 return ConstString();
949
Johnny Chenf5df5372011-10-18 19:28:30 +0000950 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000951 if (dot_pos == NULL)
952 return m_filename;
953
954 return ConstString(filename, dot_pos-filename);
955}
956
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957//------------------------------------------------------------------
958// Returns a shared pointer to a data buffer that contains all or
959// part of the contents of a file. The data is memory mapped and
960// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000961// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962// file, and "file_size" bytes will be mapped. If "file_size" is
963// greater than the number of bytes available in the file starting
964// at "file_offset", the number of bytes will be appropriately
965// truncated. The final number of bytes that get mapped can be
966// verified using the DataBuffer::GetByteSize() function.
967//------------------------------------------------------------------
968DataBufferSP
969FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
970{
971 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000972 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973 if (mmap_data.get())
974 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000975 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
976 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 data_sp.reset(mmap_data.release());
978 }
979 return data_sp;
980}
981
Greg Clayton736888c2015-02-23 23:47:09 +0000982DataBufferSP
983FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
984{
985 if (FileSystem::IsLocal(*this))
986 return MemoryMapFileContents(file_offset, file_size);
987 else
988 return ReadFileContents(file_offset, file_size, NULL);
989}
990
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
992//------------------------------------------------------------------
993// Return the size in bytes that this object takes in memory. This
994// returns the size in bytes of this object, not any shared string
995// values it may refer to.
996//------------------------------------------------------------------
997size_t
998FileSpec::MemorySize() const
999{
1000 return m_filename.MemorySize() + m_directory.MemorySize();
1001}
1002
Greg Claytondda4f7b2010-06-30 23:03:03 +00001003
1004size_t
Greg Clayton4017fa32012-01-06 02:01:06 +00001005FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006{
Greg Clayton4017fa32012-01-06 02:01:06 +00001007 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001008 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 char resolved_path[PATH_MAX];
1010 if (GetPath(resolved_path, sizeof(resolved_path)))
1011 {
Greg Clayton96c09682012-01-04 22:56:43 +00001012 File file;
1013 error = file.Open(resolved_path, File::eOpenOptionRead);
1014 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 {
Greg Clayton96c09682012-01-04 22:56:43 +00001016 off_t file_offset_after_seek = file_offset;
1017 bytes_read = dst_len;
1018 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001019 }
Greg Claytondda4f7b2010-06-30 23:03:03 +00001020 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001021 else
1022 {
1023 error.SetErrorString("invalid file specification");
1024 }
1025 if (error_ptr)
1026 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001027 return bytes_read;
1028}
1029
1030//------------------------------------------------------------------
1031// Returns a shared pointer to a data buffer that contains all or
1032// part of the contents of a file. The data copies into a heap based
1033// buffer that lives in the DataBuffer shared pointer object returned.
1034// The data that is cached will start "file_offset" bytes into the
1035// file, and "file_size" bytes will be mapped. If "file_size" is
1036// greater than the number of bytes available in the file starting
1037// at "file_offset", the number of bytes will be appropriately
1038// truncated. The final number of bytes that get mapped can be
1039// verified using the DataBuffer::GetByteSize() function.
1040//------------------------------------------------------------------
1041DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +00001042FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +00001043{
Greg Clayton4017fa32012-01-06 02:01:06 +00001044 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001045 DataBufferSP data_sp;
1046 char resolved_path[PATH_MAX];
1047 if (GetPath(resolved_path, sizeof(resolved_path)))
1048 {
Greg Clayton96c09682012-01-04 22:56:43 +00001049 File file;
1050 error = file.Open(resolved_path, File::eOpenOptionRead);
1051 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +00001052 {
1053 const bool null_terminate = false;
1054 error = file.Read (file_size, file_offset, null_terminate, data_sp);
1055 }
1056 }
1057 else
1058 {
1059 error.SetErrorString("invalid file specification");
1060 }
1061 if (error_ptr)
1062 *error_ptr = error;
1063 return data_sp;
1064}
1065
1066DataBufferSP
1067FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1068{
1069 Error error;
1070 DataBufferSP data_sp;
1071 char resolved_path[PATH_MAX];
1072 if (GetPath(resolved_path, sizeof(resolved_path)))
1073 {
1074 File file;
1075 error = file.Open(resolved_path, File::eOpenOptionRead);
1076 if (error.Success())
1077 {
1078 off_t offset = 0;
1079 size_t length = SIZE_MAX;
1080 const bool null_terminate = true;
1081 error = file.Read (length, offset, null_terminate, data_sp);
1082 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001084 else
1085 {
1086 error.SetErrorString("invalid file specification");
1087 }
1088 if (error_ptr)
1089 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090 return data_sp;
1091}
1092
Greg Clayton58fc50e2010-10-20 22:52:05 +00001093size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094FileSpec::ReadFileLines (STLStringArray &lines)
1095{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001097 char path[PATH_MAX];
1098 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001100 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101
Greg Clayton58fc50e2010-10-20 22:52:05 +00001102 if (file_stream)
1103 {
1104 std::string line;
1105 while (getline (file_stream, line))
1106 lines.push_back (line);
1107 }
1108 }
1109 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110}
Greg Clayton4272cc72011-02-02 02:24:04 +00001111
1112FileSpec::EnumerateDirectoryResult
Greg Clayton58c65f02015-06-29 18:29:00 +00001113FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const &callback)
1114{
1115 if (dir_path && dir_path[0])
1116 {
1117#if _WIN32
1118 std::string szDir(dir_path);
1119 szDir += "\\*";
1120
1121 WIN32_FIND_DATA ffd;
1122 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
1123
1124 if (hFind == INVALID_HANDLE_VALUE)
1125 {
1126 return eEnumerateDirectoryResultNext;
1127 }
1128
1129 do
1130 {
Greg Clayton58c65f02015-06-29 18:29:00 +00001131 FileSpec::FileType file_type = eFileTypeUnknown;
1132 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1133 {
1134 size_t len = strlen(ffd.cFileName);
1135
1136 if (len == 1 && ffd.cFileName[0] == '.')
1137 continue;
1138
1139 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1140 continue;
1141
1142 file_type = eFileTypeDirectory;
Greg Clayton58c65f02015-06-29 18:29:00 +00001143 }
1144 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1145 {
1146 file_type = eFileTypeOther;
Greg Clayton58c65f02015-06-29 18:29:00 +00001147 }
1148 else
1149 {
1150 file_type = eFileTypeRegular;
Greg Clayton58c65f02015-06-29 18:29:00 +00001151 }
Ewan Crawford184d4df2015-06-30 15:03:31 +00001152
1153 char child_path[MAX_PATH];
1154 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1155 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton58c65f02015-06-29 18:29:00 +00001156 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001157 // Don't resolve the file type or path
1158 FileSpec child_path_spec (child_path, false);
1159
1160 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1161
1162 switch (result)
Greg Clayton58c65f02015-06-29 18:29:00 +00001163 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001164 case eEnumerateDirectoryResultNext:
1165 // Enumerate next entry in the current directory. We just
1166 // exit this switch and will continue enumerating the
1167 // current directory as we currently are...
1168 break;
Greg Clayton58c65f02015-06-29 18:29:00 +00001169
Ewan Crawford184d4df2015-06-30 15:03:31 +00001170 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1171 if (FileSpec::ForEachItemInDirectory(child_path, callback) == eEnumerateDirectoryResultQuit)
1172 {
1173 // The subdirectory returned Quit, which means to
1174 // stop all directory enumerations at all levels.
Greg Clayton58c65f02015-06-29 18:29:00 +00001175 return eEnumerateDirectoryResultQuit;
Ewan Crawford184d4df2015-06-30 15:03:31 +00001176 }
1177 break;
1178
1179 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1180 // Exit from this directory level and tell parent to
1181 // keep enumerating.
1182 return eEnumerateDirectoryResultNext;
1183
1184 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1185 return eEnumerateDirectoryResultQuit;
Greg Clayton58c65f02015-06-29 18:29:00 +00001186 }
1187 }
1188 } while (FindNextFile(hFind, &ffd) != 0);
1189
1190 FindClose(hFind);
1191#else
1192 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1193 if (dir_path_dir.is_valid())
1194 {
1195 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1196
1197 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1198#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1199 if (path_max < __DARWIN_MAXPATHLEN)
1200 path_max = __DARWIN_MAXPATHLEN;
1201#endif
1202 struct dirent *buf, *dp;
1203 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1204
1205 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1206 {
1207 // Only search directories
1208 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1209 {
1210 size_t len = strlen(dp->d_name);
1211
1212 if (len == 1 && dp->d_name[0] == '.')
1213 continue;
1214
1215 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1216 continue;
1217 }
1218
1219 FileSpec::FileType file_type = eFileTypeUnknown;
1220
1221 switch (dp->d_type)
1222 {
1223 default:
1224 case DT_UNKNOWN: file_type = eFileTypeUnknown; break;
1225 case DT_FIFO: file_type = eFileTypePipe; break;
1226 case DT_CHR: file_type = eFileTypeOther; break;
1227 case DT_DIR: file_type = eFileTypeDirectory; break;
1228 case DT_BLK: file_type = eFileTypeOther; break;
1229 case DT_REG: file_type = eFileTypeRegular; break;
1230 case DT_LNK: file_type = eFileTypeSymbolicLink; break;
1231 case DT_SOCK: file_type = eFileTypeSocket; break;
1232#if !defined(__OpenBSD__)
1233 case DT_WHT: file_type = eFileTypeOther; break;
1234#endif
1235 }
1236
1237 char child_path[PATH_MAX];
1238
1239 // Don't make paths with "/foo//bar", that just confuses everybody.
1240 int child_path_len;
1241 if (dir_path_last_char == '/')
1242 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1243 else
1244 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1245
1246 if (child_path_len < (int)(sizeof(child_path) - 1))
1247 {
1248 // Don't resolve the file type or path
1249 FileSpec child_path_spec (child_path, false);
1250
1251 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1252
1253 switch (result)
1254 {
1255 case eEnumerateDirectoryResultNext:
1256 // Enumerate next entry in the current directory. We just
1257 // exit this switch and will continue enumerating the
1258 // current directory as we currently are...
1259 break;
1260
1261 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1262 if (FileSpec::ForEachItemInDirectory (child_path, callback) == eEnumerateDirectoryResultQuit)
1263 {
1264 // The subdirectory returned Quit, which means to
1265 // stop all directory enumerations at all levels.
1266 if (buf)
1267 free (buf);
1268 return eEnumerateDirectoryResultQuit;
1269 }
1270 break;
1271
1272 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1273 // Exit from this directory level and tell parent to
1274 // keep enumerating.
1275 if (buf)
1276 free (buf);
1277 return eEnumerateDirectoryResultNext;
1278
1279 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1280 if (buf)
1281 free (buf);
1282 return eEnumerateDirectoryResultQuit;
1283 }
1284 }
1285 }
1286 if (buf)
1287 {
1288 free (buf);
1289 }
1290 }
1291#endif
1292 }
1293 // By default when exiting a directory, we tell the parent enumeration
1294 // to continue enumerating.
1295 return eEnumerateDirectoryResultNext;
1296}
1297
1298FileSpec::EnumerateDirectoryResult
Greg Clayton4272cc72011-02-02 02:24:04 +00001299FileSpec::EnumerateDirectory
1300(
1301 const char *dir_path,
1302 bool find_directories,
1303 bool find_files,
1304 bool find_other,
1305 EnumerateDirectoryCallbackType callback,
1306 void *callback_baton
1307)
1308{
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001309 return ForEachItemInDirectory(dir_path,
1310 [&find_directories, &find_files, &find_other, &callback, &callback_baton]
1311 (FileType file_type, const FileSpec &file_spec) {
1312 switch (file_type)
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001313 {
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001314 case FileType::eFileTypeDirectory:
1315 if (find_directories)
1316 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001317 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001318 case FileType::eFileTypeRegular:
1319 if (find_files)
1320 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001321 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001322 default:
1323 if (find_other)
1324 return callback(callback_baton, file_type, file_spec);
1325 break;
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001326 }
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001327 return eEnumerateDirectoryResultNext;
1328 });
Greg Clayton4272cc72011-02-02 02:24:04 +00001329}
1330
Daniel Maleae0f8f572013-08-26 23:57:52 +00001331FileSpec
1332FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1333{
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001334 FileSpec ret = *this;
1335 ret.AppendPathComponent(new_path);
1336 return ret;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001337}
1338
1339FileSpec
1340FileSpec::CopyByRemovingLastPathComponent () const
1341{
1342 const bool resolve = false;
1343 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1344 return FileSpec("",resolve);
1345 if (m_directory.IsEmpty())
1346 return FileSpec("",resolve);
1347 if (m_filename.IsEmpty())
1348 {
1349 const char* dir_cstr = m_directory.GetCString();
1350 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1351
1352 // check for obvious cases before doing the full thing
1353 if (!last_slash_ptr)
1354 return FileSpec("",resolve);
1355 if (last_slash_ptr == dir_cstr)
1356 return FileSpec("/",resolve);
1357
1358 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1359 ConstString new_path(dir_cstr,last_slash_pos);
1360 return FileSpec(new_path.GetCString(),resolve);
1361 }
1362 else
1363 return FileSpec(m_directory.GetCString(),resolve);
1364}
1365
Greg Claytonfbb76342013-11-20 21:07:01 +00001366ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001367FileSpec::GetLastPathComponent () const
1368{
Greg Claytonfbb76342013-11-20 21:07:01 +00001369 if (m_filename)
1370 return m_filename;
1371 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001372 {
1373 const char* dir_cstr = m_directory.GetCString();
1374 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1375 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001376 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001377 if (last_slash_ptr == dir_cstr)
1378 {
1379 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001380 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001381 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001382 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001383 }
1384 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001385 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001386 const char* penultimate_slash_ptr = last_slash_ptr;
1387 while (*penultimate_slash_ptr)
1388 {
1389 --penultimate_slash_ptr;
1390 if (penultimate_slash_ptr == dir_cstr)
1391 break;
1392 if (*penultimate_slash_ptr == '/')
1393 break;
1394 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001395 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1396 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001397 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001398 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001399}
1400
1401void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001402FileSpec::PrependPathComponent(const char *new_path)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001403{
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001404 if (!new_path) return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001405 const bool resolve = false;
1406 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1407 {
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001408 SetFile(new_path, resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001409 return;
1410 }
1411 StreamString stream;
1412 if (m_filename.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001413 stream.Printf("%s/%s", new_path, m_directory.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001414 else if (m_directory.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001415 stream.Printf("%s/%s", new_path, m_filename.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001416 else
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001417 stream.Printf("%s/%s/%s", new_path, m_directory.GetCString(), m_filename.GetCString());
1418 SetFile(stream.GetData(), resolve);
1419}
1420
1421void
1422FileSpec::PrependPathComponent(const std::string &new_path)
1423{
1424 return PrependPathComponent(new_path.c_str());
1425}
1426
1427void
1428FileSpec::PrependPathComponent(const FileSpec &new_path)
1429{
1430 return PrependPathComponent(new_path.GetPath(false));
1431}
1432
1433void
1434FileSpec::AppendPathComponent(const char *new_path)
1435{
1436 if (!new_path) return;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001437
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001438 StreamString stream;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001439 if (!m_directory.IsEmpty())
1440 {
1441 stream.PutCString(m_directory.GetCString());
1442 if (m_directory.GetLength() != 1 || m_directory.GetCString()[0] != '/')
1443 stream.PutChar('/');
1444 }
1445
1446 if (!m_filename.IsEmpty())
1447 {
1448 stream.PutCString(m_filename.GetCString());
1449 if (m_filename.GetLength() != 1 || m_filename.GetCString()[0] != '/')
1450 stream.PutChar('/');
1451 }
1452
1453 stream.PutCString(new_path);
1454
1455 const bool resolve = false;
1456 SetFile(stream.GetData(), resolve, m_syntax);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001457}
1458
1459void
Chaoren Lind3173f32015-05-29 19:52:29 +00001460FileSpec::AppendPathComponent(const std::string &new_path)
1461{
1462 return AppendPathComponent(new_path.c_str());
1463}
1464
1465void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001466FileSpec::AppendPathComponent(const FileSpec &new_path)
1467{
1468 return AppendPathComponent(new_path.GetPath(false));
1469}
1470
1471void
Daniel Maleae0f8f572013-08-26 23:57:52 +00001472FileSpec::RemoveLastPathComponent ()
1473{
1474 const bool resolve = false;
1475 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1476 {
1477 SetFile("",resolve);
1478 return;
1479 }
1480 if (m_directory.IsEmpty())
1481 {
1482 SetFile("",resolve);
1483 return;
1484 }
1485 if (m_filename.IsEmpty())
1486 {
1487 const char* dir_cstr = m_directory.GetCString();
1488 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1489
1490 // check for obvious cases before doing the full thing
1491 if (!last_slash_ptr)
1492 {
1493 SetFile("",resolve);
1494 return;
1495 }
1496 if (last_slash_ptr == dir_cstr)
1497 {
1498 SetFile("/",resolve);
1499 return;
1500 }
1501 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1502 ConstString new_path(dir_cstr,last_slash_pos);
1503 SetFile(new_path.GetCString(),resolve);
1504 }
1505 else
1506 SetFile(m_directory.GetCString(),resolve);
1507}
Greg Clayton1f746072012-08-29 21:13:06 +00001508//------------------------------------------------------------------
1509/// Returns true if the filespec represents an implementation source
1510/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1511/// extension).
1512///
1513/// @return
1514/// \b true if the filespec represents an implementation source
1515/// file, \b false otherwise.
1516//------------------------------------------------------------------
1517bool
1518FileSpec::IsSourceImplementationFile () const
1519{
1520 ConstString extension (GetFileNameExtension());
1521 if (extension)
1522 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001523 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 +00001524 return g_source_file_regex.Execute (extension.GetCString());
1525 }
1526 return false;
1527}
1528
Greg Claytona0ca6602012-10-18 16:33:33 +00001529bool
Chaoren Lin372e9062015-06-09 17:54:27 +00001530FileSpec::IsRelative() const
Greg Claytona0ca6602012-10-18 16:33:33 +00001531{
Zachary Turner270e99a2014-12-08 21:36:42 +00001532 const char *dir = m_directory.GetCString();
1533 llvm::StringRef directory(dir ? dir : "");
1534
1535 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001536 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001537 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001538 {
1539 // If the path doesn't start with '/' or '~', return true
1540 switch (directory[0])
1541 {
1542 case '/':
1543 case '~':
1544 return false;
1545 default:
1546 return true;
1547 }
1548 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001549 else
1550 {
1551 if (directory.size() >= 2 && directory[1] == ':')
1552 return false;
1553 if (directory[0] == '/')
1554 return false;
1555 return true;
1556 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001557 }
1558 else if (m_filename)
1559 {
1560 // No directory, just a basename, return true
1561 return true;
1562 }
1563 return false;
1564}
Chaoren Lin372e9062015-06-09 17:54:27 +00001565
1566bool
1567FileSpec::IsAbsolute() const
1568{
1569 return !FileSpec::IsRelative();
1570}