1 //===-- 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
11 #ifndef _WIN32
12 #include <dirent.h>
13 #else
14 #include "lldb/Host/windows/windows.h"
15 #endif
16 #include <fcntl.h>
17 #ifndef _MSC_VER
18 #include <libgen.h>
19 #endif
20 #include <sys/stat.h>
21 #include <set>
22 #include <string.h>
23 #include <fstream>
24
25 #include "lldb/Host/Config.h" // Have to include this before we test the define...
26 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
27 #include <pwd.h>
28 #endif
29
30 #include "lldb/Core/ArchSpec.h"
31 #include "lldb/Core/DataBufferHeap.h"
32 #include "lldb/Core/DataBufferMemoryMap.h"
33 #include "lldb/Core/RegularExpression.h"
34 #include "lldb/Core/StreamString.h"
35 #include "lldb/Core/Stream.h"
36 #include "lldb/Host/File.h"
37 #include "lldb/Host/FileSpec.h"
38 #include "lldb/Host/FileSystem.h"
39 #include "lldb/Host/Host.h"
40 #include "lldb/Utility/CleanUp.h"
41
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Program.h"
46
47 using namespace lldb;
48 using namespace lldb_private;
49
50 namespace {
51
52 bool
PathSyntaxIsPosix(FileSpec::PathSyntax syntax)53 PathSyntaxIsPosix(FileSpec::PathSyntax syntax)
54 {
55 return (syntax == FileSpec::ePathSyntaxPosix ||
56 (syntax == FileSpec::ePathSyntaxHostNative &&
57 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
58 }
59
60 char
GetPathSeparator(FileSpec::PathSyntax syntax)61 GetPathSeparator(FileSpec::PathSyntax syntax)
62 {
63 return PathSyntaxIsPosix(syntax) ? '/' : '\\';
64 }
65
66 void
Normalize(llvm::SmallVectorImpl<char> & path,FileSpec::PathSyntax syntax)67 Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
68 {
69 if (PathSyntaxIsPosix(syntax)) return;
70
71 std::replace(path.begin(), path.end(), '\\', '/');
72 // Windows path can have \\ slashes which can be changed by replace
73 // call above to //. Here we remove the duplicate.
74 auto iter = std::unique ( path.begin(), path.end(),
75 []( char &c1, char &c2 ){
76 return (c1 == '/' && c2 == '/');});
77 path.erase(iter, path.end());
78 }
79
80 void
Denormalize(llvm::SmallVectorImpl<char> & path,FileSpec::PathSyntax syntax)81 Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
82 {
83 if (PathSyntaxIsPosix(syntax)) return;
84
85 std::replace(path.begin(), path.end(), '/', '\\');
86 }
87
88 bool
GetFileStats(const FileSpec * file_spec,struct stat * stats_ptr)89 GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
90 {
91 char resolved_path[PATH_MAX];
92 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
93 return ::stat (resolved_path, stats_ptr) == 0;
94 return false;
95 }
96
97 }
98
99 // Resolves the username part of a path of the form ~user/other/directories, and
100 // writes the result into dst_path. This will also resolve "~" to the current user.
101 // If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
102 void
ResolveUsername(llvm::SmallVectorImpl<char> & path)103 FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
104 {
105 #if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
106 if (path.empty() || path[0] != '~')
107 return;
108
109 llvm::StringRef path_str(path.data(), path.size());
110 size_t slash_pos = path_str.find_first_of("/", 1);
111 if (slash_pos == 1 || path.size() == 1)
112 {
113 // A path of ~/ resolves to the current user's home dir
114 llvm::SmallString<64> home_dir;
115 if (!llvm::sys::path::home_directory(home_dir))
116 return;
117
118 // Overwrite the ~ with the first character of the homedir, and insert
119 // the rest. This way we only trigger one move, whereas an insert
120 // followed by a delete (or vice versa) would trigger two.
121 path[0] = home_dir[0];
122 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
123 return;
124 }
125
126 auto username_begin = path.begin()+1;
127 auto username_end = (slash_pos == llvm::StringRef::npos)
128 ? path.end()
129 : (path.begin() + slash_pos);
130 size_t replacement_length = std::distance(path.begin(), username_end);
131
132 llvm::SmallString<20> username(username_begin, username_end);
133 struct passwd *user_entry = ::getpwnam(username.c_str());
134 if (user_entry != nullptr)
135 {
136 // Copy over the first n characters of the path, where n is the smaller of the length
137 // of the home directory and the slash pos.
138 llvm::StringRef homedir(user_entry->pw_dir);
139 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
140 auto src_begin = homedir.begin();
141 auto src_end = src_begin + initial_copy_length;
142 std::copy(src_begin, src_end, path.begin());
143 if (replacement_length > homedir.size())
144 {
145 // We copied the entire home directory, but the ~username portion of the path was
146 // longer, so there's characters that need to be removed.
147 path.erase(path.begin() + initial_copy_length, username_end);
148 }
149 else if (replacement_length < homedir.size())
150 {
151 // We copied all the way up to the slash in the destination, but there's still more
152 // characters that need to be inserted.
153 path.insert(username_end, src_end, homedir.end());
154 }
155 }
156 else
157 {
158 // Unable to resolve username (user doesn't exist?)
159 path.clear();
160 }
161 #endif
162 }
163
164 size_t
ResolvePartialUsername(const char * partial_name,StringList & matches)165 FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
166 {
167 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
168 size_t extant_entries = matches.GetSize();
169
170 setpwent();
171 struct passwd *user_entry;
172 const char *name_start = partial_name + 1;
173 std::set<std::string> name_list;
174
175 while ((user_entry = getpwent()) != NULL)
176 {
177 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
178 {
179 std::string tmp_buf("~");
180 tmp_buf.append(user_entry->pw_name);
181 tmp_buf.push_back('/');
182 name_list.insert(tmp_buf);
183 }
184 }
185 std::set<std::string>::iterator pos, end = name_list.end();
186 for (pos = name_list.begin(); pos != end; pos++)
187 {
188 matches.AppendString((*pos).c_str());
189 }
190 return matches.GetSize() - extant_entries;
191 #else
192 // Resolving home directories is not supported, just copy the path...
193 return 0;
194 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
195 }
196
197 void
Resolve(llvm::SmallVectorImpl<char> & path)198 FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
199 {
200 if (path.empty())
201 return;
202
203 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
204 if (path[0] == '~')
205 ResolveUsername(path);
206 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
207
208 // Save a copy of the original path that's passed in
209 llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end());
210
211 llvm::sys::fs::make_absolute(path);
212
213
214 path.push_back(0); // Be sure we have a nul terminated string
215 path.pop_back();
216 struct stat file_stats;
217 if (::stat (path.data(), &file_stats) != 0)
218 {
219 path.clear();
220 path.append(original_path.begin(), original_path.end());
221 }
222 }
223
FileSpec()224 FileSpec::FileSpec() :
225 m_directory(),
226 m_filename(),
227 m_syntax(FileSystem::GetNativePathSyntax())
228 {
229 }
230
231 //------------------------------------------------------------------
232 // Default constructor that can take an optional full path to a
233 // file on disk.
234 //------------------------------------------------------------------
FileSpec(const char * pathname,bool resolve_path,PathSyntax syntax)235 FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
236 m_directory(),
237 m_filename(),
238 m_is_resolved(false),
239 m_syntax(syntax)
240 {
241 if (pathname && pathname[0])
242 SetFile(pathname, resolve_path, syntax);
243 }
244
FileSpec(const char * pathname,bool resolve_path,ArchSpec arch)245 FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
246 FileSpec{pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix}
247 {
248 }
249
FileSpec(const std::string & path,bool resolve_path,PathSyntax syntax)250 FileSpec::FileSpec(const std::string &path, bool resolve_path, PathSyntax syntax) :
251 FileSpec{path.c_str(), resolve_path, syntax}
252 {
253 }
254
FileSpec(const std::string & path,bool resolve_path,ArchSpec arch)255 FileSpec::FileSpec(const std::string &path, bool resolve_path, ArchSpec arch) :
256 FileSpec{path.c_str(), resolve_path, arch}
257 {
258 }
259
260 //------------------------------------------------------------------
261 // Copy constructor
262 //------------------------------------------------------------------
FileSpec(const FileSpec & rhs)263 FileSpec::FileSpec(const FileSpec& rhs) :
264 m_directory (rhs.m_directory),
265 m_filename (rhs.m_filename),
266 m_is_resolved (rhs.m_is_resolved),
267 m_syntax (rhs.m_syntax)
268 {
269 }
270
271 //------------------------------------------------------------------
272 // Copy constructor
273 //------------------------------------------------------------------
FileSpec(const FileSpec * rhs)274 FileSpec::FileSpec(const FileSpec* rhs) :
275 m_directory(),
276 m_filename()
277 {
278 if (rhs)
279 *this = *rhs;
280 }
281
282 //------------------------------------------------------------------
283 // Virtual destructor in case anyone inherits from this class.
284 //------------------------------------------------------------------
~FileSpec()285 FileSpec::~FileSpec()
286 {
287 }
288
289 //------------------------------------------------------------------
290 // Assignment operator.
291 //------------------------------------------------------------------
292 const FileSpec&
operator =(const FileSpec & rhs)293 FileSpec::operator= (const FileSpec& rhs)
294 {
295 if (this != &rhs)
296 {
297 m_directory = rhs.m_directory;
298 m_filename = rhs.m_filename;
299 m_is_resolved = rhs.m_is_resolved;
300 m_syntax = rhs.m_syntax;
301 }
302 return *this;
303 }
304
305 //------------------------------------------------------------------
306 // Update the contents of this object with a new path. The path will
307 // be split up into a directory and filename and stored as uniqued
308 // string values for quick comparison and efficient memory usage.
309 //------------------------------------------------------------------
310 void
SetFile(const char * pathname,bool resolve,PathSyntax syntax)311 FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
312 {
313 m_filename.Clear();
314 m_directory.Clear();
315 m_is_resolved = false;
316 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
317
318 if (pathname == NULL || pathname[0] == '\0')
319 return;
320
321 llvm::SmallString<64> normalized(pathname);
322
323 if (resolve)
324 {
325 FileSpec::Resolve (normalized);
326 m_is_resolved = true;
327 }
328
329 // Only normalize after resolving the path. Resolution will modify the path
330 // string, potentially adding wrong kinds of slashes to the path, that need
331 // to be re-normalized.
332 Normalize(normalized, syntax);
333
334 llvm::StringRef resolve_path_ref(normalized.c_str());
335 llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref);
336 if (!filename_ref.empty())
337 {
338 m_filename.SetString (filename_ref);
339 llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref);
340 if (!directory_ref.empty())
341 m_directory.SetString(directory_ref);
342 }
343 else
344 m_directory.SetCString(normalized.c_str());
345 }
346
347 void
SetFile(const char * pathname,bool resolve,ArchSpec arch)348 FileSpec::SetFile(const char *pathname, bool resolve, ArchSpec arch)
349 {
350 return SetFile(pathname, resolve,
351 arch.GetTriple().isOSWindows()
352 ? ePathSyntaxWindows
353 : ePathSyntaxPosix);
354 }
355
356 void
SetFile(const std::string & pathname,bool resolve,PathSyntax syntax)357 FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
358 {
359 return SetFile(pathname.c_str(), resolve, syntax);
360 }
361
362 void
SetFile(const std::string & pathname,bool resolve,ArchSpec arch)363 FileSpec::SetFile(const std::string &pathname, bool resolve, ArchSpec arch)
364 {
365 return SetFile(pathname.c_str(), resolve, arch);
366 }
367
368 //----------------------------------------------------------------------
369 // Convert to pointer operator. This allows code to check any FileSpec
370 // objects to see if they contain anything valid using code such as:
371 //
372 // if (file_spec)
373 // {}
374 //----------------------------------------------------------------------
operator bool() const375 FileSpec::operator bool() const
376 {
377 return m_filename || m_directory;
378 }
379
380 //----------------------------------------------------------------------
381 // Logical NOT operator. This allows code to check any FileSpec
382 // objects to see if they are invalid using code such as:
383 //
384 // if (!file_spec)
385 // {}
386 //----------------------------------------------------------------------
387 bool
operator !() const388 FileSpec::operator!() const
389 {
390 return !m_directory && !m_filename;
391 }
392
393 //------------------------------------------------------------------
394 // Equal to operator
395 //------------------------------------------------------------------
396 bool
operator ==(const FileSpec & rhs) const397 FileSpec::operator== (const FileSpec& rhs) const
398 {
399 if (m_filename == rhs.m_filename)
400 {
401 if (m_directory == rhs.m_directory)
402 return true;
403
404 // TODO: determine if we want to keep this code in here.
405 // The code below was added to handle a case where we were
406 // trying to set a file and line breakpoint and one path
407 // was resolved, and the other not and the directory was
408 // in a mount point that resolved to a more complete path:
409 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
410 // this out...
411 if (IsResolved() && rhs.IsResolved())
412 {
413 // Both paths are resolved, no need to look further...
414 return false;
415 }
416
417 FileSpec resolved_lhs(*this);
418
419 // If "this" isn't resolved, resolve it
420 if (!IsResolved())
421 {
422 if (resolved_lhs.ResolvePath())
423 {
424 // This path wasn't resolved but now it is. Check if the resolved
425 // directory is the same as our unresolved directory, and if so,
426 // we can mark this object as resolved to avoid more future resolves
427 m_is_resolved = (m_directory == resolved_lhs.m_directory);
428 }
429 else
430 return false;
431 }
432
433 FileSpec resolved_rhs(rhs);
434 if (!rhs.IsResolved())
435 {
436 if (resolved_rhs.ResolvePath())
437 {
438 // rhs's path wasn't resolved but now it is. Check if the resolved
439 // directory is the same as rhs's unresolved directory, and if so,
440 // we can mark this object as resolved to avoid more future resolves
441 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
442 }
443 else
444 return false;
445 }
446
447 // If we reach this point in the code we were able to resolve both paths
448 // and since we only resolve the paths if the basenames are equal, then
449 // we can just check if both directories are equal...
450 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
451 }
452 return false;
453 }
454
455 //------------------------------------------------------------------
456 // Not equal to operator
457 //------------------------------------------------------------------
458 bool
operator !=(const FileSpec & rhs) const459 FileSpec::operator!= (const FileSpec& rhs) const
460 {
461 return !(*this == rhs);
462 }
463
464 //------------------------------------------------------------------
465 // Less than operator
466 //------------------------------------------------------------------
467 bool
operator <(const FileSpec & rhs) const468 FileSpec::operator< (const FileSpec& rhs) const
469 {
470 return FileSpec::Compare(*this, rhs, true) < 0;
471 }
472
473 //------------------------------------------------------------------
474 // Dump a FileSpec object to a stream
475 //------------------------------------------------------------------
476 Stream&
operator <<(Stream & s,const FileSpec & f)477 lldb_private::operator << (Stream &s, const FileSpec& f)
478 {
479 f.Dump(&s);
480 return s;
481 }
482
483 //------------------------------------------------------------------
484 // Clear this object by releasing both the directory and filename
485 // string values and making them both the empty string.
486 //------------------------------------------------------------------
487 void
Clear()488 FileSpec::Clear()
489 {
490 m_directory.Clear();
491 m_filename.Clear();
492 }
493
494 //------------------------------------------------------------------
495 // Compare two FileSpec objects. If "full" is true, then both
496 // the directory and the filename must match. If "full" is false,
497 // then the directory names for "a" and "b" are only compared if
498 // they are both non-empty. This allows a FileSpec object to only
499 // contain a filename and it can match FileSpec objects that have
500 // matching filenames with different paths.
501 //
502 // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
503 // and "1" if "a" is greater than "b".
504 //------------------------------------------------------------------
505 int
Compare(const FileSpec & a,const FileSpec & b,bool full)506 FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
507 {
508 int result = 0;
509
510 // If full is true, then we must compare both the directory and filename.
511
512 // If full is false, then if either directory is empty, then we match on
513 // the basename only, and if both directories have valid values, we still
514 // do a full compare. This allows for matching when we just have a filename
515 // in one of the FileSpec objects.
516
517 if (full || (a.m_directory && b.m_directory))
518 {
519 result = ConstString::Compare(a.m_directory, b.m_directory);
520 if (result)
521 return result;
522 }
523 return ConstString::Compare (a.m_filename, b.m_filename);
524 }
525
526 bool
Equal(const FileSpec & a,const FileSpec & b,bool full,bool remove_backups)527 FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
528 {
529 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
530 return a.m_filename == b.m_filename;
531 else if (remove_backups == false)
532 return a == b;
533 else
534 {
535 if (a.m_filename != b.m_filename)
536 return false;
537 if (a.m_directory == b.m_directory)
538 return true;
539 ConstString a_without_dots;
540 ConstString b_without_dots;
541
542 RemoveBackupDots (a.m_directory, a_without_dots);
543 RemoveBackupDots (b.m_directory, b_without_dots);
544 return a_without_dots == b_without_dots;
545 }
546 }
547
548 void
NormalizePath()549 FileSpec::NormalizePath ()
550 {
551 ConstString normalized_directory;
552 FileSpec::RemoveBackupDots(m_directory, normalized_directory);
553 m_directory = normalized_directory;
554 }
555
556 void
RemoveBackupDots(const ConstString & input_const_str,ConstString & result_const_str)557 FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
558 {
559 const char *input = input_const_str.GetCString();
560 result_const_str.Clear();
561 if (!input || input[0] == '\0')
562 return;
563
564 const char win_sep = '\\';
565 const char unix_sep = '/';
566 char found_sep;
567 const char *win_backup = "\\..";
568 const char *unix_backup = "/..";
569
570 bool is_win = false;
571
572 // Determine the platform for the path (win or unix):
573
574 if (input[0] == win_sep)
575 is_win = true;
576 else if (input[0] == unix_sep)
577 is_win = false;
578 else if (input[1] == ':')
579 is_win = true;
580 else if (strchr(input, unix_sep) != nullptr)
581 is_win = false;
582 else if (strchr(input, win_sep) != nullptr)
583 is_win = true;
584 else
585 {
586 // No separators at all, no reason to do any work here.
587 result_const_str = input_const_str;
588 return;
589 }
590
591 llvm::StringRef backup_sep;
592 if (is_win)
593 {
594 found_sep = win_sep;
595 backup_sep = win_backup;
596 }
597 else
598 {
599 found_sep = unix_sep;
600 backup_sep = unix_backup;
601 }
602
603 llvm::StringRef input_ref(input);
604 llvm::StringRef curpos(input);
605
606 bool had_dots = false;
607 std::string result;
608
609 while (1)
610 {
611 // Start of loop
612 llvm::StringRef before_sep;
613 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
614
615 before_sep = around_sep.first;
616 curpos = around_sep.second;
617
618 if (curpos.empty())
619 {
620 if (had_dots)
621 {
622 while (before_sep.startswith("//"))
623 before_sep = before_sep.substr(1);
624 if (!before_sep.empty())
625 {
626 result.append(before_sep.data(), before_sep.size());
627 }
628 }
629 break;
630 }
631 had_dots = true;
632
633 unsigned num_backups = 1;
634 while (curpos.startswith(backup_sep))
635 {
636 num_backups++;
637 curpos = curpos.slice(backup_sep.size(), curpos.size());
638 }
639
640 size_t end_pos = before_sep.size();
641 while (num_backups-- > 0)
642 {
643 end_pos = before_sep.rfind(found_sep, end_pos);
644 if (end_pos == llvm::StringRef::npos)
645 {
646 result_const_str = input_const_str;
647 return;
648 }
649 }
650 result.append(before_sep.data(), end_pos);
651 }
652
653 if (had_dots)
654 result_const_str.SetCString(result.c_str());
655 else
656 result_const_str = input_const_str;
657
658 return;
659 }
660
661 //------------------------------------------------------------------
662 // Dump the object to the supplied stream. If the object contains
663 // a valid directory name, it will be displayed followed by a
664 // directory delimiter, and the filename.
665 //------------------------------------------------------------------
666 void
Dump(Stream * s) const667 FileSpec::Dump(Stream *s) const
668 {
669 if (s)
670 {
671 std::string path{GetPath(true)};
672 s->PutCString(path.c_str());
673 char path_separator = GetPathSeparator(m_syntax);
674 if (!m_filename && !path.empty() && path.back() != path_separator)
675 s->PutChar(path_separator);
676 }
677 }
678
679 //------------------------------------------------------------------
680 // Returns true if the file exists.
681 //------------------------------------------------------------------
682 bool
Exists() const683 FileSpec::Exists () const
684 {
685 struct stat file_stats;
686 return GetFileStats (this, &file_stats);
687 }
688
689 bool
Readable() const690 FileSpec::Readable () const
691 {
692 const uint32_t permissions = GetPermissions();
693 if (permissions & eFilePermissionsEveryoneR)
694 return true;
695 return false;
696 }
697
698 bool
ResolveExecutableLocation()699 FileSpec::ResolveExecutableLocation ()
700 {
701 if (!m_directory)
702 {
703 const char *file_cstr = m_filename.GetCString();
704 if (file_cstr)
705 {
706 const std::string file_str (file_cstr);
707 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
708 if (!error_or_path)
709 return false;
710 std::string path = error_or_path.get();
711 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
712 if (!dir_ref.empty())
713 {
714 // FindProgramByName returns "." if it can't find the file.
715 if (strcmp (".", dir_ref.data()) == 0)
716 return false;
717
718 m_directory.SetCString (dir_ref.data());
719 if (Exists())
720 return true;
721 else
722 {
723 // If FindProgramByName found the file, it returns the directory + filename in its return results.
724 // We need to separate them.
725 FileSpec tmp_file (dir_ref.data(), false);
726 if (tmp_file.Exists())
727 {
728 m_directory = tmp_file.m_directory;
729 return true;
730 }
731 }
732 }
733 }
734 }
735
736 return false;
737 }
738
739 bool
ResolvePath()740 FileSpec::ResolvePath ()
741 {
742 if (m_is_resolved)
743 return true; // We have already resolved this path
744
745 char path_buf[PATH_MAX];
746 if (!GetPath (path_buf, PATH_MAX, false))
747 return false;
748 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
749 SetFile (path_buf, true);
750 return m_is_resolved;
751 }
752
753 uint64_t
GetByteSize() const754 FileSpec::GetByteSize() const
755 {
756 struct stat file_stats;
757 if (GetFileStats (this, &file_stats))
758 return file_stats.st_size;
759 return 0;
760 }
761
762 FileSpec::PathSyntax
GetPathSyntax() const763 FileSpec::GetPathSyntax() const
764 {
765 return m_syntax;
766 }
767
768 FileSpec::FileType
GetFileType() const769 FileSpec::GetFileType () const
770 {
771 struct stat file_stats;
772 if (GetFileStats (this, &file_stats))
773 {
774 mode_t file_type = file_stats.st_mode & S_IFMT;
775 switch (file_type)
776 {
777 case S_IFDIR: return eFileTypeDirectory;
778 case S_IFREG: return eFileTypeRegular;
779 #ifndef _WIN32
780 case S_IFIFO: return eFileTypePipe;
781 case S_IFSOCK: return eFileTypeSocket;
782 case S_IFLNK: return eFileTypeSymbolicLink;
783 #endif
784 default:
785 break;
786 }
787 return eFileTypeUnknown;
788 }
789 return eFileTypeInvalid;
790 }
791
792 uint32_t
GetPermissions() const793 FileSpec::GetPermissions () const
794 {
795 uint32_t file_permissions = 0;
796 if (*this)
797 FileSystem::GetFilePermissions(*this, file_permissions);
798 return file_permissions;
799 }
800
801 TimeValue
GetModificationTime() const802 FileSpec::GetModificationTime () const
803 {
804 TimeValue mod_time;
805 struct stat file_stats;
806 if (GetFileStats (this, &file_stats))
807 mod_time.OffsetWithSeconds(file_stats.st_mtime);
808 return mod_time;
809 }
810
811 //------------------------------------------------------------------
812 // Directory string get accessor.
813 //------------------------------------------------------------------
814 ConstString &
GetDirectory()815 FileSpec::GetDirectory()
816 {
817 return m_directory;
818 }
819
820 //------------------------------------------------------------------
821 // Directory string const get accessor.
822 //------------------------------------------------------------------
823 const ConstString &
GetDirectory() const824 FileSpec::GetDirectory() const
825 {
826 return m_directory;
827 }
828
829 //------------------------------------------------------------------
830 // Filename string get accessor.
831 //------------------------------------------------------------------
832 ConstString &
GetFilename()833 FileSpec::GetFilename()
834 {
835 return m_filename;
836 }
837
838 //------------------------------------------------------------------
839 // Filename string const get accessor.
840 //------------------------------------------------------------------
841 const ConstString &
GetFilename() const842 FileSpec::GetFilename() const
843 {
844 return m_filename;
845 }
846
847 //------------------------------------------------------------------
848 // Extract the directory and path into a fixed buffer. This is
849 // needed as the directory and path are stored in separate string
850 // values.
851 //------------------------------------------------------------------
852 size_t
GetPath(char * path,size_t path_max_len,bool denormalize) const853 FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
854 {
855 if (!path)
856 return 0;
857
858 std::string result = GetPath(denormalize);
859 ::snprintf(path, path_max_len, "%s", result.c_str());
860 return std::min(path_max_len-1, result.length());
861 }
862
863 std::string
GetPath(bool denormalize) const864 FileSpec::GetPath(bool denormalize) const
865 {
866 llvm::SmallString<64> result;
867 GetPath(result, denormalize);
868 return std::string(result.begin(), result.end());
869 }
870
871 const char *
GetCString(bool denormalize) const872 FileSpec::GetCString(bool denormalize) const
873 {
874 return ConstString{GetPath(denormalize)}.AsCString(NULL);
875 }
876
877 void
GetPath(llvm::SmallVectorImpl<char> & path,bool denormalize) const878 FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
879 {
880 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
881 if (m_directory)
882 path.insert(path.end(), '/');
883 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
884 Normalize(path, m_syntax);
885 if (path.size() > 1 && path.back() == '/') path.pop_back();
886 if (denormalize && !path.empty())
887 Denormalize(path, m_syntax);
888 }
889
890 ConstString
GetFileNameExtension() const891 FileSpec::GetFileNameExtension () const
892 {
893 if (m_filename)
894 {
895 const char *filename = m_filename.GetCString();
896 const char* dot_pos = strrchr(filename, '.');
897 if (dot_pos && dot_pos[1] != '\0')
898 return ConstString(dot_pos+1);
899 }
900 return ConstString();
901 }
902
903 ConstString
GetFileNameStrippingExtension() const904 FileSpec::GetFileNameStrippingExtension () const
905 {
906 const char *filename = m_filename.GetCString();
907 if (filename == NULL)
908 return ConstString();
909
910 const char* dot_pos = strrchr(filename, '.');
911 if (dot_pos == NULL)
912 return m_filename;
913
914 return ConstString(filename, dot_pos-filename);
915 }
916
917 //------------------------------------------------------------------
918 // Returns a shared pointer to a data buffer that contains all or
919 // part of the contents of a file. The data is memory mapped and
920 // will lazily page in data from the file as memory is accessed.
921 // The data that is mapped will start "file_offset" bytes into the
922 // file, and "file_size" bytes will be mapped. If "file_size" is
923 // greater than the number of bytes available in the file starting
924 // at "file_offset", the number of bytes will be appropriately
925 // truncated. The final number of bytes that get mapped can be
926 // verified using the DataBuffer::GetByteSize() function.
927 //------------------------------------------------------------------
928 DataBufferSP
MemoryMapFileContents(off_t file_offset,size_t file_size) const929 FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
930 {
931 DataBufferSP data_sp;
932 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
933 if (mmap_data.get())
934 {
935 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
936 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
937 data_sp.reset(mmap_data.release());
938 }
939 return data_sp;
940 }
941
942 DataBufferSP
MemoryMapFileContentsIfLocal(off_t file_offset,size_t file_size) const943 FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
944 {
945 if (FileSystem::IsLocal(*this))
946 return MemoryMapFileContents(file_offset, file_size);
947 else
948 return ReadFileContents(file_offset, file_size, NULL);
949 }
950
951
952 //------------------------------------------------------------------
953 // Return the size in bytes that this object takes in memory. This
954 // returns the size in bytes of this object, not any shared string
955 // values it may refer to.
956 //------------------------------------------------------------------
957 size_t
MemorySize() const958 FileSpec::MemorySize() const
959 {
960 return m_filename.MemorySize() + m_directory.MemorySize();
961 }
962
963
964 size_t
ReadFileContents(off_t file_offset,void * dst,size_t dst_len,Error * error_ptr) const965 FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
966 {
967 Error error;
968 size_t bytes_read = 0;
969 char resolved_path[PATH_MAX];
970 if (GetPath(resolved_path, sizeof(resolved_path)))
971 {
972 File file;
973 error = file.Open(resolved_path, File::eOpenOptionRead);
974 if (error.Success())
975 {
976 off_t file_offset_after_seek = file_offset;
977 bytes_read = dst_len;
978 error = file.Read(dst, bytes_read, file_offset_after_seek);
979 }
980 }
981 else
982 {
983 error.SetErrorString("invalid file specification");
984 }
985 if (error_ptr)
986 *error_ptr = error;
987 return bytes_read;
988 }
989
990 //------------------------------------------------------------------
991 // Returns a shared pointer to a data buffer that contains all or
992 // part of the contents of a file. The data copies into a heap based
993 // buffer that lives in the DataBuffer shared pointer object returned.
994 // The data that is cached will start "file_offset" bytes into the
995 // file, and "file_size" bytes will be mapped. If "file_size" is
996 // greater than the number of bytes available in the file starting
997 // at "file_offset", the number of bytes will be appropriately
998 // truncated. The final number of bytes that get mapped can be
999 // verified using the DataBuffer::GetByteSize() function.
1000 //------------------------------------------------------------------
1001 DataBufferSP
ReadFileContents(off_t file_offset,size_t file_size,Error * error_ptr) const1002 FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
1003 {
1004 Error error;
1005 DataBufferSP data_sp;
1006 char resolved_path[PATH_MAX];
1007 if (GetPath(resolved_path, sizeof(resolved_path)))
1008 {
1009 File file;
1010 error = file.Open(resolved_path, File::eOpenOptionRead);
1011 if (error.Success())
1012 {
1013 const bool null_terminate = false;
1014 error = file.Read (file_size, file_offset, null_terminate, data_sp);
1015 }
1016 }
1017 else
1018 {
1019 error.SetErrorString("invalid file specification");
1020 }
1021 if (error_ptr)
1022 *error_ptr = error;
1023 return data_sp;
1024 }
1025
1026 DataBufferSP
ReadFileContentsAsCString(Error * error_ptr)1027 FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1028 {
1029 Error error;
1030 DataBufferSP data_sp;
1031 char resolved_path[PATH_MAX];
1032 if (GetPath(resolved_path, sizeof(resolved_path)))
1033 {
1034 File file;
1035 error = file.Open(resolved_path, File::eOpenOptionRead);
1036 if (error.Success())
1037 {
1038 off_t offset = 0;
1039 size_t length = SIZE_MAX;
1040 const bool null_terminate = true;
1041 error = file.Read (length, offset, null_terminate, data_sp);
1042 }
1043 }
1044 else
1045 {
1046 error.SetErrorString("invalid file specification");
1047 }
1048 if (error_ptr)
1049 *error_ptr = error;
1050 return data_sp;
1051 }
1052
1053 size_t
ReadFileLines(STLStringArray & lines)1054 FileSpec::ReadFileLines (STLStringArray &lines)
1055 {
1056 lines.clear();
1057 char path[PATH_MAX];
1058 if (GetPath(path, sizeof(path)))
1059 {
1060 std::ifstream file_stream (path);
1061
1062 if (file_stream)
1063 {
1064 std::string line;
1065 while (getline (file_stream, line))
1066 lines.push_back (line);
1067 }
1068 }
1069 return lines.size();
1070 }
1071
1072 FileSpec::EnumerateDirectoryResult
ForEachItemInDirectory(const char * dir_path,DirectoryCallback const & callback)1073 FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const &callback)
1074 {
1075 if (dir_path && dir_path[0])
1076 {
1077 #if _WIN32
1078 std::string szDir(dir_path);
1079 szDir += "\\*";
1080
1081 WIN32_FIND_DATA ffd;
1082 HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd);
1083
1084 if (hFind == INVALID_HANDLE_VALUE)
1085 {
1086 return eEnumerateDirectoryResultNext;
1087 }
1088
1089 do
1090 {
1091 FileSpec::FileType file_type = eFileTypeUnknown;
1092 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1093 {
1094 size_t len = strlen(ffd.cFileName);
1095
1096 if (len == 1 && ffd.cFileName[0] == '.')
1097 continue;
1098
1099 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
1100 continue;
1101
1102 file_type = eFileTypeDirectory;
1103 }
1104 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1105 {
1106 file_type = eFileTypeOther;
1107 }
1108 else
1109 {
1110 file_type = eFileTypeRegular;
1111 }
1112
1113 char child_path[MAX_PATH];
1114 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
1115 if (child_path_len < (int)(sizeof(child_path) - 1))
1116 {
1117 // Don't resolve the file type or path
1118 FileSpec child_path_spec (child_path, false);
1119
1120 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1121
1122 switch (result)
1123 {
1124 case eEnumerateDirectoryResultNext:
1125 // Enumerate next entry in the current directory. We just
1126 // exit this switch and will continue enumerating the
1127 // current directory as we currently are...
1128 break;
1129
1130 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1131 if (FileSpec::ForEachItemInDirectory(child_path, callback) == eEnumerateDirectoryResultQuit)
1132 {
1133 // The subdirectory returned Quit, which means to
1134 // stop all directory enumerations at all levels.
1135 return eEnumerateDirectoryResultQuit;
1136 }
1137 break;
1138
1139 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1140 // Exit from this directory level and tell parent to
1141 // keep enumerating.
1142 return eEnumerateDirectoryResultNext;
1143
1144 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1145 return eEnumerateDirectoryResultQuit;
1146 }
1147 }
1148 } while (FindNextFile(hFind, &ffd) != 0);
1149
1150 FindClose(hFind);
1151 #else
1152 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1153 if (dir_path_dir.is_valid())
1154 {
1155 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1156
1157 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1158 #if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1159 if (path_max < __DARWIN_MAXPATHLEN)
1160 path_max = __DARWIN_MAXPATHLEN;
1161 #endif
1162 struct dirent *buf, *dp;
1163 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1164
1165 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1166 {
1167 // Only search directories
1168 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1169 {
1170 size_t len = strlen(dp->d_name);
1171
1172 if (len == 1 && dp->d_name[0] == '.')
1173 continue;
1174
1175 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1176 continue;
1177 }
1178
1179 FileSpec::FileType file_type = eFileTypeUnknown;
1180
1181 switch (dp->d_type)
1182 {
1183 default:
1184 case DT_UNKNOWN: file_type = eFileTypeUnknown; break;
1185 case DT_FIFO: file_type = eFileTypePipe; break;
1186 case DT_CHR: file_type = eFileTypeOther; break;
1187 case DT_DIR: file_type = eFileTypeDirectory; break;
1188 case DT_BLK: file_type = eFileTypeOther; break;
1189 case DT_REG: file_type = eFileTypeRegular; break;
1190 case DT_LNK: file_type = eFileTypeSymbolicLink; break;
1191 case DT_SOCK: file_type = eFileTypeSocket; break;
1192 #if !defined(__OpenBSD__)
1193 case DT_WHT: file_type = eFileTypeOther; break;
1194 #endif
1195 }
1196
1197 char child_path[PATH_MAX];
1198
1199 // Don't make paths with "/foo//bar", that just confuses everybody.
1200 int child_path_len;
1201 if (dir_path_last_char == '/')
1202 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1203 else
1204 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1205
1206 if (child_path_len < (int)(sizeof(child_path) - 1))
1207 {
1208 // Don't resolve the file type or path
1209 FileSpec child_path_spec (child_path, false);
1210
1211 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1212
1213 switch (result)
1214 {
1215 case eEnumerateDirectoryResultNext:
1216 // Enumerate next entry in the current directory. We just
1217 // exit this switch and will continue enumerating the
1218 // current directory as we currently are...
1219 break;
1220
1221 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1222 if (FileSpec::ForEachItemInDirectory (child_path, callback) == eEnumerateDirectoryResultQuit)
1223 {
1224 // The subdirectory returned Quit, which means to
1225 // stop all directory enumerations at all levels.
1226 if (buf)
1227 free (buf);
1228 return eEnumerateDirectoryResultQuit;
1229 }
1230 break;
1231
1232 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1233 // Exit from this directory level and tell parent to
1234 // keep enumerating.
1235 if (buf)
1236 free (buf);
1237 return eEnumerateDirectoryResultNext;
1238
1239 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1240 if (buf)
1241 free (buf);
1242 return eEnumerateDirectoryResultQuit;
1243 }
1244 }
1245 }
1246 if (buf)
1247 {
1248 free (buf);
1249 }
1250 }
1251 #endif
1252 }
1253 // By default when exiting a directory, we tell the parent enumeration
1254 // to continue enumerating.
1255 return eEnumerateDirectoryResultNext;
1256 }
1257
1258 FileSpec::EnumerateDirectoryResult
EnumerateDirectory(const char * dir_path,bool find_directories,bool find_files,bool find_other,EnumerateDirectoryCallbackType callback,void * callback_baton)1259 FileSpec::EnumerateDirectory
1260 (
1261 const char *dir_path,
1262 bool find_directories,
1263 bool find_files,
1264 bool find_other,
1265 EnumerateDirectoryCallbackType callback,
1266 void *callback_baton
1267 )
1268 {
1269 return ForEachItemInDirectory(dir_path,
1270 [&find_directories, &find_files, &find_other, &callback, &callback_baton]
1271 (FileType file_type, const FileSpec &file_spec) {
1272 switch (file_type)
1273 {
1274 case FileType::eFileTypeDirectory:
1275 if (find_directories)
1276 return callback(callback_baton, file_type, file_spec);
1277 break;
1278 case FileType::eFileTypeRegular:
1279 if (find_files)
1280 return callback(callback_baton, file_type, file_spec);
1281 break;
1282 default:
1283 if (find_other)
1284 return callback(callback_baton, file_type, file_spec);
1285 break;
1286 }
1287 return eEnumerateDirectoryResultNext;
1288 });
1289 }
1290
1291 FileSpec
CopyByAppendingPathComponent(const char * new_path) const1292 FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1293 {
1294 const bool resolve = false;
1295 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1296 return FileSpec(new_path,resolve);
1297 StreamString stream;
1298 if (m_filename.IsEmpty())
1299 stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1300 else if (m_directory.IsEmpty())
1301 stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1302 else
1303 stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1304 return FileSpec(stream.GetData(),resolve);
1305 }
1306
1307 FileSpec
CopyByRemovingLastPathComponent() const1308 FileSpec::CopyByRemovingLastPathComponent () const
1309 {
1310 const bool resolve = false;
1311 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1312 return FileSpec("",resolve);
1313 if (m_directory.IsEmpty())
1314 return FileSpec("",resolve);
1315 if (m_filename.IsEmpty())
1316 {
1317 const char* dir_cstr = m_directory.GetCString();
1318 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1319
1320 // check for obvious cases before doing the full thing
1321 if (!last_slash_ptr)
1322 return FileSpec("",resolve);
1323 if (last_slash_ptr == dir_cstr)
1324 return FileSpec("/",resolve);
1325
1326 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1327 ConstString new_path(dir_cstr,last_slash_pos);
1328 return FileSpec(new_path.GetCString(),resolve);
1329 }
1330 else
1331 return FileSpec(m_directory.GetCString(),resolve);
1332 }
1333
1334 ConstString
GetLastPathComponent() const1335 FileSpec::GetLastPathComponent () const
1336 {
1337 if (m_filename)
1338 return m_filename;
1339 if (m_directory)
1340 {
1341 const char* dir_cstr = m_directory.GetCString();
1342 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1343 if (last_slash_ptr == NULL)
1344 return m_directory;
1345 if (last_slash_ptr == dir_cstr)
1346 {
1347 if (last_slash_ptr[1] == 0)
1348 return ConstString(last_slash_ptr);
1349 else
1350 return ConstString(last_slash_ptr+1);
1351 }
1352 if (last_slash_ptr[1] != 0)
1353 return ConstString(last_slash_ptr+1);
1354 const char* penultimate_slash_ptr = last_slash_ptr;
1355 while (*penultimate_slash_ptr)
1356 {
1357 --penultimate_slash_ptr;
1358 if (penultimate_slash_ptr == dir_cstr)
1359 break;
1360 if (*penultimate_slash_ptr == '/')
1361 break;
1362 }
1363 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1364 return result;
1365 }
1366 return ConstString();
1367 }
1368
1369 void
PrependPathComponent(const char * new_path)1370 FileSpec::PrependPathComponent(const char *new_path)
1371 {
1372 if (!new_path) return;
1373 const bool resolve = false;
1374 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1375 {
1376 SetFile(new_path, resolve);
1377 return;
1378 }
1379 StreamString stream;
1380 if (m_filename.IsEmpty())
1381 stream.Printf("%s/%s", new_path, m_directory.GetCString());
1382 else if (m_directory.IsEmpty())
1383 stream.Printf("%s/%s", new_path, m_filename.GetCString());
1384 else
1385 stream.Printf("%s/%s/%s", new_path, m_directory.GetCString(), m_filename.GetCString());
1386 SetFile(stream.GetData(), resolve);
1387 }
1388
1389 void
PrependPathComponent(const std::string & new_path)1390 FileSpec::PrependPathComponent(const std::string &new_path)
1391 {
1392 return PrependPathComponent(new_path.c_str());
1393 }
1394
1395 void
PrependPathComponent(const FileSpec & new_path)1396 FileSpec::PrependPathComponent(const FileSpec &new_path)
1397 {
1398 return PrependPathComponent(new_path.GetPath(false));
1399 }
1400
1401 void
AppendPathComponent(const char * new_path)1402 FileSpec::AppendPathComponent(const char *new_path)
1403 {
1404 if (!new_path) return;
1405 const bool resolve = false;
1406 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1407 {
1408 SetFile(new_path, resolve);
1409 return;
1410 }
1411 StreamString stream;
1412 if (m_filename.IsEmpty())
1413 stream.Printf("%s/%s", m_directory.GetCString(), new_path);
1414 else if (m_directory.IsEmpty())
1415 stream.Printf("%s/%s", m_filename.GetCString(), new_path);
1416 else
1417 stream.Printf("%s/%s/%s", m_directory.GetCString(), m_filename.GetCString(), new_path);
1418 SetFile(stream.GetData(), resolve);
1419 }
1420
1421 void
AppendPathComponent(const std::string & new_path)1422 FileSpec::AppendPathComponent(const std::string &new_path)
1423 {
1424 return AppendPathComponent(new_path.c_str());
1425 }
1426
1427 void
AppendPathComponent(const FileSpec & new_path)1428 FileSpec::AppendPathComponent(const FileSpec &new_path)
1429 {
1430 return AppendPathComponent(new_path.GetPath(false));
1431 }
1432
1433 void
RemoveLastPathComponent()1434 FileSpec::RemoveLastPathComponent ()
1435 {
1436 const bool resolve = false;
1437 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1438 {
1439 SetFile("",resolve);
1440 return;
1441 }
1442 if (m_directory.IsEmpty())
1443 {
1444 SetFile("",resolve);
1445 return;
1446 }
1447 if (m_filename.IsEmpty())
1448 {
1449 const char* dir_cstr = m_directory.GetCString();
1450 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1451
1452 // check for obvious cases before doing the full thing
1453 if (!last_slash_ptr)
1454 {
1455 SetFile("",resolve);
1456 return;
1457 }
1458 if (last_slash_ptr == dir_cstr)
1459 {
1460 SetFile("/",resolve);
1461 return;
1462 }
1463 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1464 ConstString new_path(dir_cstr,last_slash_pos);
1465 SetFile(new_path.GetCString(),resolve);
1466 }
1467 else
1468 SetFile(m_directory.GetCString(),resolve);
1469 }
1470 //------------------------------------------------------------------
1471 /// Returns true if the filespec represents an implementation source
1472 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1473 /// extension).
1474 ///
1475 /// @return
1476 /// \b true if the filespec represents an implementation source
1477 /// file, \b false otherwise.
1478 //------------------------------------------------------------------
1479 bool
IsSourceImplementationFile() const1480 FileSpec::IsSourceImplementationFile () const
1481 {
1482 ConstString extension (GetFileNameExtension());
1483 if (extension)
1484 {
1485 static RegularExpression g_source_file_regex ("^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|[cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO][rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])$");
1486 return g_source_file_regex.Execute (extension.GetCString());
1487 }
1488 return false;
1489 }
1490
1491 bool
IsRelative() const1492 FileSpec::IsRelative() const
1493 {
1494 const char *dir = m_directory.GetCString();
1495 llvm::StringRef directory(dir ? dir : "");
1496
1497 if (directory.size() > 0)
1498 {
1499 if (PathSyntaxIsPosix(m_syntax))
1500 {
1501 // If the path doesn't start with '/' or '~', return true
1502 switch (directory[0])
1503 {
1504 case '/':
1505 case '~':
1506 return false;
1507 default:
1508 return true;
1509 }
1510 }
1511 else
1512 {
1513 if (directory.size() >= 2 && directory[1] == ':')
1514 return false;
1515 if (directory[0] == '/')
1516 return false;
1517 return true;
1518 }
1519 }
1520 else if (m_filename)
1521 {
1522 // No directory, just a basename, return true
1523 return true;
1524 }
1525 return false;
1526 }
1527
1528 bool
IsAbsolute() const1529 FileSpec::IsAbsolute() const
1530 {
1531 return !FileSpec::IsRelative();
1532 }
1533