blob: 4b8037aef11fa44c554b8843527be723dbed096a [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>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include <libgen.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include <sys/stat.h>
Rafael Espindola09079162013-06-13 20:10:23 +000019#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000020#include <string.h>
Jim Ingham9035e7c2011-02-07 19:42:39 +000021#include <fstream>
Greg Claytonfd184262011-02-05 02:27:52 +000022
Jim Ingham9035e7c2011-02-07 19:42:39 +000023#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000024#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000025#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000026#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Caroline Tice391a9602010-09-12 00:10:52 +000028#include "llvm/ADT/StringRef.h"
Greg Clayton38a61402010-12-02 23:20:03 +000029#include "llvm/Support/Path.h"
30#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000031
Daniel Maleae0f8f572013-08-26 23:57:52 +000032#include "lldb/Core/StreamString.h"
Greg Clayton96c09682012-01-04 22:56:43 +000033#include "lldb/Host/File.h"
Greg Clayton53239f02011-02-08 05:05:52 +000034#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Core/DataBufferHeap.h"
36#include "lldb/Core/DataBufferMemoryMap.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Core/RegularExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Core/Stream.h"
Caroline Tice428a9a52010-09-10 04:48:55 +000039#include "lldb/Host/Host.h"
Greg Clayton4272cc72011-02-02 02:24:04 +000040#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
45static bool
46GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
47{
48 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +000049 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050 return ::stat (resolved_path, stats_ptr) == 0;
51 return false;
52}
53
Greg Clayton45319462011-02-08 00:35:34 +000054#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +000055
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056static const char*
57GetCachedGlobTildeSlash()
58{
59 static std::string g_tilde;
60 if (g_tilde.empty())
61 {
Jim Inghamf818ca32010-07-01 01:48:53 +000062 struct passwd *user_entry;
63 user_entry = getpwuid(geteuid());
64 if (user_entry != NULL)
65 g_tilde = user_entry->pw_dir;
66
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067 if (g_tilde.empty())
68 return NULL;
69 }
70 return g_tilde.c_str();
71}
72
Greg Clayton87e5ff02011-02-08 05:19:06 +000073#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
74
Jim Inghamf818ca32010-07-01 01:48:53 +000075// Resolves the username part of a path of the form ~user/other/directories, and
76// writes the result into dst_path.
77// Returns 0 if there WAS a ~ in the path but the username couldn't be resolved.
78// Otherwise returns the number of characters copied into dst_path. If the return
79// is >= dst_len, then the resolved path is too long...
Greg Claytonc982c762010-07-09 20:39:50 +000080size_t
Jim Inghamf818ca32010-07-01 01:48:53 +000081FileSpec::ResolveUsername (const char *src_path, char *dst_path, size_t dst_len)
82{
Greg Clayton87e5ff02011-02-08 05:19:06 +000083 if (src_path == NULL || src_path[0] == '\0')
84 return 0;
85
86#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
87
Jim Inghamf818ca32010-07-01 01:48:53 +000088 char user_home[PATH_MAX];
89 const char *user_name;
90
Greg Claytona5d24f62010-07-01 17:07:48 +000091
Jim Inghamf818ca32010-07-01 01:48:53 +000092 // If there's no ~, then just copy src_path straight to dst_path (they may be the same string...)
93 if (src_path[0] != '~')
94 {
Greg Claytonc982c762010-07-09 20:39:50 +000095 size_t len = strlen (src_path);
Jim Inghamf818ca32010-07-01 01:48:53 +000096 if (len >= dst_len)
97 {
Greg Claytona5d24f62010-07-01 17:07:48 +000098 ::bcopy (src_path, dst_path, dst_len - 1);
99 dst_path[dst_len] = '\0';
Jim Inghamf818ca32010-07-01 01:48:53 +0000100 }
101 else
Greg Claytona5d24f62010-07-01 17:07:48 +0000102 ::bcopy (src_path, dst_path, len + 1);
103
Jim Inghamf818ca32010-07-01 01:48:53 +0000104 return len;
105 }
106
Eli Friedmanfeaeebf2010-07-02 19:15:50 +0000107 const char *first_slash = ::strchr (src_path, '/');
Jim Inghamf818ca32010-07-01 01:48:53 +0000108 char remainder[PATH_MAX];
109
110 if (first_slash == NULL)
111 {
112 // The whole name is the username (minus the ~):
113 user_name = src_path + 1;
114 remainder[0] = '\0';
115 }
116 else
117 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000118 size_t user_name_len = first_slash - src_path - 1;
Greg Claytona5d24f62010-07-01 17:07:48 +0000119 ::memcpy (user_home, src_path + 1, user_name_len);
Jim Inghamf818ca32010-07-01 01:48:53 +0000120 user_home[user_name_len] = '\0';
121 user_name = user_home;
122
Greg Claytona5d24f62010-07-01 17:07:48 +0000123 ::strcpy (remainder, first_slash);
Jim Inghamf818ca32010-07-01 01:48:53 +0000124 }
Greg Claytona5d24f62010-07-01 17:07:48 +0000125
Jim Inghamf818ca32010-07-01 01:48:53 +0000126 if (user_name == NULL)
127 return 0;
128 // User name of "" means the current user...
129
130 struct passwd *user_entry;
Greg Claytonc982c762010-07-09 20:39:50 +0000131 const char *home_dir = NULL;
Jim Inghamf818ca32010-07-01 01:48:53 +0000132
133 if (user_name[0] == '\0')
134 {
135 home_dir = GetCachedGlobTildeSlash();
136 }
137 else
138 {
Greg Claytona5d24f62010-07-01 17:07:48 +0000139 user_entry = ::getpwnam (user_name);
Jim Inghamf818ca32010-07-01 01:48:53 +0000140 if (user_entry != NULL)
141 home_dir = user_entry->pw_dir;
142 }
143
144 if (home_dir == NULL)
145 return 0;
146 else
147 return ::snprintf (dst_path, dst_len, "%s%s", home_dir, remainder);
Greg Clayton87e5ff02011-02-08 05:19:06 +0000148#else
149 // Resolving home directories is not supported, just copy the path...
150 return ::snprintf (dst_path, dst_len, "%s", src_path);
151#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000152}
153
Greg Claytonc982c762010-07-09 20:39:50 +0000154size_t
Jim Ingham84363072011-02-08 23:24:09 +0000155FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
156{
157#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
158 size_t extant_entries = matches.GetSize();
159
160 setpwent();
161 struct passwd *user_entry;
162 const char *name_start = partial_name + 1;
163 std::set<std::string> name_list;
164
165 while ((user_entry = getpwent()) != NULL)
166 {
167 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
168 {
169 std::string tmp_buf("~");
170 tmp_buf.append(user_entry->pw_name);
171 tmp_buf.push_back('/');
172 name_list.insert(tmp_buf);
173 }
174 }
175 std::set<std::string>::iterator pos, end = name_list.end();
176 for (pos = name_list.begin(); pos != end; pos++)
177 {
178 matches.AppendString((*pos).c_str());
179 }
180 return matches.GetSize() - extant_entries;
181#else
182 // Resolving home directories is not supported, just copy the path...
183 return 0;
184#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
185}
186
187
188
189size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000190FileSpec::Resolve (const char *src_path, char *dst_path, size_t dst_len)
191{
192 if (src_path == NULL || src_path[0] == '\0')
193 return 0;
194
195 // Glob if needed for ~/, otherwise copy in case src_path is same as dst_path...
196 char unglobbed_path[PATH_MAX];
Greg Clayton45319462011-02-08 00:35:34 +0000197#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +0000198 if (src_path[0] == '~')
199 {
Greg Claytonc982c762010-07-09 20:39:50 +0000200 size_t return_count = ResolveUsername(src_path, unglobbed_path, sizeof(unglobbed_path));
Jim Inghamf818ca32010-07-01 01:48:53 +0000201
202 // If we couldn't find the user referred to, or the resultant path was too long,
203 // then just copy over the src_path.
204 if (return_count == 0 || return_count >= sizeof(unglobbed_path))
205 ::snprintf (unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
206 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207 else
Greg Clayton45319462011-02-08 00:35:34 +0000208#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Greg Claytonfd184262011-02-05 02:27:52 +0000209 {
210 ::snprintf(unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
211 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000212
213 // Now resolve the path if needed
214 char resolved_path[PATH_MAX];
215 if (::realpath (unglobbed_path, resolved_path))
216 {
217 // Success, copy the resolved path
218 return ::snprintf(dst_path, dst_len, "%s", resolved_path);
219 }
220 else
221 {
222 // Failed, just copy the unglobbed path
223 return ::snprintf(dst_path, dst_len, "%s", unglobbed_path);
224 }
225}
226
227FileSpec::FileSpec() :
228 m_directory(),
229 m_filename()
230{
231}
232
233//------------------------------------------------------------------
234// Default constructor that can take an optional full path to a
235// file on disk.
236//------------------------------------------------------------------
Jim Ingham0909e5f2010-09-16 00:57:33 +0000237FileSpec::FileSpec(const char *pathname, bool resolve_path) :
238 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000239 m_filename(),
240 m_is_resolved(false)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000241{
242 if (pathname && pathname[0])
243 SetFile(pathname, resolve_path);
244}
245
246//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000247// Copy constructor
248//------------------------------------------------------------------
249FileSpec::FileSpec(const FileSpec& rhs) :
250 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000251 m_filename (rhs.m_filename),
252 m_is_resolved (rhs.m_is_resolved)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253{
254}
255
256//------------------------------------------------------------------
257// Copy constructor
258//------------------------------------------------------------------
259FileSpec::FileSpec(const FileSpec* rhs) :
260 m_directory(),
261 m_filename()
262{
263 if (rhs)
264 *this = *rhs;
265}
266
267//------------------------------------------------------------------
268// Virtual destrcuctor in case anyone inherits from this class.
269//------------------------------------------------------------------
270FileSpec::~FileSpec()
271{
272}
273
274//------------------------------------------------------------------
275// Assignment operator.
276//------------------------------------------------------------------
277const FileSpec&
278FileSpec::operator= (const FileSpec& rhs)
279{
280 if (this != &rhs)
281 {
282 m_directory = rhs.m_directory;
283 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000284 m_is_resolved = rhs.m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000285 }
286 return *this;
287}
288
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289//------------------------------------------------------------------
290// Update the contents of this object with a new path. The path will
291// be split up into a directory and filename and stored as uniqued
292// string values for quick comparison and efficient memory usage.
293//------------------------------------------------------------------
294void
Greg Clayton7481c202010-11-08 00:28:40 +0000295FileSpec::SetFile (const char *pathname, bool resolve)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296{
297 m_filename.Clear();
298 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000299 m_is_resolved = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300 if (pathname == NULL || pathname[0] == '\0')
301 return;
302
303 char resolved_path[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000304 bool path_fit = true;
305
306 if (resolve)
307 {
308 path_fit = (FileSpec::Resolve (pathname, resolved_path, sizeof(resolved_path)) < sizeof(resolved_path) - 1);
Greg Clayton7481c202010-11-08 00:28:40 +0000309 m_is_resolved = path_fit;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000310 }
311 else
312 {
Greg Clayton7481c202010-11-08 00:28:40 +0000313 // Copy the path because "basename" and "dirname" want to muck with the
314 // path buffer
315 if (::strlen (pathname) > sizeof(resolved_path) - 1)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000316 path_fit = false;
317 else
Greg Clayton7481c202010-11-08 00:28:40 +0000318 ::strcpy (resolved_path, pathname);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000319 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320
Jim Ingham0909e5f2010-09-16 00:57:33 +0000321
322 if (path_fit)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323 {
324 char *filename = ::basename (resolved_path);
325 if (filename)
326 {
327 m_filename.SetCString (filename);
328 // Truncate the basename off the end of the resolved path
329
330 // Only attempt to get the dirname if it looks like we have a path
Virgile Bello1fd7ec72013-09-20 22:31:10 +0000331 if (strchr(resolved_path, '/')
332#ifdef _WIN32
333 || strchr(resolved_path, '\\')
334#endif
335 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000336 {
337 char *directory = ::dirname (resolved_path);
338
339 // Make sure we didn't get our directory resolved to "." without having
340 // specified
341 if (directory)
342 m_directory.SetCString(directory);
343 else
344 {
345 char *last_resolved_path_slash = strrchr(resolved_path, '/');
Virgile Bello1fd7ec72013-09-20 22:31:10 +0000346#ifdef _WIN32
347 char* last_resolved_path_slash_windows = strrchr(resolved_path, '\\');
348 if (last_resolved_path_slash_windows > last_resolved_path_slash)
349 last_resolved_path_slash = last_resolved_path_slash_windows;
350#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351 if (last_resolved_path_slash)
352 {
353 *last_resolved_path_slash = '\0';
354 m_directory.SetCString(resolved_path);
355 }
356 }
357 }
358 }
359 else
360 m_directory.SetCString(resolved_path);
361 }
362}
363
364//----------------------------------------------------------------------
365// Convert to pointer operator. This allows code to check any FileSpec
366// objects to see if they contain anything valid using code such as:
367//
368// if (file_spec)
369// {}
370//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000371FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000372{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000373 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374}
375
376//----------------------------------------------------------------------
377// Logical NOT operator. This allows code to check any FileSpec
378// objects to see if they are invalid using code such as:
379//
380// if (!file_spec)
381// {}
382//----------------------------------------------------------------------
383bool
384FileSpec::operator!() const
385{
386 return !m_directory && !m_filename;
387}
388
389//------------------------------------------------------------------
390// Equal to operator
391//------------------------------------------------------------------
392bool
393FileSpec::operator== (const FileSpec& rhs) const
394{
Greg Clayton7481c202010-11-08 00:28:40 +0000395 if (m_filename == rhs.m_filename)
396 {
397 if (m_directory == rhs.m_directory)
398 return true;
399
400 // TODO: determine if we want to keep this code in here.
401 // The code below was added to handle a case where we were
402 // trying to set a file and line breakpoint and one path
403 // was resolved, and the other not and the directory was
404 // in a mount point that resolved to a more complete path:
405 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
406 // this out...
407 if (IsResolved() && rhs.IsResolved())
408 {
409 // Both paths are resolved, no need to look further...
410 return false;
411 }
412
413 FileSpec resolved_lhs(*this);
414
415 // If "this" isn't resolved, resolve it
416 if (!IsResolved())
417 {
418 if (resolved_lhs.ResolvePath())
419 {
420 // This path wasn't resolved but now it is. Check if the resolved
421 // directory is the same as our unresolved directory, and if so,
422 // we can mark this object as resolved to avoid more future resolves
423 m_is_resolved = (m_directory == resolved_lhs.m_directory);
424 }
425 else
426 return false;
427 }
428
429 FileSpec resolved_rhs(rhs);
430 if (!rhs.IsResolved())
431 {
432 if (resolved_rhs.ResolvePath())
433 {
434 // rhs's path wasn't resolved but now it is. Check if the resolved
435 // directory is the same as rhs's unresolved directory, and if so,
436 // we can mark this object as resolved to avoid more future resolves
Jim Inghama537f6c2012-11-03 02:12:46 +0000437 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
Greg Clayton7481c202010-11-08 00:28:40 +0000438 }
439 else
440 return false;
441 }
442
443 // If we reach this point in the code we were able to resolve both paths
444 // and since we only resolve the paths if the basenames are equal, then
445 // we can just check if both directories are equal...
446 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
447 }
448 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449}
450
451//------------------------------------------------------------------
452// Not equal to operator
453//------------------------------------------------------------------
454bool
455FileSpec::operator!= (const FileSpec& rhs) const
456{
Greg Clayton7481c202010-11-08 00:28:40 +0000457 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458}
459
460//------------------------------------------------------------------
461// Less than operator
462//------------------------------------------------------------------
463bool
464FileSpec::operator< (const FileSpec& rhs) const
465{
466 return FileSpec::Compare(*this, rhs, true) < 0;
467}
468
469//------------------------------------------------------------------
470// Dump a FileSpec object to a stream
471//------------------------------------------------------------------
472Stream&
473lldb_private::operator << (Stream &s, const FileSpec& f)
474{
475 f.Dump(&s);
476 return s;
477}
478
479//------------------------------------------------------------------
480// Clear this object by releasing both the directory and filename
481// string values and making them both the empty string.
482//------------------------------------------------------------------
483void
484FileSpec::Clear()
485{
486 m_directory.Clear();
487 m_filename.Clear();
488}
489
490//------------------------------------------------------------------
491// Compare two FileSpec objects. If "full" is true, then both
492// the directory and the filename must match. If "full" is false,
493// then the directory names for "a" and "b" are only compared if
494// they are both non-empty. This allows a FileSpec object to only
495// contain a filename and it can match FileSpec objects that have
496// matching filenames with different paths.
497//
498// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
499// and "1" if "a" is greater than "b".
500//------------------------------------------------------------------
501int
502FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
503{
504 int result = 0;
505
506 // If full is true, then we must compare both the directory and filename.
507
508 // If full is false, then if either directory is empty, then we match on
509 // the basename only, and if both directories have valid values, we still
510 // do a full compare. This allows for matching when we just have a filename
511 // in one of the FileSpec objects.
512
513 if (full || (a.m_directory && b.m_directory))
514 {
515 result = ConstString::Compare(a.m_directory, b.m_directory);
516 if (result)
517 return result;
518 }
519 return ConstString::Compare (a.m_filename, b.m_filename);
520}
521
522bool
523FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full)
524{
Jim Ingham87df91b2011-09-23 00:54:11 +0000525 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526 return a.m_filename == b.m_filename;
Jim Ingham87df91b2011-09-23 00:54:11 +0000527 else
528 return a == b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529}
530
531
532
533//------------------------------------------------------------------
534// Dump the object to the supplied stream. If the object contains
535// a valid directory name, it will be displayed followed by a
536// directory delimiter, and the filename.
537//------------------------------------------------------------------
538void
539FileSpec::Dump(Stream *s) const
540{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000541 static ConstString g_slash_only ("/");
Enrico Granata80fcdd42012-11-03 00:09:46 +0000542 if (s)
543 {
544 m_directory.Dump(s);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000545 if (m_directory && m_directory != g_slash_only)
Enrico Granata80fcdd42012-11-03 00:09:46 +0000546 s->PutChar('/');
547 m_filename.Dump(s);
548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549}
550
551//------------------------------------------------------------------
552// Returns true if the file exists.
553//------------------------------------------------------------------
554bool
555FileSpec::Exists () const
556{
557 struct stat file_stats;
558 return GetFileStats (this, &file_stats);
559}
560
Caroline Tice428a9a52010-09-10 04:48:55 +0000561bool
562FileSpec::ResolveExecutableLocation ()
563{
Greg Clayton274060b2010-10-20 20:54:39 +0000564 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000565 {
Greg Clayton58f41712011-01-25 21:32:01 +0000566 const char *file_cstr = m_filename.GetCString();
567 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000568 {
Greg Clayton58f41712011-01-25 21:32:01 +0000569 const std::string file_str (file_cstr);
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000570 std::string path = llvm::sys::FindProgramByName (file_str);
571 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton58f41712011-01-25 21:32:01 +0000572 //llvm::StringRef dir_ref = path.getDirname();
573 if (! dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000574 {
Greg Clayton58f41712011-01-25 21:32:01 +0000575 // FindProgramByName returns "." if it can't find the file.
576 if (strcmp (".", dir_ref.data()) == 0)
577 return false;
578
579 m_directory.SetCString (dir_ref.data());
580 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000581 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000582 else
583 {
584 // If FindProgramByName found the file, it returns the directory + filename in its return results.
585 // We need to separate them.
586 FileSpec tmp_file (dir_ref.data(), false);
587 if (tmp_file.Exists())
588 {
589 m_directory = tmp_file.m_directory;
590 return true;
591 }
Caroline Tice391a9602010-09-12 00:10:52 +0000592 }
593 }
594 }
595 }
596
597 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000598}
599
Jim Ingham0909e5f2010-09-16 00:57:33 +0000600bool
601FileSpec::ResolvePath ()
602{
Greg Clayton7481c202010-11-08 00:28:40 +0000603 if (m_is_resolved)
604 return true; // We have already resolved this path
605
606 char path_buf[PATH_MAX];
Jim Ingham0909e5f2010-09-16 00:57:33 +0000607 if (!GetPath (path_buf, PATH_MAX))
608 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000609 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000610 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000611 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000612}
613
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000614uint64_t
615FileSpec::GetByteSize() const
616{
617 struct stat file_stats;
618 if (GetFileStats (this, &file_stats))
619 return file_stats.st_size;
620 return 0;
621}
622
623FileSpec::FileType
624FileSpec::GetFileType () const
625{
626 struct stat file_stats;
627 if (GetFileStats (this, &file_stats))
628 {
629 mode_t file_type = file_stats.st_mode & S_IFMT;
630 switch (file_type)
631 {
632 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000634#ifndef _WIN32
635 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636 case S_IFSOCK: return eFileTypeSocket;
637 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000638#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 default:
640 break;
641 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000642 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643 }
644 return eFileTypeInvalid;
645}
646
647TimeValue
648FileSpec::GetModificationTime () const
649{
650 TimeValue mod_time;
651 struct stat file_stats;
652 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000653 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654 return mod_time;
655}
656
657//------------------------------------------------------------------
658// Directory string get accessor.
659//------------------------------------------------------------------
660ConstString &
661FileSpec::GetDirectory()
662{
663 return m_directory;
664}
665
666//------------------------------------------------------------------
667// Directory string const get accessor.
668//------------------------------------------------------------------
669const ConstString &
670FileSpec::GetDirectory() const
671{
672 return m_directory;
673}
674
675//------------------------------------------------------------------
676// Filename string get accessor.
677//------------------------------------------------------------------
678ConstString &
679FileSpec::GetFilename()
680{
681 return m_filename;
682}
683
684//------------------------------------------------------------------
685// Filename string const get accessor.
686//------------------------------------------------------------------
687const ConstString &
688FileSpec::GetFilename() const
689{
690 return m_filename;
691}
692
693//------------------------------------------------------------------
694// Extract the directory and path into a fixed buffer. This is
695// needed as the directory and path are stored in separate string
696// values.
697//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000698size_t
699FileSpec::GetPath(char *path, size_t path_max_len) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000700{
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000701 if (path_max_len)
Greg Claytondd36def2010-10-17 22:03:32 +0000702 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000703 const char *dirname = m_directory.GetCString();
704 const char *filename = m_filename.GetCString();
Greg Claytondd36def2010-10-17 22:03:32 +0000705 if (dirname)
706 {
707 if (filename)
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000708 return ::snprintf (path, path_max_len, "%s/%s", dirname, filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000709 else
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000710 return ::snprintf (path, path_max_len, "%s", dirname);
Greg Claytondd36def2010-10-17 22:03:32 +0000711 }
712 else if (filename)
713 {
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000714 return ::snprintf (path, path_max_len, "%s", filename);
Greg Claytondd36def2010-10-17 22:03:32 +0000715 }
716 }
Enrico Granataa9dbf432011-10-17 21:45:27 +0000717 if (path)
718 path[0] = '\0';
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000719 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720}
721
Greg Claytona44c1e62013-04-29 16:36:27 +0000722std::string
723FileSpec::GetPath (void) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000724{
Jason Molendadb7d11c2013-05-06 10:21:11 +0000725 static ConstString g_slash_only ("/");
Greg Claytona44c1e62013-04-29 16:36:27 +0000726 std::string path;
Jason Molendaa7ae4672013-04-29 09:46:43 +0000727 const char *dirname = m_directory.GetCString();
728 const char *filename = m_filename.GetCString();
Jason Molendaa7ae4672013-04-29 09:46:43 +0000729 if (dirname)
730 {
731 path.append (dirname);
Jason Molendadb7d11c2013-05-06 10:21:11 +0000732 if (filename && m_directory != g_slash_only)
Jason Molendaa7ae4672013-04-29 09:46:43 +0000733 path.append ("/");
734 }
735 if (filename)
Jason Molendaa7ae4672013-04-29 09:46:43 +0000736 path.append (filename);
Jason Molendaa7ae4672013-04-29 09:46:43 +0000737 return path;
738}
739
Enrico Granataa9dbf432011-10-17 21:45:27 +0000740ConstString
741FileSpec::GetFileNameExtension () const
742{
Greg Clayton1f746072012-08-29 21:13:06 +0000743 if (m_filename)
744 {
745 const char *filename = m_filename.GetCString();
746 const char* dot_pos = strrchr(filename, '.');
747 if (dot_pos && dot_pos[1] != '\0')
748 return ConstString(dot_pos+1);
749 }
750 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +0000751}
752
753ConstString
754FileSpec::GetFileNameStrippingExtension () const
755{
756 const char *filename = m_filename.GetCString();
757 if (filename == NULL)
758 return ConstString();
759
Johnny Chenf5df5372011-10-18 19:28:30 +0000760 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +0000761 if (dot_pos == NULL)
762 return m_filename;
763
764 return ConstString(filename, dot_pos-filename);
765}
766
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767//------------------------------------------------------------------
768// Returns a shared pointer to a data buffer that contains all or
769// part of the contents of a file. The data is memory mapped and
770// will lazily page in data from the file as memory is accessed.
771// The data that is mappped will start "file_offset" bytes into the
772// file, and "file_size" bytes will be mapped. If "file_size" is
773// greater than the number of bytes available in the file starting
774// at "file_offset", the number of bytes will be appropriately
775// truncated. The final number of bytes that get mapped can be
776// verified using the DataBuffer::GetByteSize() function.
777//------------------------------------------------------------------
778DataBufferSP
779FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
780{
781 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +0000782 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 if (mmap_data.get())
784 {
Greg Claytond398a1c2013-04-20 00:23:26 +0000785 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
786 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787 data_sp.reset(mmap_data.release());
788 }
789 return data_sp;
790}
791
792
793//------------------------------------------------------------------
794// Return the size in bytes that this object takes in memory. This
795// returns the size in bytes of this object, not any shared string
796// values it may refer to.
797//------------------------------------------------------------------
798size_t
799FileSpec::MemorySize() const
800{
801 return m_filename.MemorySize() + m_directory.MemorySize();
802}
803
Greg Claytondda4f7b2010-06-30 23:03:03 +0000804
805size_t
Greg Clayton4017fa32012-01-06 02:01:06 +0000806FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807{
Greg Clayton4017fa32012-01-06 02:01:06 +0000808 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000809 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 char resolved_path[PATH_MAX];
811 if (GetPath(resolved_path, sizeof(resolved_path)))
812 {
Greg Clayton96c09682012-01-04 22:56:43 +0000813 File file;
814 error = file.Open(resolved_path, File::eOpenOptionRead);
815 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 {
Greg Clayton96c09682012-01-04 22:56:43 +0000817 off_t file_offset_after_seek = file_offset;
818 bytes_read = dst_len;
819 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000820 }
Greg Claytondda4f7b2010-06-30 23:03:03 +0000821 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000822 else
823 {
824 error.SetErrorString("invalid file specification");
825 }
826 if (error_ptr)
827 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000828 return bytes_read;
829}
830
831//------------------------------------------------------------------
832// Returns a shared pointer to a data buffer that contains all or
833// part of the contents of a file. The data copies into a heap based
834// buffer that lives in the DataBuffer shared pointer object returned.
835// The data that is cached will start "file_offset" bytes into the
836// file, and "file_size" bytes will be mapped. If "file_size" is
837// greater than the number of bytes available in the file starting
838// at "file_offset", the number of bytes will be appropriately
839// truncated. The final number of bytes that get mapped can be
840// verified using the DataBuffer::GetByteSize() function.
841//------------------------------------------------------------------
842DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +0000843FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +0000844{
Greg Clayton4017fa32012-01-06 02:01:06 +0000845 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000846 DataBufferSP data_sp;
847 char resolved_path[PATH_MAX];
848 if (GetPath(resolved_path, sizeof(resolved_path)))
849 {
Greg Clayton96c09682012-01-04 22:56:43 +0000850 File file;
851 error = file.Open(resolved_path, File::eOpenOptionRead);
852 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +0000853 {
854 const bool null_terminate = false;
855 error = file.Read (file_size, file_offset, null_terminate, data_sp);
856 }
857 }
858 else
859 {
860 error.SetErrorString("invalid file specification");
861 }
862 if (error_ptr)
863 *error_ptr = error;
864 return data_sp;
865}
866
867DataBufferSP
868FileSpec::ReadFileContentsAsCString(Error *error_ptr)
869{
870 Error error;
871 DataBufferSP data_sp;
872 char resolved_path[PATH_MAX];
873 if (GetPath(resolved_path, sizeof(resolved_path)))
874 {
875 File file;
876 error = file.Open(resolved_path, File::eOpenOptionRead);
877 if (error.Success())
878 {
879 off_t offset = 0;
880 size_t length = SIZE_MAX;
881 const bool null_terminate = true;
882 error = file.Read (length, offset, null_terminate, data_sp);
883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 }
Greg Clayton4017fa32012-01-06 02:01:06 +0000885 else
886 {
887 error.SetErrorString("invalid file specification");
888 }
889 if (error_ptr)
890 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 return data_sp;
892}
893
Greg Clayton58fc50e2010-10-20 22:52:05 +0000894size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895FileSpec::ReadFileLines (STLStringArray &lines)
896{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +0000898 char path[PATH_MAX];
899 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 {
Greg Claytone01e07b2013-04-18 18:10:51 +0000901 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000902
Greg Clayton58fc50e2010-10-20 22:52:05 +0000903 if (file_stream)
904 {
905 std::string line;
906 while (getline (file_stream, line))
907 lines.push_back (line);
908 }
909 }
910 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000911}
Greg Clayton4272cc72011-02-02 02:24:04 +0000912
913FileSpec::EnumerateDirectoryResult
914FileSpec::EnumerateDirectory
915(
916 const char *dir_path,
917 bool find_directories,
918 bool find_files,
919 bool find_other,
920 EnumerateDirectoryCallbackType callback,
921 void *callback_baton
922)
923{
924 if (dir_path && dir_path[0])
925 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000926#if _WIN32
927 char szDir[MAX_PATH];
928 strcpy_s(szDir, MAX_PATH, dir_path);
929 strcat_s(szDir, MAX_PATH, "\\*");
930
931 WIN32_FIND_DATA ffd;
932 HANDLE hFind = FindFirstFile(szDir, &ffd);
933
934 if (hFind == INVALID_HANDLE_VALUE)
935 {
936 return eEnumerateDirectoryResultNext;
937 }
938
939 do
940 {
941 bool call_callback = false;
942 FileSpec::FileType file_type = eFileTypeUnknown;
943 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
944 {
945 size_t len = strlen(ffd.cFileName);
946
947 if (len == 1 && ffd.cFileName[0] == '.')
948 continue;
949
950 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
951 continue;
952
953 file_type = eFileTypeDirectory;
954 call_callback = find_directories;
955 }
956 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
957 {
958 file_type = eFileTypeOther;
959 call_callback = find_other;
960 }
961 else
962 {
963 file_type = eFileTypeRegular;
964 call_callback = find_files;
965 }
966 if (call_callback)
967 {
968 char child_path[MAX_PATH];
969 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
970 if (child_path_len < (int)(sizeof(child_path) - 1))
971 {
972 // Don't resolve the file type or path
973 FileSpec child_path_spec (child_path, false);
974
975 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
976
977 switch (result)
978 {
979 case eEnumerateDirectoryResultNext:
980 // Enumerate next entry in the current directory. We just
981 // exit this switch and will continue enumerating the
982 // current directory as we currently are...
983 break;
984
985 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
986 if (FileSpec::EnumerateDirectory(child_path,
987 find_directories,
988 find_files,
989 find_other,
990 callback,
991 callback_baton) == eEnumerateDirectoryResultQuit)
992 {
993 // The subdirectory returned Quit, which means to
994 // stop all directory enumerations at all levels.
995 return eEnumerateDirectoryResultQuit;
996 }
997 break;
998
999 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1000 // Exit from this directory level and tell parent to
1001 // keep enumerating.
1002 return eEnumerateDirectoryResultNext;
1003
1004 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1005 return eEnumerateDirectoryResultQuit;
1006 }
1007 }
1008 }
1009 } while (FindNextFile(hFind, &ffd) != 0);
1010
1011 FindClose(hFind);
1012#else
1013 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
Greg Clayton4272cc72011-02-02 02:24:04 +00001014 if (dir_path_dir.is_valid())
1015 {
Jason Molenda14aef122013-04-04 03:19:27 +00001016 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1017#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1018 if (path_max < __DARWIN_MAXPATHLEN)
1019 path_max = __DARWIN_MAXPATHLEN;
1020#endif
1021 struct dirent *buf, *dp;
1022 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1023
1024 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
Greg Clayton4272cc72011-02-02 02:24:04 +00001025 {
1026 // Only search directories
1027 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1028 {
Greg Claytone0f3c022011-02-07 17:41:11 +00001029 size_t len = strlen(dp->d_name);
1030
1031 if (len == 1 && dp->d_name[0] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001032 continue;
1033
Greg Claytone0f3c022011-02-07 17:41:11 +00001034 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
Greg Clayton4272cc72011-02-02 02:24:04 +00001035 continue;
1036 }
1037
1038 bool call_callback = false;
1039 FileSpec::FileType file_type = eFileTypeUnknown;
1040
1041 switch (dp->d_type)
1042 {
1043 default:
1044 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break;
1045 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break;
1046 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break;
1047 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break;
1048 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break;
1049 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break;
1050 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break;
1051 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001052#if !defined(__OpenBSD__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001053 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break;
Greg Clayton2b4d9b72011-04-01 18:18:34 +00001054#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001055 }
1056
1057 if (call_callback)
1058 {
1059 char child_path[PATH_MAX];
1060 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 +00001061 if (child_path_len < (int)(sizeof(child_path) - 1))
Greg Clayton4272cc72011-02-02 02:24:04 +00001062 {
1063 // Don't resolve the file type or path
1064 FileSpec child_path_spec (child_path, false);
1065
1066 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1067
1068 switch (result)
1069 {
Greg Clayton4272cc72011-02-02 02:24:04 +00001070 case eEnumerateDirectoryResultNext:
1071 // Enumerate next entry in the current directory. We just
1072 // exit this switch and will continue enumerating the
1073 // current directory as we currently are...
1074 break;
1075
1076 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1077 if (FileSpec::EnumerateDirectory (child_path,
1078 find_directories,
1079 find_files,
1080 find_other,
1081 callback,
1082 callback_baton) == eEnumerateDirectoryResultQuit)
1083 {
1084 // The subdirectory returned Quit, which means to
1085 // stop all directory enumerations at all levels.
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001086 if (buf)
1087 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001088 return eEnumerateDirectoryResultQuit;
1089 }
1090 break;
1091
1092 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1093 // Exit from this directory level and tell parent to
1094 // keep enumerating.
Jason Molendafe806902013-05-04 00:39:52 +00001095 if (buf)
1096 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001097 return eEnumerateDirectoryResultNext;
1098
1099 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
Jason Molendafe806902013-05-04 00:39:52 +00001100 if (buf)
1101 free (buf);
Greg Clayton4272cc72011-02-02 02:24:04 +00001102 return eEnumerateDirectoryResultQuit;
1103 }
1104 }
1105 }
1106 }
Jason Molenda14aef122013-04-04 03:19:27 +00001107 if (buf)
1108 {
1109 free (buf);
1110 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001111 }
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001112#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001113 }
1114 // By default when exiting a directory, we tell the parent enumeration
1115 // to continue enumerating.
1116 return eEnumerateDirectoryResultNext;
1117}
1118
Daniel Maleae0f8f572013-08-26 23:57:52 +00001119FileSpec
1120FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1121{
1122 const bool resolve = false;
1123 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1124 return FileSpec(new_path,resolve);
1125 StreamString stream;
1126 if (m_filename.IsEmpty())
1127 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1128 else if (m_directory.IsEmpty())
1129 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1130 else
1131 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1132 return FileSpec(stream.GetData(),resolve);
1133}
1134
1135FileSpec
1136FileSpec::CopyByRemovingLastPathComponent () const
1137{
1138 const bool resolve = false;
1139 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1140 return FileSpec("",resolve);
1141 if (m_directory.IsEmpty())
1142 return FileSpec("",resolve);
1143 if (m_filename.IsEmpty())
1144 {
1145 const char* dir_cstr = m_directory.GetCString();
1146 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1147
1148 // check for obvious cases before doing the full thing
1149 if (!last_slash_ptr)
1150 return FileSpec("",resolve);
1151 if (last_slash_ptr == dir_cstr)
1152 return FileSpec("/",resolve);
1153
1154 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1155 ConstString new_path(dir_cstr,last_slash_pos);
1156 return FileSpec(new_path.GetCString(),resolve);
1157 }
1158 else
1159 return FileSpec(m_directory.GetCString(),resolve);
1160}
1161
1162const char*
1163FileSpec::GetLastPathComponent () const
1164{
1165 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1166 return NULL;
1167 if (m_filename.IsEmpty())
1168 {
1169 const char* dir_cstr = m_directory.GetCString();
1170 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1171 if (last_slash_ptr == NULL)
1172 return m_directory.GetCString();
1173 if (last_slash_ptr == dir_cstr)
1174 {
1175 if (last_slash_ptr[1] == 0)
1176 return last_slash_ptr;
1177 else
1178 return last_slash_ptr+1;
1179 }
1180 if (last_slash_ptr[1] != 0)
1181 return last_slash_ptr+1;
1182 const char* penultimate_slash_ptr = last_slash_ptr;
1183 while (*penultimate_slash_ptr)
1184 {
1185 --penultimate_slash_ptr;
1186 if (penultimate_slash_ptr == dir_cstr)
1187 break;
1188 if (*penultimate_slash_ptr == '/')
1189 break;
1190 }
1191 ConstString new_path(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1192 return new_path.AsCString();
1193 }
1194 return m_filename.GetCString();
1195}
1196
1197void
1198FileSpec::AppendPathComponent (const char *new_path)
1199{
1200 const bool resolve = false;
1201 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1202 {
1203 SetFile(new_path,resolve);
1204 return;
1205 }
1206 StreamString stream;
1207 if (m_filename.IsEmpty())
1208 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1209 else if (m_directory.IsEmpty())
1210 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1211 else
1212 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1213 SetFile(stream.GetData(), resolve);
1214}
1215
1216void
1217FileSpec::RemoveLastPathComponent ()
1218{
1219 const bool resolve = false;
1220 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1221 {
1222 SetFile("",resolve);
1223 return;
1224 }
1225 if (m_directory.IsEmpty())
1226 {
1227 SetFile("",resolve);
1228 return;
1229 }
1230 if (m_filename.IsEmpty())
1231 {
1232 const char* dir_cstr = m_directory.GetCString();
1233 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1234
1235 // check for obvious cases before doing the full thing
1236 if (!last_slash_ptr)
1237 {
1238 SetFile("",resolve);
1239 return;
1240 }
1241 if (last_slash_ptr == dir_cstr)
1242 {
1243 SetFile("/",resolve);
1244 return;
1245 }
1246 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1247 ConstString new_path(dir_cstr,last_slash_pos);
1248 SetFile(new_path.GetCString(),resolve);
1249 }
1250 else
1251 SetFile(m_directory.GetCString(),resolve);
1252}
Greg Clayton1f746072012-08-29 21:13:06 +00001253//------------------------------------------------------------------
1254/// Returns true if the filespec represents an implementation source
1255/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1256/// extension).
1257///
1258/// @return
1259/// \b true if the filespec represents an implementation source
1260/// file, \b false otherwise.
1261//------------------------------------------------------------------
1262bool
1263FileSpec::IsSourceImplementationFile () const
1264{
1265 ConstString extension (GetFileNameExtension());
1266 if (extension)
1267 {
1268 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)$",
1269 REG_EXTENDED | REG_ICASE);
1270 return g_source_file_regex.Execute (extension.GetCString());
1271 }
1272 return false;
1273}
1274
Greg Claytona0ca6602012-10-18 16:33:33 +00001275bool
1276FileSpec::IsRelativeToCurrentWorkingDirectory () const
1277{
1278 const char *directory = m_directory.GetCString();
1279 if (directory && directory[0])
1280 {
1281 // If the path doesn't start with '/' or '~', return true
1282 switch (directory[0])
1283 {
1284 case '/':
1285 case '~':
1286 return false;
1287 default:
1288 return true;
1289 }
1290 }
1291 else if (m_filename)
1292 {
1293 // No directory, just a basename, return true
1294 return true;
1295 }
1296 return false;
1297}