blob: ac5b07233c660e1b660ba1299176ab89f7ab7f2f [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
Greg Clayton4272cc72011-02-02 02:24:04 +000011#include <dirent.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <fcntl.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013#include <libgen.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014#include <sys/stat.h>
Greg Claytone0f3c022011-02-07 17:41:11 +000015#include <string.h>
Jim Ingham9035e7c2011-02-07 19:42:39 +000016#include <fstream>
Greg Claytonfd184262011-02-05 02:27:52 +000017
Jim Ingham9035e7c2011-02-07 19:42:39 +000018#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000019#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000020#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000021#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
Caroline Tice391a9602010-09-12 00:10:52 +000023#include "llvm/ADT/StringRef.h"
Greg Clayton38a61402010-12-02 23:20:03 +000024#include "llvm/Support/Path.h"
25#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000026
Greg Clayton96c09682012-01-04 22:56:43 +000027#include "lldb/Host/File.h"
Greg Clayton53239f02011-02-08 05:05:52 +000028#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Core/DataBufferHeap.h"
30#include "lldb/Core/DataBufferMemoryMap.h"
Greg Clayton1f746072012-08-29 21:13:06 +000031#include "lldb/Core/RegularExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/Stream.h"
Caroline Tice428a9a52010-09-10 04:48:55 +000033#include "lldb/Host/Host.h"
Greg Clayton4272cc72011-02-02 02:24:04 +000034#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035
36using namespace lldb;
37using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038
39static bool
40GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
41{
42 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000043 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044 return ::stat (resolved_path, stats_ptr) == 0;
45 return false;
46}
47
Greg Clayton45319462011-02-08 00:35:34 +000048#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +000049
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050static const char*
51GetCachedGlobTildeSlash()
52{
53 static std::string g_tilde;
54 if (g_tilde.empty())
55 {
Jim Inghamf818ca32010-07-01 01:48:53 +000056 struct passwd *user_entry;
57 user_entry = getpwuid(geteuid());
58 if (user_entry != NULL)
59 g_tilde = user_entry->pw_dir;
60
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061 if (g_tilde.empty())
62 return NULL;
63 }
64 return g_tilde.c_str();
65}
66
Greg Clayton87e5ff02011-02-08 05:19:06 +000067#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
68
Jim Inghamf818ca32010-07-01 01:48:53 +000069// Resolves the username part of a path of the form ~user/other/directories, and
70// writes the result into dst_path.
71// Returns 0 if there WAS a ~ in the path but the username couldn't be resolved.
72// Otherwise returns the number of characters copied into dst_path. If the return
73// is >= dst_len, then the resolved path is too long...
Greg Claytonc982c762010-07-09 20:39:50 +000074size_t
Jim Inghamf818ca32010-07-01 01:48:53 +000075FileSpec::ResolveUsername (const char *src_path, char *dst_path, size_t dst_len)
76{
Greg Clayton87e5ff02011-02-08 05:19:06 +000077 if (src_path == NULL || src_path[0] == '\0')
78 return 0;
79
80#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
81
Jim Inghamf818ca32010-07-01 01:48:53 +000082 char user_home[PATH_MAX];
83 const char *user_name;
84
Greg Claytona5d24f62010-07-01 17:07:48 +000085
Jim Inghamf818ca32010-07-01 01:48:53 +000086 // If there's no ~, then just copy src_path straight to dst_path (they may be the same string...)
87 if (src_path[0] != '~')
88 {
Greg Claytonc982c762010-07-09 20:39:50 +000089 size_t len = strlen (src_path);
Jim Inghamf818ca32010-07-01 01:48:53 +000090 if (len >= dst_len)
91 {
Greg Claytona5d24f62010-07-01 17:07:48 +000092 ::bcopy (src_path, dst_path, dst_len - 1);
93 dst_path[dst_len] = '\0';
Jim Inghamf818ca32010-07-01 01:48:53 +000094 }
95 else
Greg Claytona5d24f62010-07-01 17:07:48 +000096 ::bcopy (src_path, dst_path, len + 1);
97
Jim Inghamf818ca32010-07-01 01:48:53 +000098 return len;
99 }
100
Eli Friedmanfeaeebf2010-07-02 19:15:50 +0000101 const char *first_slash = ::strchr (src_path, '/');
Jim Inghamf818ca32010-07-01 01:48:53 +0000102 char remainder[PATH_MAX];
103
104 if (first_slash == NULL)
105 {
106 // The whole name is the username (minus the ~):
107 user_name = src_path + 1;
108 remainder[0] = '\0';
109 }
110 else
111 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000112 size_t user_name_len = first_slash - src_path - 1;
Greg Claytona5d24f62010-07-01 17:07:48 +0000113 ::memcpy (user_home, src_path + 1, user_name_len);
Jim Inghamf818ca32010-07-01 01:48:53 +0000114 user_home[user_name_len] = '\0';
115 user_name = user_home;
116
Greg Claytona5d24f62010-07-01 17:07:48 +0000117 ::strcpy (remainder, first_slash);
Jim Inghamf818ca32010-07-01 01:48:53 +0000118 }
Greg Claytona5d24f62010-07-01 17:07:48 +0000119
Jim Inghamf818ca32010-07-01 01:48:53 +0000120 if (user_name == NULL)
121 return 0;
122 // User name of "" means the current user...
123
124 struct passwd *user_entry;
Greg Claytonc982c762010-07-09 20:39:50 +0000125 const char *home_dir = NULL;
Jim Inghamf818ca32010-07-01 01:48:53 +0000126
127 if (user_name[0] == '\0')
128 {
129 home_dir = GetCachedGlobTildeSlash();
130 }
131 else
132 {
Greg Claytona5d24f62010-07-01 17:07:48 +0000133 user_entry = ::getpwnam (user_name);
Jim Inghamf818ca32010-07-01 01:48:53 +0000134 if (user_entry != NULL)
135 home_dir = user_entry->pw_dir;
136 }
137
138 if (home_dir == NULL)
139 return 0;
140 else
141 return ::snprintf (dst_path, dst_len, "%s%s", home_dir, remainder);
Greg Clayton87e5ff02011-02-08 05:19:06 +0000142#else
143 // Resolving home directories is not supported, just copy the path...
144 return ::snprintf (dst_path, dst_len, "%s", src_path);
145#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000146}
147
Greg Claytonc982c762010-07-09 20:39:50 +0000148size_t
Jim Ingham84363072011-02-08 23:24:09 +0000149FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
150{
151#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
152 size_t extant_entries = matches.GetSize();
153
154 setpwent();
155 struct passwd *user_entry;
156 const char *name_start = partial_name + 1;
157 std::set<std::string> name_list;
158
159 while ((user_entry = getpwent()) != NULL)
160 {
161 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
162 {
163 std::string tmp_buf("~");
164 tmp_buf.append(user_entry->pw_name);
165 tmp_buf.push_back('/');
166 name_list.insert(tmp_buf);
167 }
168 }
169 std::set<std::string>::iterator pos, end = name_list.end();
170 for (pos = name_list.begin(); pos != end; pos++)
171 {
172 matches.AppendString((*pos).c_str());
173 }
174 return matches.GetSize() - extant_entries;
175#else
176 // Resolving home directories is not supported, just copy the path...
177 return 0;
178#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
179}
180
181
182
183size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184FileSpec::Resolve (const char *src_path, char *dst_path, size_t dst_len)
185{
186 if (src_path == NULL || src_path[0] == '\0')
187 return 0;
188
189 // Glob if needed for ~/, otherwise copy in case src_path is same as dst_path...
190 char unglobbed_path[PATH_MAX];
Greg Clayton45319462011-02-08 00:35:34 +0000191#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000192 if (src_path[0] == '~')
193 {
Greg Claytonc982c762010-07-09 20:39:50 +0000194 size_t return_count = ResolveUsername(src_path, unglobbed_path, sizeof(unglobbed_path));
Jim Inghamf818ca32010-07-01 01:48:53 +0000195
196 // If we couldn't find the user referred to, or the resultant path was too long,
197 // then just copy over the src_path.
198 if (return_count == 0 || return_count >= sizeof(unglobbed_path))
199 ::snprintf (unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
200 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201 else
Greg Clayton45319462011-02-08 00:35:34 +0000202#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +0000203 {
204 ::snprintf(unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
205 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206
207 // Now resolve the path if needed
208 char resolved_path[PATH_MAX];
209 if (::realpath (unglobbed_path, resolved_path))
210 {
211 // Success, copy the resolved path
212 return ::snprintf(dst_path, dst_len, "%s", resolved_path);
213 }
214 else
215 {
216 // Failed, just copy the unglobbed path
217 return ::snprintf(dst_path, dst_len, "%s", unglobbed_path);
218 }
219}
220
221FileSpec::FileSpec() :
222 m_directory(),
223 m_filename()
224{
225}
226
227//------------------------------------------------------------------
228// Default constructor that can take an optional full path to a
229// file on disk.
230//------------------------------------------------------------------
Jim Ingham0909e5f2010-09-16 00:57:33 +0000231FileSpec::FileSpec(const char *pathname, bool resolve_path) :
232 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000233 m_filename(),
234 m_is_resolved(false)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000235{
236 if (pathname && pathname[0])
237 SetFile(pathname, resolve_path);
238}
239
240//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000241// Copy constructor
242//------------------------------------------------------------------
243FileSpec::FileSpec(const FileSpec& rhs) :
244 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000245 m_filename (rhs.m_filename),
246 m_is_resolved (rhs.m_is_resolved)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000247{
248}
249
250//------------------------------------------------------------------
251// Copy constructor
252//------------------------------------------------------------------
253FileSpec::FileSpec(const FileSpec* rhs) :
254 m_directory(),
255 m_filename()
256{
257 if (rhs)
258 *this = *rhs;
259}
260
261//------------------------------------------------------------------
262// Virtual destrcuctor in case anyone inherits from this class.
263//------------------------------------------------------------------
264FileSpec::~FileSpec()
265{
266}
267
268//------------------------------------------------------------------
269// Assignment operator.
270//------------------------------------------------------------------
271const FileSpec&
272FileSpec::operator= (const FileSpec& rhs)
273{
274 if (this != &rhs)
275 {
276 m_directory = rhs.m_directory;
277 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000278 m_is_resolved = rhs.m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000279 }
280 return *this;
281}
282
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000283//------------------------------------------------------------------
284// Update the contents of this object with a new path. The path will
285// be split up into a directory and filename and stored as uniqued
286// string values for quick comparison and efficient memory usage.
287//------------------------------------------------------------------
288void
Greg Clayton7481c202010-11-08 00:28:40 +0000289FileSpec::SetFile (const char *pathname, bool resolve)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000290{
291 m_filename.Clear();
292 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000293 m_is_resolved = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294 if (pathname == NULL || pathname[0] == '\0')
295 return;
296
297 char resolved_path[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000298 bool path_fit = true;
299
300 if (resolve)
301 {
302 path_fit = (FileSpec::Resolve (pathname, resolved_path, sizeof(resolved_path)) < sizeof(resolved_path) - 1);
Greg Clayton7481c202010-11-08 00:28:40 +0000303 m_is_resolved = path_fit;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000304 }
305 else
306 {
Greg Clayton7481c202010-11-08 00:28:40 +0000307 // Copy the path because "basename" and "dirname" want to muck with the
308 // path buffer
309 if (::strlen (pathname) > sizeof(resolved_path) - 1)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000310 path_fit = false;
311 else
Greg Clayton7481c202010-11-08 00:28:40 +0000312 ::strcpy (resolved_path, pathname);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000313 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314
Jim Ingham0909e5f2010-09-16 00:57:33 +0000315
316 if (path_fit)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000317 {
318 char *filename = ::basename (resolved_path);
319 if (filename)
320 {
321 m_filename.SetCString (filename);
322 // Truncate the basename off the end of the resolved path
323
324 // Only attempt to get the dirname if it looks like we have a path
325 if (strchr(resolved_path, '/'))
326 {
327 char *directory = ::dirname (resolved_path);
328
329 // Make sure we didn't get our directory resolved to "." without having
330 // specified
331 if (directory)
332 m_directory.SetCString(directory);
333 else
334 {
335 char *last_resolved_path_slash = strrchr(resolved_path, '/');
336 if (last_resolved_path_slash)
337 {
338 *last_resolved_path_slash = '\0';
339 m_directory.SetCString(resolved_path);
340 }
341 }
342 }
343 }
344 else
345 m_directory.SetCString(resolved_path);
346 }
347}
348
349//----------------------------------------------------------------------
350// Convert to pointer operator. This allows code to check any FileSpec
351// objects to see if they contain anything valid using code such as:
352//
353// if (file_spec)
354// {}
355//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000356FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000358 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000359}
360
361//----------------------------------------------------------------------
362// Logical NOT operator. This allows code to check any FileSpec
363// objects to see if they are invalid using code such as:
364//
365// if (!file_spec)
366// {}
367//----------------------------------------------------------------------
368bool
369FileSpec::operator!() const
370{
371 return !m_directory && !m_filename;
372}
373
374//------------------------------------------------------------------
375// Equal to operator
376//------------------------------------------------------------------
377bool
378FileSpec::operator== (const FileSpec& rhs) const
379{
Greg Clayton7481c202010-11-08 00:28:40 +0000380 if (m_filename == rhs.m_filename)
381 {
382 if (m_directory == rhs.m_directory)
383 return true;
384
385 // TODO: determine if we want to keep this code in here.
386 // The code below was added to handle a case where we were
387 // trying to set a file and line breakpoint and one path
388 // was resolved, and the other not and the directory was
389 // in a mount point that resolved to a more complete path:
390 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
391 // this out...
392 if (IsResolved() && rhs.IsResolved())
393 {
394 // Both paths are resolved, no need to look further...
395 return false;
396 }
397
398 FileSpec resolved_lhs(*this);
399
400 // If "this" isn't resolved, resolve it
401 if (!IsResolved())
402 {
403 if (resolved_lhs.ResolvePath())
404 {
405 // This path wasn't resolved but now it is. Check if the resolved
406 // directory is the same as our unresolved directory, and if so,
407 // we can mark this object as resolved to avoid more future resolves
408 m_is_resolved = (m_directory == resolved_lhs.m_directory);
409 }
410 else
411 return false;
412 }
413
414 FileSpec resolved_rhs(rhs);
415 if (!rhs.IsResolved())
416 {
417 if (resolved_rhs.ResolvePath())
418 {
419 // rhs's path wasn't resolved but now it is. Check if the resolved
420 // directory is the same as rhs's unresolved directory, and if so,
421 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000422 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000423 }
424 else
425 return false;
426 }
427
428 // If we reach this point in the code we were able to resolve both paths
429 // and since we only resolve the paths if the basenames are equal, then
430 // we can just check if both directories are equal...
431 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
432 }
433 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434}
435
436//------------------------------------------------------------------
437// Not equal to operator
438//------------------------------------------------------------------
439bool
440FileSpec::operator!= (const FileSpec& rhs) const
441{
Greg Clayton7481c202010-11-08 00:28:40 +0000442 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000443}
444
445//------------------------------------------------------------------
446// Less than operator
447//------------------------------------------------------------------
448bool
449FileSpec::operator< (const FileSpec& rhs) const
450{
451 return FileSpec::Compare(*this, rhs, true) < 0;
452}
453
454//------------------------------------------------------------------
455// Dump a FileSpec object to a stream
456//------------------------------------------------------------------
457Stream&
458lldb_private::operator << (Stream &s, const FileSpec& f)
459{
460 f.Dump(&s);
461 return s;
462}
463
464//------------------------------------------------------------------
465// Clear this object by releasing both the directory and filename
466// string values and making them both the empty string.
467//------------------------------------------------------------------
468void
469FileSpec::Clear()
470{
471 m_directory.Clear();
472 m_filename.Clear();
473}
474
475//------------------------------------------------------------------
476// Compare two FileSpec objects. If "full" is true, then both
477// the directory and the filename must match. If "full" is false,
478// then the directory names for "a" and "b" are only compared if
479// they are both non-empty. This allows a FileSpec object to only
480// contain a filename and it can match FileSpec objects that have
481// matching filenames with different paths.
482//
483// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
484// and "1" if "a" is greater than "b".
485//------------------------------------------------------------------
486int
487FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
488{
489 int result = 0;
490
491 // If full is true, then we must compare both the directory and filename.
492
493 // If full is false, then if either directory is empty, then we match on
494 // the basename only, and if both directories have valid values, we still
495 // do a full compare. This allows for matching when we just have a filename
496 // in one of the FileSpec objects.
497
498 if (full || (a.m_directory && b.m_directory))
499 {
500 result = ConstString::Compare(a.m_directory, b.m_directory);
501 if (result)
502 return result;
503 }
504 return ConstString::Compare (a.m_filename, b.m_filename);
505}
506
507bool
508FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full)
509{
Jim Ingham87df91b2011-09-23 00:54:11 +0000510 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000511 return a.m_filename == b.m_filename;
Jim Ingham87df91b2011-09-23 00:54:11 +0000512 else
513 return a == b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000514}
515
516
517
518//------------------------------------------------------------------
519// Dump the object to the supplied stream. If the object contains
520// a valid directory name, it will be displayed followed by a
521// directory delimiter, and the filename.
522//------------------------------------------------------------------
523void
524FileSpec::Dump(Stream *s) const
525{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000526 static ConstString g_slash_only ("/");
Enrico Granata80fcdd42012-11-03 00:09:46 +0000527 if (s)
528 {
529 m_directory.Dump(s);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000530 if (m_directory && m_directory != g_slash_only)
Enrico Granata80fcdd42012-11-03 00:09:46 +0000531 s->PutChar('/');
532 m_filename.Dump(s);
533 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534}
535
536//------------------------------------------------------------------
537// Returns true if the file exists.
538//------------------------------------------------------------------
539bool
540FileSpec::Exists () const
541{
542 struct stat file_stats;
543 return GetFileStats (this, &file_stats);
544}
545
Caroline Tice428a9a52010-09-10 04:48:55 +0000546bool
547FileSpec::ResolveExecutableLocation ()
548{
Greg Clayton274060b2010-10-20 20:54:39 +0000549 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000550 {
Greg Clayton58f41712011-01-25 21:32:01 +0000551 const char *file_cstr = m_filename.GetCString();
552 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000553 {
Greg Clayton58f41712011-01-25 21:32:01 +0000554 const std::string file_str (file_cstr);
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000555 std::string path = llvm::sys::FindProgramByName (file_str);
556 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton58f41712011-01-25 21:32:01 +0000557 //llvm::StringRef dir_ref = path.getDirname();
558 if (! dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000559 {
Greg Clayton58f41712011-01-25 21:32:01 +0000560 // FindProgramByName returns "." if it can't find the file.
561 if (strcmp (".", dir_ref.data()) == 0)
562 return false;
563
564 m_directory.SetCString (dir_ref.data());
565 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000566 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000567 else
568 {
569 // If FindProgramByName found the file, it returns the directory + filename in its return results.
570 // We need to separate them.
571 FileSpec tmp_file (dir_ref.data(), false);
572 if (tmp_file.Exists())
573 {
574 m_directory = tmp_file.m_directory;
575 return true;
576 }
Caroline Tice391a9602010-09-12 00:10:52 +0000577 }
578 }
579 }
580 }
581
582 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000583}
584
Jim Ingham0909e5f2010-09-16 00:57:33 +0000585bool
586FileSpec::ResolvePath ()
587{
Greg Clayton7481c202010-11-08 00:28:40 +0000588 if (m_is_resolved)
589 return true; // We have already resolved this path
590
591 char path_buf[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000592 if (!GetPath (path_buf, PATH_MAX))
593 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000594 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000595 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000596 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000597}
598
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599uint64_t
600FileSpec::GetByteSize() const
601{
602 struct stat file_stats;
603 if (GetFileStats (this, &file_stats))
604 return file_stats.st_size;
605 return 0;
606}
607
608FileSpec::FileType
609FileSpec::GetFileType () const
610{
611 struct stat file_stats;
612 if (GetFileStats (this, &file_stats))
613 {
614 mode_t file_type = file_stats.st_mode & S_IFMT;
615 switch (file_type)
616 {
617 case S_IFDIR: return eFileTypeDirectory;
618 case S_IFIFO: return eFileTypePipe;
619 case S_IFREG: return eFileTypeRegular;
620 case S_IFSOCK: return eFileTypeSocket;
621 case S_IFLNK: return eFileTypeSymbolicLink;
622 default:
623 break;
624 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000625 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626 }
627 return eFileTypeInvalid;
628}
629
630TimeValue
631FileSpec::GetModificationTime () const
632{
633 TimeValue mod_time;
634 struct stat file_stats;
635 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000636 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 return mod_time;
638}
639
640//------------------------------------------------------------------
641// Directory string get accessor.
642//------------------------------------------------------------------
643ConstString &
644FileSpec::GetDirectory()
645{
646 return m_directory;
647}
648
649//------------------------------------------------------------------
650// Directory string const get accessor.
651//------------------------------------------------------------------
652const ConstString &
653FileSpec::GetDirectory() const
654{
655 return m_directory;
656}
657
658//------------------------------------------------------------------
659// Filename string get accessor.
660//------------------------------------------------------------------
661ConstString &
662FileSpec::GetFilename()
663{
664 return m_filename;
665}
666
667//------------------------------------------------------------------
668// Filename string const get accessor.
669//------------------------------------------------------------------
670const ConstString &
671FileSpec::GetFilename() const
672{
673 return m_filename;
674}
675
676//------------------------------------------------------------------
677// Extract the directory and path into a fixed buffer. This is
678// needed as the directory and path are stored in separate string
679// values.
680//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000681size_t
682FileSpec::GetPath(char *path, size_t path_max_len) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683{
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000684 if (path_max_len)
Greg Claytondd36def2010-10-17 22:03:32 +0000685 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000686 const char *dirname = m_directory.GetCString();
687 const char *filename = m_filename.GetCString();
Greg Claytondd36def2010-10-17 22:03:32 +0000688 if (dirname)
689 {
690 if (filename)
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000691 return ::snprintf (path, path_max_len, "%s/%s", dirname, filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000692 else
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000693 return ::snprintf (path, path_max_len, "%s", dirname);
Greg Claytondd36def2010-10-17 22:03:32 +0000694 }
695 else if (filename)
696 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000697 return ::snprintf (path, path_max_len, "%s", filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000698 }
699 }
Enrico Granataa9dbf432011-10-17 21:45:27 +0000700 if (path)
701 path[0] = '\0';
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000702 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703}
704
Greg Claytona44c1e62013-04-29 16:36:27 +0000705std::string
706FileSpec::GetPath (void) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000707{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000708 static ConstString g_slash_only ("/");
Greg Claytona44c1e62013-04-29 16:36:27 +0000709 std::string path;
Jason Molendaa7ae4672013-04-29 09:46:43 +0000710 const char *dirname = m_directory.GetCString();
711 const char *filename = m_filename.GetCString();
Jason Molendaa7ae4672013-04-29 09:46:43 +0000712 if (dirname)
713 {
714 path.append (dirname);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000715 if (filename && m_directory != g_slash_only)
Jason Molendaa7ae4672013-04-29 09:46:43 +0000716 path.append ("/");
717 }
718 if (filename)
Jason Molendaa7ae4672013-04-29 09:46:43 +0000719 path.append (filename);
Jason Molendaa7ae4672013-04-29 09:46:43 +0000720 return path;
721}
722
Enrico Granataa9dbf432011-10-17 21:45:27 +0000723ConstString
724FileSpec::GetFileNameExtension () const
725{
Greg Clayton1f746072012-08-29 21:13:06 +0000726 if (m_filename)
727 {
728 const char *filename = m_filename.GetCString();
729 const char* dot_pos = strrchr(filename, '.');
730 if (dot_pos && dot_pos[1] != '\0')
731 return ConstString(dot_pos+1);
732 }
733 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000734}
735
736ConstString
737FileSpec::GetFileNameStrippingExtension () const
738{
739 const char *filename = m_filename.GetCString();
740 if (filename == NULL)
741 return ConstString();
742
Johnny Chenf5df5372011-10-18 19:28:30 +0000743 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000744 if (dot_pos == NULL)
745 return m_filename;
746
747 return ConstString(filename, dot_pos-filename);
748}
749
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750//------------------------------------------------------------------
751// Returns a shared pointer to a data buffer that contains all or
752// part of the contents of a file. The data is memory mapped and
753// will lazily page in data from the file as memory is accessed.
754// The data that is mappped will start "file_offset" bytes into the
755// file, and "file_size" bytes will be mapped. If "file_size" is
756// greater than the number of bytes available in the file starting
757// at "file_offset", the number of bytes will be appropriately
758// truncated. The final number of bytes that get mapped can be
759// verified using the DataBuffer::GetByteSize() function.
760//------------------------------------------------------------------
761DataBufferSP
762FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
763{
764 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000765 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766 if (mmap_data.get())
767 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000768 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
769 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770 data_sp.reset(mmap_data.release());
771 }
772 return data_sp;
773}
774
775
776//------------------------------------------------------------------
777// Return the size in bytes that this object takes in memory. This
778// returns the size in bytes of this object, not any shared string
779// values it may refer to.
780//------------------------------------------------------------------
781size_t
782FileSpec::MemorySize() const
783{
784 return m_filename.MemorySize() + m_directory.MemorySize();
785}
786
Greg Claytondda4f7b2010-06-30 23:03:03 +0000787
788size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000789FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790{
Greg Clayton4017fa32012-01-06 02:01:06 +0000791 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000792 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 char resolved_path[PATH_MAX];
794 if (GetPath(resolved_path, sizeof(resolved_path)))
795 {
Greg Clayton96c09682012-01-04 22:56:43 +0000796 File file;
797 error = file.Open(resolved_path, File::eOpenOptionRead);
798 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 {
Greg Clayton96c09682012-01-04 22:56:43 +0000800 off_t file_offset_after_seek = file_offset;
801 bytes_read = dst_len;
802 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000803 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000804 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000805 else
806 {
807 error.SetErrorString("invalid file specification");
808 }
809 if (error_ptr)
810 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000811 return bytes_read;
812}
813
814//------------------------------------------------------------------
815// Returns a shared pointer to a data buffer that contains all or
816// part of the contents of a file. The data copies into a heap based
817// buffer that lives in the DataBuffer shared pointer object returned.
818// The data that is cached will start "file_offset" bytes into the
819// file, and "file_size" bytes will be mapped. If "file_size" is
820// greater than the number of bytes available in the file starting
821// at "file_offset", the number of bytes will be appropriately
822// truncated. The final number of bytes that get mapped can be
823// verified using the DataBuffer::GetByteSize() function.
824//------------------------------------------------------------------
825DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000826FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000827{
Greg Clayton4017fa32012-01-06 02:01:06 +0000828 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000829 DataBufferSP data_sp;
830 char resolved_path[PATH_MAX];
831 if (GetPath(resolved_path, sizeof(resolved_path)))
832 {
Greg Clayton96c09682012-01-04 22:56:43 +0000833 File file;
834 error = file.Open(resolved_path, File::eOpenOptionRead);
835 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000836 {
837 const bool null_terminate = false;
838 error = file.Read (file_size, file_offset, null_terminate, data_sp);
839 }
840 }
841 else
842 {
843 error.SetErrorString("invalid file specification");
844 }
845 if (error_ptr)
846 *error_ptr = error;
847 return data_sp;
848}
849
850DataBufferSP
851FileSpec::ReadFileContentsAsCString(Error *error_ptr)
852{
853 Error error;
854 DataBufferSP data_sp;
855 char resolved_path[PATH_MAX];
856 if (GetPath(resolved_path, sizeof(resolved_path)))
857 {
858 File file;
859 error = file.Open(resolved_path, File::eOpenOptionRead);
860 if (error.Success())
861 {
862 off_t offset = 0;
863 size_t length = SIZE_MAX;
864 const bool null_terminate = true;
865 error = file.Read (length, offset, null_terminate, data_sp);
866 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000868 else
869 {
870 error.SetErrorString("invalid file specification");
871 }
872 if (error_ptr)
873 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874 return data_sp;
875}
876
Greg Clayton58fc50e2010-10-20 22:52:05 +0000877size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878FileSpec::ReadFileLines (STLStringArray &lines)
879{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000881 char path[PATH_MAX];
882 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000883 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000884 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885
Greg Clayton58fc50e2010-10-20 22:52:05 +0000886 if (file_stream)
887 {
888 std::string line;
889 while (getline (file_stream, line))
890 lines.push_back (line);
891 }
892 }
893 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894}
Greg Clayton4272cc72011-02-02 02:24:04 +0000895
896FileSpec::EnumerateDirectoryResult
897FileSpec::EnumerateDirectory
898(
899 const char *dir_path,
900 bool find_directories,
901 bool find_files,
902 bool find_other,
903 EnumerateDirectoryCallbackType callback,
904 void *callback_baton
905)
906{
907 if (dir_path && dir_path[0])
908 {
909 lldb_utility::CleanUp <DIR *, int> dir_path_dir (opendir(dir_path), NULL, closedir);
910 if (dir_path_dir.is_valid())
911 {
Jason Molenda14aef122013-04-04 03:19:27 +0000912 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
913#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
914 if (path_max < __DARWIN_MAXPATHLEN)
915 path_max = __DARWIN_MAXPATHLEN;
916#endif
917 struct dirent *buf, *dp;
918 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
919
920 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +0000921 {
922 // Only search directories
923 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
924 {
Greg Claytone0f3c022011-02-07 17:41:11 +0000925 size_t len = strlen(dp->d_name);
926
927 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +0000928 continue;
929
Greg Claytone0f3c022011-02-07 17:41:11 +0000930 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +0000931 continue;
932 }
933
934 bool call_callback = false;
935 FileSpec::FileType file_type = eFileTypeUnknown;
936
937 switch (dp->d_type)
938 {
939 default:
940 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
941 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
942 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
943 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
944 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
945 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
946 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
947 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +0000948#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +0000949 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +0000950#endif
Greg Clayton4272cc72011-02-02 02:24:04 +0000951 }
952
953 if (call_callback)
954 {
955 char child_path[PATH_MAX];
956 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
Johnny Chen44805302011-07-19 19:48:13 +0000957 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +0000958 {
959 // Don't resolve the file type or path
960 FileSpec child_path_spec (child_path, false);
961
962 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
963
964 switch (result)
965 {
Greg Clayton4272cc72011-02-02 02:24:04 +0000966 case eEnumerateDirectoryResultNext:
967 // Enumerate next entry in the current directory. We just
968 // exit this switch and will continue enumerating the
969 // current directory as we currently are...
970 break;
971
972 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
973 if (FileSpec::EnumerateDirectory (child_path,
974 find_directories,
975 find_files,
976 find_other,
977 callback,
978 callback_baton) == eEnumerateDirectoryResultQuit)
979 {
980 // The subdirectory returned Quit, which means to
981 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000982 if (buf)
983 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +0000984 return eEnumerateDirectoryResultQuit;
985 }
986 break;
987
988 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
989 // Exit from this directory level and tell parent to
990 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +0000991 if (buf)
992 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +0000993 return eEnumerateDirectoryResultNext;
994
995 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +0000996 if (buf)
997 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +0000998 return eEnumerateDirectoryResultQuit;
999 }
1000 }
1001 }
1002 }
Jason Molenda14aef122013-04-04 03:19:27 +00001003 if (buf)
1004 {
1005 free (buf);
1006 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001007 }
1008 }
1009 // By default when exiting a directory, we tell the parent enumeration
1010 // to continue enumerating.
1011 return eEnumerateDirectoryResultNext;
1012}
1013
Greg Clayton1f746072012-08-29 21:13:06 +00001014//------------------------------------------------------------------
1015/// Returns true if the filespec represents an implementation source
1016/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1017/// extension).
1018///
1019/// @return
1020/// \b true if the filespec represents an implementation source
1021/// file, \b false otherwise.
1022//------------------------------------------------------------------
1023bool
1024FileSpec::IsSourceImplementationFile () const
1025{
1026 ConstString extension (GetFileNameExtension());
1027 if (extension)
1028 {
1029 static RegularExpression g_source_file_regex ("^(c|m|mm|cpp|c\\+\\+|cxx|cc|cp|s|asm|f|f77|f90|f95|f03|for|ftn|fpp|ada|adb|ads)$",
1030 REG_EXTENDED | REG_ICASE);
1031 return g_source_file_regex.Execute (extension.GetCString());
1032 }
1033 return false;
1034}
1035
Greg Claytona0ca6602012-10-18 16:33:33 +00001036bool
1037FileSpec::IsRelativeToCurrentWorkingDirectory () const
1038{
1039 const char *directory = m_directory.GetCString();
1040 if (directory && directory[0])
1041 {
1042 // If the path doesn't start with '/' or '~', return true
1043 switch (directory[0])
1044 {
1045 case '/':
1046 case '~':
1047 return false;
1048 default:
1049 return true;
1050 }
1051 }
1052 else if (m_filename)
1053 {
1054 // No directory, just a basename, return true
1055 return true;
1056 }
1057 return false;
1058}