blob: 8b986c2a7fbee2291c4dfd7414828f4f7aa45958 [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;
38using namespace std;
39
40static bool
41GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
42{
43 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000044 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045 return ::stat (resolved_path, stats_ptr) == 0;
46 return false;
47}
48
Greg Clayton45319462011-02-08 00:35:34 +000049#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +000050
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051static const char*
52GetCachedGlobTildeSlash()
53{
54 static std::string g_tilde;
55 if (g_tilde.empty())
56 {
Jim Inghamf818ca32010-07-01 01:48:53 +000057 struct passwd *user_entry;
58 user_entry = getpwuid(geteuid());
59 if (user_entry != NULL)
60 g_tilde = user_entry->pw_dir;
61
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062 if (g_tilde.empty())
63 return NULL;
64 }
65 return g_tilde.c_str();
66}
67
Greg Clayton87e5ff02011-02-08 05:19:06 +000068#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
69
Jim Inghamf818ca32010-07-01 01:48:53 +000070// Resolves the username part of a path of the form ~user/other/directories, and
71// writes the result into dst_path.
72// Returns 0 if there WAS a ~ in the path but the username couldn't be resolved.
73// Otherwise returns the number of characters copied into dst_path. If the return
74// is >= dst_len, then the resolved path is too long...
Greg Claytonc982c762010-07-09 20:39:50 +000075size_t
Jim Inghamf818ca32010-07-01 01:48:53 +000076FileSpec::ResolveUsername (const char *src_path, char *dst_path, size_t dst_len)
77{
Greg Clayton87e5ff02011-02-08 05:19:06 +000078 if (src_path == NULL || src_path[0] == '\0')
79 return 0;
80
81#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
82
Jim Inghamf818ca32010-07-01 01:48:53 +000083 char user_home[PATH_MAX];
84 const char *user_name;
85
Greg Claytona5d24f62010-07-01 17:07:48 +000086
Jim Inghamf818ca32010-07-01 01:48:53 +000087 // If there's no ~, then just copy src_path straight to dst_path (they may be the same string...)
88 if (src_path[0] != '~')
89 {
Greg Claytonc982c762010-07-09 20:39:50 +000090 size_t len = strlen (src_path);
Jim Inghamf818ca32010-07-01 01:48:53 +000091 if (len >= dst_len)
92 {
Greg Claytona5d24f62010-07-01 17:07:48 +000093 ::bcopy (src_path, dst_path, dst_len - 1);
94 dst_path[dst_len] = '\0';
Jim Inghamf818ca32010-07-01 01:48:53 +000095 }
96 else
Greg Claytona5d24f62010-07-01 17:07:48 +000097 ::bcopy (src_path, dst_path, len + 1);
98
Jim Inghamf818ca32010-07-01 01:48:53 +000099 return len;
100 }
101
Eli Friedmanfeaeebf2010-07-02 19:15:50 +0000102 const char *first_slash = ::strchr (src_path, '/');
Jim Inghamf818ca32010-07-01 01:48:53 +0000103 char remainder[PATH_MAX];
104
105 if (first_slash == NULL)
106 {
107 // The whole name is the username (minus the ~):
108 user_name = src_path + 1;
109 remainder[0] = '\0';
110 }
111 else
112 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000113 size_t user_name_len = first_slash - src_path - 1;
Greg Claytona5d24f62010-07-01 17:07:48 +0000114 ::memcpy (user_home, src_path + 1, user_name_len);
Jim Inghamf818ca32010-07-01 01:48:53 +0000115 user_home[user_name_len] = '\0';
116 user_name = user_home;
117
Greg Claytona5d24f62010-07-01 17:07:48 +0000118 ::strcpy (remainder, first_slash);
Jim Inghamf818ca32010-07-01 01:48:53 +0000119 }
Greg Claytona5d24f62010-07-01 17:07:48 +0000120
Jim Inghamf818ca32010-07-01 01:48:53 +0000121 if (user_name == NULL)
122 return 0;
123 // User name of "" means the current user...
124
125 struct passwd *user_entry;
Greg Claytonc982c762010-07-09 20:39:50 +0000126 const char *home_dir = NULL;
Jim Inghamf818ca32010-07-01 01:48:53 +0000127
128 if (user_name[0] == '\0')
129 {
130 home_dir = GetCachedGlobTildeSlash();
131 }
132 else
133 {
Greg Claytona5d24f62010-07-01 17:07:48 +0000134 user_entry = ::getpwnam (user_name);
Jim Inghamf818ca32010-07-01 01:48:53 +0000135 if (user_entry != NULL)
136 home_dir = user_entry->pw_dir;
137 }
138
139 if (home_dir == NULL)
140 return 0;
141 else
142 return ::snprintf (dst_path, dst_len, "%s%s", home_dir, remainder);
Greg Clayton87e5ff02011-02-08 05:19:06 +0000143#else
144 // Resolving home directories is not supported, just copy the path...
145 return ::snprintf (dst_path, dst_len, "%s", src_path);
146#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000147}
148
Greg Claytonc982c762010-07-09 20:39:50 +0000149size_t
Jim Ingham84363072011-02-08 23:24:09 +0000150FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
151{
152#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
153 size_t extant_entries = matches.GetSize();
154
155 setpwent();
156 struct passwd *user_entry;
157 const char *name_start = partial_name + 1;
158 std::set<std::string> name_list;
159
160 while ((user_entry = getpwent()) != NULL)
161 {
162 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
163 {
164 std::string tmp_buf("~");
165 tmp_buf.append(user_entry->pw_name);
166 tmp_buf.push_back('/');
167 name_list.insert(tmp_buf);
168 }
169 }
170 std::set<std::string>::iterator pos, end = name_list.end();
171 for (pos = name_list.begin(); pos != end; pos++)
172 {
173 matches.AppendString((*pos).c_str());
174 }
175 return matches.GetSize() - extant_entries;
176#else
177 // Resolving home directories is not supported, just copy the path...
178 return 0;
179#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
180}
181
182
183
184size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000185FileSpec::Resolve (const char *src_path, char *dst_path, size_t dst_len)
186{
187 if (src_path == NULL || src_path[0] == '\0')
188 return 0;
189
190 // Glob if needed for ~/, otherwise copy in case src_path is same as dst_path...
191 char unglobbed_path[PATH_MAX];
Greg Clayton45319462011-02-08 00:35:34 +0000192#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000193 if (src_path[0] == '~')
194 {
Greg Claytonc982c762010-07-09 20:39:50 +0000195 size_t return_count = ResolveUsername(src_path, unglobbed_path, sizeof(unglobbed_path));
Jim Inghamf818ca32010-07-01 01:48:53 +0000196
197 // If we couldn't find the user referred to, or the resultant path was too long,
198 // then just copy over the src_path.
199 if (return_count == 0 || return_count >= sizeof(unglobbed_path))
200 ::snprintf (unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
201 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202 else
Greg Clayton45319462011-02-08 00:35:34 +0000203#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +0000204 {
205 ::snprintf(unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
206 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207
208 // Now resolve the path if needed
209 char resolved_path[PATH_MAX];
210 if (::realpath (unglobbed_path, resolved_path))
211 {
212 // Success, copy the resolved path
213 return ::snprintf(dst_path, dst_len, "%s", resolved_path);
214 }
215 else
216 {
217 // Failed, just copy the unglobbed path
218 return ::snprintf(dst_path, dst_len, "%s", unglobbed_path);
219 }
220}
221
222FileSpec::FileSpec() :
223 m_directory(),
224 m_filename()
225{
226}
227
228//------------------------------------------------------------------
229// Default constructor that can take an optional full path to a
230// file on disk.
231//------------------------------------------------------------------
Jim Ingham0909e5f2010-09-16 00:57:33 +0000232FileSpec::FileSpec(const char *pathname, bool resolve_path) :
233 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000234 m_filename(),
235 m_is_resolved(false)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000236{
237 if (pathname && pathname[0])
238 SetFile(pathname, resolve_path);
239}
240
241//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000242// Copy constructor
243//------------------------------------------------------------------
244FileSpec::FileSpec(const FileSpec& rhs) :
245 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000246 m_filename (rhs.m_filename),
247 m_is_resolved (rhs.m_is_resolved)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000248{
249}
250
251//------------------------------------------------------------------
252// Copy constructor
253//------------------------------------------------------------------
254FileSpec::FileSpec(const FileSpec* rhs) :
255 m_directory(),
256 m_filename()
257{
258 if (rhs)
259 *this = *rhs;
260}
261
262//------------------------------------------------------------------
263// Virtual destrcuctor in case anyone inherits from this class.
264//------------------------------------------------------------------
265FileSpec::~FileSpec()
266{
267}
268
269//------------------------------------------------------------------
270// Assignment operator.
271//------------------------------------------------------------------
272const FileSpec&
273FileSpec::operator= (const FileSpec& rhs)
274{
275 if (this != &rhs)
276 {
277 m_directory = rhs.m_directory;
278 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000279 m_is_resolved = rhs.m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000280 }
281 return *this;
282}
283
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284//------------------------------------------------------------------
285// Update the contents of this object with a new path. The path will
286// be split up into a directory and filename and stored as uniqued
287// string values for quick comparison and efficient memory usage.
288//------------------------------------------------------------------
289void
Greg Clayton7481c202010-11-08 00:28:40 +0000290FileSpec::SetFile (const char *pathname, bool resolve)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000291{
292 m_filename.Clear();
293 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000294 m_is_resolved = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295 if (pathname == NULL || pathname[0] == '\0')
296 return;
297
298 char resolved_path[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000299 bool path_fit = true;
300
301 if (resolve)
302 {
303 path_fit = (FileSpec::Resolve (pathname, resolved_path, sizeof(resolved_path)) < sizeof(resolved_path) - 1);
Greg Clayton7481c202010-11-08 00:28:40 +0000304 m_is_resolved = path_fit;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000305 }
306 else
307 {
Greg Clayton7481c202010-11-08 00:28:40 +0000308 // Copy the path because "basename" and "dirname" want to muck with the
309 // path buffer
310 if (::strlen (pathname) > sizeof(resolved_path) - 1)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000311 path_fit = false;
312 else
Greg Clayton7481c202010-11-08 00:28:40 +0000313 ::strcpy (resolved_path, pathname);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000314 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000315
Jim Ingham0909e5f2010-09-16 00:57:33 +0000316
317 if (path_fit)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 {
319 char *filename = ::basename (resolved_path);
320 if (filename)
321 {
322 m_filename.SetCString (filename);
323 // Truncate the basename off the end of the resolved path
324
325 // Only attempt to get the dirname if it looks like we have a path
326 if (strchr(resolved_path, '/'))
327 {
328 char *directory = ::dirname (resolved_path);
329
330 // Make sure we didn't get our directory resolved to "." without having
331 // specified
332 if (directory)
333 m_directory.SetCString(directory);
334 else
335 {
336 char *last_resolved_path_slash = strrchr(resolved_path, '/');
337 if (last_resolved_path_slash)
338 {
339 *last_resolved_path_slash = '\0';
340 m_directory.SetCString(resolved_path);
341 }
342 }
343 }
344 }
345 else
346 m_directory.SetCString(resolved_path);
347 }
348}
349
350//----------------------------------------------------------------------
351// Convert to pointer operator. This allows code to check any FileSpec
352// objects to see if they contain anything valid using code such as:
353//
354// if (file_spec)
355// {}
356//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000357FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000359 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360}
361
362//----------------------------------------------------------------------
363// Logical NOT operator. This allows code to check any FileSpec
364// objects to see if they are invalid using code such as:
365//
366// if (!file_spec)
367// {}
368//----------------------------------------------------------------------
369bool
370FileSpec::operator!() const
371{
372 return !m_directory && !m_filename;
373}
374
375//------------------------------------------------------------------
376// Equal to operator
377//------------------------------------------------------------------
378bool
379FileSpec::operator== (const FileSpec& rhs) const
380{
Greg Clayton7481c202010-11-08 00:28:40 +0000381 if (m_filename == rhs.m_filename)
382 {
383 if (m_directory == rhs.m_directory)
384 return true;
385
386 // TODO: determine if we want to keep this code in here.
387 // The code below was added to handle a case where we were
388 // trying to set a file and line breakpoint and one path
389 // was resolved, and the other not and the directory was
390 // in a mount point that resolved to a more complete path:
391 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
392 // this out...
393 if (IsResolved() && rhs.IsResolved())
394 {
395 // Both paths are resolved, no need to look further...
396 return false;
397 }
398
399 FileSpec resolved_lhs(*this);
400
401 // If "this" isn't resolved, resolve it
402 if (!IsResolved())
403 {
404 if (resolved_lhs.ResolvePath())
405 {
406 // This path wasn't resolved but now it is. Check if the resolved
407 // directory is the same as our unresolved directory, and if so,
408 // we can mark this object as resolved to avoid more future resolves
409 m_is_resolved = (m_directory == resolved_lhs.m_directory);
410 }
411 else
412 return false;
413 }
414
415 FileSpec resolved_rhs(rhs);
416 if (!rhs.IsResolved())
417 {
418 if (resolved_rhs.ResolvePath())
419 {
420 // rhs's path wasn't resolved but now it is. Check if the resolved
421 // directory is the same as rhs's unresolved directory, and if so,
422 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000423 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000424 }
425 else
426 return false;
427 }
428
429 // If we reach this point in the code we were able to resolve both paths
430 // and since we only resolve the paths if the basenames are equal, then
431 // we can just check if both directories are equal...
432 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
433 }
434 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435}
436
437//------------------------------------------------------------------
438// Not equal to operator
439//------------------------------------------------------------------
440bool
441FileSpec::operator!= (const FileSpec& rhs) const
442{
Greg Clayton7481c202010-11-08 00:28:40 +0000443 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444}
445
446//------------------------------------------------------------------
447// Less than operator
448//------------------------------------------------------------------
449bool
450FileSpec::operator< (const FileSpec& rhs) const
451{
452 return FileSpec::Compare(*this, rhs, true) < 0;
453}
454
455//------------------------------------------------------------------
456// Dump a FileSpec object to a stream
457//------------------------------------------------------------------
458Stream&
459lldb_private::operator << (Stream &s, const FileSpec& f)
460{
461 f.Dump(&s);
462 return s;
463}
464
465//------------------------------------------------------------------
466// Clear this object by releasing both the directory and filename
467// string values and making them both the empty string.
468//------------------------------------------------------------------
469void
470FileSpec::Clear()
471{
472 m_directory.Clear();
473 m_filename.Clear();
474}
475
476//------------------------------------------------------------------
477// Compare two FileSpec objects. If "full" is true, then both
478// the directory and the filename must match. If "full" is false,
479// then the directory names for "a" and "b" are only compared if
480// they are both non-empty. This allows a FileSpec object to only
481// contain a filename and it can match FileSpec objects that have
482// matching filenames with different paths.
483//
484// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
485// and "1" if "a" is greater than "b".
486//------------------------------------------------------------------
487int
488FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
489{
490 int result = 0;
491
492 // If full is true, then we must compare both the directory and filename.
493
494 // If full is false, then if either directory is empty, then we match on
495 // the basename only, and if both directories have valid values, we still
496 // do a full compare. This allows for matching when we just have a filename
497 // in one of the FileSpec objects.
498
499 if (full || (a.m_directory && b.m_directory))
500 {
501 result = ConstString::Compare(a.m_directory, b.m_directory);
502 if (result)
503 return result;
504 }
505 return ConstString::Compare (a.m_filename, b.m_filename);
506}
507
508bool
509FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full)
510{
Jim Ingham87df91b2011-09-23 00:54:11 +0000511 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000512 return a.m_filename == b.m_filename;
Jim Ingham87df91b2011-09-23 00:54:11 +0000513 else
514 return a == b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000515}
516
517
518
519//------------------------------------------------------------------
520// Dump the object to the supplied stream. If the object contains
521// a valid directory name, it will be displayed followed by a
522// directory delimiter, and the filename.
523//------------------------------------------------------------------
524void
525FileSpec::Dump(Stream *s) const
526{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000527 if (s)
528 {
529 m_directory.Dump(s);
530 if (m_directory)
531 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);
555 llvm::sys::Path path = llvm::sys::Program::FindProgramByName (file_str);
556 const std::string &path_str = path.str();
557 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path_str);
558 //llvm::StringRef dir_ref = path.getDirname();
559 if (! dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000560 {
Greg Clayton58f41712011-01-25 21:32:01 +0000561 // FindProgramByName returns "." if it can't find the file.
562 if (strcmp (".", dir_ref.data()) == 0)
563 return false;
564
565 m_directory.SetCString (dir_ref.data());
566 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000567 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000568 else
569 {
570 // If FindProgramByName found the file, it returns the directory + filename in its return results.
571 // We need to separate them.
572 FileSpec tmp_file (dir_ref.data(), false);
573 if (tmp_file.Exists())
574 {
575 m_directory = tmp_file.m_directory;
576 return true;
577 }
Caroline Tice391a9602010-09-12 00:10:52 +0000578 }
579 }
580 }
581 }
582
583 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000584}
585
Jim Ingham0909e5f2010-09-16 00:57:33 +0000586bool
587FileSpec::ResolvePath ()
588{
Greg Clayton7481c202010-11-08 00:28:40 +0000589 if (m_is_resolved)
590 return true; // We have already resolved this path
591
592 char path_buf[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000593 if (!GetPath (path_buf, PATH_MAX))
594 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000595 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000596 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000597 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000598}
599
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000600uint64_t
601FileSpec::GetByteSize() const
602{
603 struct stat file_stats;
604 if (GetFileStats (this, &file_stats))
605 return file_stats.st_size;
606 return 0;
607}
608
609FileSpec::FileType
610FileSpec::GetFileType () const
611{
612 struct stat file_stats;
613 if (GetFileStats (this, &file_stats))
614 {
615 mode_t file_type = file_stats.st_mode & S_IFMT;
616 switch (file_type)
617 {
618 case S_IFDIR: return eFileTypeDirectory;
619 case S_IFIFO: return eFileTypePipe;
620 case S_IFREG: return eFileTypeRegular;
621 case S_IFSOCK: return eFileTypeSocket;
622 case S_IFLNK: return eFileTypeSymbolicLink;
623 default:
624 break;
625 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000626 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 }
628 return eFileTypeInvalid;
629}
630
631TimeValue
632FileSpec::GetModificationTime () const
633{
634 TimeValue mod_time;
635 struct stat file_stats;
636 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000637 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 return mod_time;
639}
640
641//------------------------------------------------------------------
642// Directory string get accessor.
643//------------------------------------------------------------------
644ConstString &
645FileSpec::GetDirectory()
646{
647 return m_directory;
648}
649
650//------------------------------------------------------------------
651// Directory string const get accessor.
652//------------------------------------------------------------------
653const ConstString &
654FileSpec::GetDirectory() const
655{
656 return m_directory;
657}
658
659//------------------------------------------------------------------
660// Filename string get accessor.
661//------------------------------------------------------------------
662ConstString &
663FileSpec::GetFilename()
664{
665 return m_filename;
666}
667
668//------------------------------------------------------------------
669// Filename string const get accessor.
670//------------------------------------------------------------------
671const ConstString &
672FileSpec::GetFilename() const
673{
674 return m_filename;
675}
676
677//------------------------------------------------------------------
678// Extract the directory and path into a fixed buffer. This is
679// needed as the directory and path are stored in separate string
680// values.
681//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000682size_t
683FileSpec::GetPath(char *path, size_t path_max_len) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684{
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000685 if (path_max_len)
Greg Claytondd36def2010-10-17 22:03:32 +0000686 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000687 const char *dirname = m_directory.GetCString();
688 const char *filename = m_filename.GetCString();
Greg Claytondd36def2010-10-17 22:03:32 +0000689 if (dirname)
690 {
691 if (filename)
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000692 return ::snprintf (path, path_max_len, "%s/%s", dirname, filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000693 else
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000694 return ::snprintf (path, path_max_len, "%s", dirname);
Greg Claytondd36def2010-10-17 22:03:32 +0000695 }
696 else if (filename)
697 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000698 return ::snprintf (path, path_max_len, "%s", filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000699 }
700 }
Enrico Granataa9dbf432011-10-17 21:45:27 +0000701 if (path)
702 path[0] = '\0';
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000703 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704}
705
Enrico Granataa9dbf432011-10-17 21:45:27 +0000706ConstString
707FileSpec::GetFileNameExtension () const
708{
Greg Clayton1f746072012-08-29 21:13:06 +0000709 if (m_filename)
710 {
711 const char *filename = m_filename.GetCString();
712 const char* dot_pos = strrchr(filename, '.');
713 if (dot_pos && dot_pos[1] != '\0')
714 return ConstString(dot_pos+1);
715 }
716 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000717}
718
719ConstString
720FileSpec::GetFileNameStrippingExtension () const
721{
722 const char *filename = m_filename.GetCString();
723 if (filename == NULL)
724 return ConstString();
725
Johnny Chenf5df5372011-10-18 19:28:30 +0000726 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000727 if (dot_pos == NULL)
728 return m_filename;
729
730 return ConstString(filename, dot_pos-filename);
731}
732
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733//------------------------------------------------------------------
734// Returns a shared pointer to a data buffer that contains all or
735// part of the contents of a file. The data is memory mapped and
736// will lazily page in data from the file as memory is accessed.
737// The data that is mappped will start "file_offset" bytes into the
738// file, and "file_size" bytes will be mapped. If "file_size" is
739// greater than the number of bytes available in the file starting
740// at "file_offset", the number of bytes will be appropriately
741// truncated. The final number of bytes that get mapped can be
742// verified using the DataBuffer::GetByteSize() function.
743//------------------------------------------------------------------
744DataBufferSP
745FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
746{
747 DataBufferSP data_sp;
748 auto_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
749 if (mmap_data.get())
750 {
751 if (mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size) >= file_size)
752 data_sp.reset(mmap_data.release());
753 }
754 return data_sp;
755}
756
757
758//------------------------------------------------------------------
759// Return the size in bytes that this object takes in memory. This
760// returns the size in bytes of this object, not any shared string
761// values it may refer to.
762//------------------------------------------------------------------
763size_t
764FileSpec::MemorySize() const
765{
766 return m_filename.MemorySize() + m_directory.MemorySize();
767}
768
Greg Claytondda4f7b2010-06-30 23:03:03 +0000769
770size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000771FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772{
Greg Clayton4017fa32012-01-06 02:01:06 +0000773 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000774 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 char resolved_path[PATH_MAX];
776 if (GetPath(resolved_path, sizeof(resolved_path)))
777 {
Greg Clayton96c09682012-01-04 22:56:43 +0000778 File file;
779 error = file.Open(resolved_path, File::eOpenOptionRead);
780 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 {
Greg Clayton96c09682012-01-04 22:56:43 +0000782 off_t file_offset_after_seek = file_offset;
783 bytes_read = dst_len;
784 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000785 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000786 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000787 else
788 {
789 error.SetErrorString("invalid file specification");
790 }
791 if (error_ptr)
792 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000793 return bytes_read;
794}
795
796//------------------------------------------------------------------
797// Returns a shared pointer to a data buffer that contains all or
798// part of the contents of a file. The data copies into a heap based
799// buffer that lives in the DataBuffer shared pointer object returned.
800// The data that is cached will start "file_offset" bytes into the
801// file, and "file_size" bytes will be mapped. If "file_size" is
802// greater than the number of bytes available in the file starting
803// at "file_offset", the number of bytes will be appropriately
804// truncated. The final number of bytes that get mapped can be
805// verified using the DataBuffer::GetByteSize() function.
806//------------------------------------------------------------------
807DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000808FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000809{
Greg Clayton4017fa32012-01-06 02:01:06 +0000810 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000811 DataBufferSP data_sp;
812 char resolved_path[PATH_MAX];
813 if (GetPath(resolved_path, sizeof(resolved_path)))
814 {
Greg Clayton96c09682012-01-04 22:56:43 +0000815 File file;
816 error = file.Open(resolved_path, File::eOpenOptionRead);
817 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000818 {
819 const bool null_terminate = false;
820 error = file.Read (file_size, file_offset, null_terminate, data_sp);
821 }
822 }
823 else
824 {
825 error.SetErrorString("invalid file specification");
826 }
827 if (error_ptr)
828 *error_ptr = error;
829 return data_sp;
830}
831
832DataBufferSP
833FileSpec::ReadFileContentsAsCString(Error *error_ptr)
834{
835 Error error;
836 DataBufferSP data_sp;
837 char resolved_path[PATH_MAX];
838 if (GetPath(resolved_path, sizeof(resolved_path)))
839 {
840 File file;
841 error = file.Open(resolved_path, File::eOpenOptionRead);
842 if (error.Success())
843 {
844 off_t offset = 0;
845 size_t length = SIZE_MAX;
846 const bool null_terminate = true;
847 error = file.Read (length, offset, null_terminate, data_sp);
848 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000850 else
851 {
852 error.SetErrorString("invalid file specification");
853 }
854 if (error_ptr)
855 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000856 return data_sp;
857}
858
Greg Clayton58fc50e2010-10-20 22:52:05 +0000859size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860FileSpec::ReadFileLines (STLStringArray &lines)
861{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000863 char path[PATH_MAX];
864 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 {
Greg Clayton58fc50e2010-10-20 22:52:05 +0000866 ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867
Greg Clayton58fc50e2010-10-20 22:52:05 +0000868 if (file_stream)
869 {
870 std::string line;
871 while (getline (file_stream, line))
872 lines.push_back (line);
873 }
874 }
875 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876}
Greg Clayton4272cc72011-02-02 02:24:04 +0000877
878FileSpec::EnumerateDirectoryResult
879FileSpec::EnumerateDirectory
880(
881 const char *dir_path,
882 bool find_directories,
883 bool find_files,
884 bool find_other,
885 EnumerateDirectoryCallbackType callback,
886 void *callback_baton
887)
888{
889 if (dir_path && dir_path[0])
890 {
891 lldb_utility::CleanUp <DIR *, int> dir_path_dir (opendir(dir_path), NULL, closedir);
892 if (dir_path_dir.is_valid())
893 {
894 struct dirent* dp;
895 while ((dp = readdir(dir_path_dir.get())) != NULL)
896 {
897 // Only search directories
898 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
899 {
Greg Claytone0f3c022011-02-07 17:41:11 +0000900 size_t len = strlen(dp->d_name);
901
902 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +0000903 continue;
904
Greg Claytone0f3c022011-02-07 17:41:11 +0000905 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +0000906 continue;
907 }
908
909 bool call_callback = false;
910 FileSpec::FileType file_type = eFileTypeUnknown;
911
912 switch (dp->d_type)
913 {
914 default:
915 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
916 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
917 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
918 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
919 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
920 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
921 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
922 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +0000923#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +0000924 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +0000925#endif
Greg Clayton4272cc72011-02-02 02:24:04 +0000926 }
927
928 if (call_callback)
929 {
930 char child_path[PATH_MAX];
931 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 +0000932 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +0000933 {
934 // Don't resolve the file type or path
935 FileSpec child_path_spec (child_path, false);
936
937 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
938
939 switch (result)
940 {
Greg Clayton4272cc72011-02-02 02:24:04 +0000941 case eEnumerateDirectoryResultNext:
942 // Enumerate next entry in the current directory. We just
943 // exit this switch and will continue enumerating the
944 // current directory as we currently are...
945 break;
946
947 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
948 if (FileSpec::EnumerateDirectory (child_path,
949 find_directories,
950 find_files,
951 find_other,
952 callback,
953 callback_baton) == eEnumerateDirectoryResultQuit)
954 {
955 // The subdirectory returned Quit, which means to
956 // stop all directory enumerations at all levels.
957 return eEnumerateDirectoryResultQuit;
958 }
959 break;
960
961 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
962 // Exit from this directory level and tell parent to
963 // keep enumerating.
964 return eEnumerateDirectoryResultNext;
965
966 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
967 return eEnumerateDirectoryResultQuit;
968 }
969 }
970 }
971 }
972 }
973 }
974 // By default when exiting a directory, we tell the parent enumeration
975 // to continue enumerating.
976 return eEnumerateDirectoryResultNext;
977}
978
Greg Clayton1f746072012-08-29 21:13:06 +0000979//------------------------------------------------------------------
980/// Returns true if the filespec represents an implementation source
981/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
982/// extension).
983///
984/// @return
985/// \b true if the filespec represents an implementation source
986/// file, \b false otherwise.
987//------------------------------------------------------------------
988bool
989FileSpec::IsSourceImplementationFile () const
990{
991 ConstString extension (GetFileNameExtension());
992 if (extension)
993 {
994 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)$",
995 REG_EXTENDED | REG_ICASE);
996 return g_source_file_regex.Execute (extension.GetCString());
997 }
998 return false;
999}
1000
Greg Claytona0ca6602012-10-18 16:33:33 +00001001bool
1002FileSpec::IsRelativeToCurrentWorkingDirectory () const
1003{
1004 const char *directory = m_directory.GetCString();
1005 if (directory && directory[0])
1006 {
1007 // If the path doesn't start with '/' or '~', return true
1008 switch (directory[0])
1009 {
1010 case '/':
1011 case '~':
1012 return false;
1013 default:
1014 return true;
1015 }
1016 }
1017 else if (m_filename)
1018 {
1019 // No directory, just a basename, return true
1020 return true;
1021 }
1022 return false;
1023}
1024
Greg Clayton1f746072012-08-29 21:13:06 +00001025