]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/llvm/tools/lldb/source/Host/common/FileSpec.cpp
MFC r258884: Update LLDB to upstream r196259 snapshot
[FreeBSD/stable/10.git] / contrib / llvm / tools / lldb / source / Host / common / FileSpec.cpp
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 "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Program.h"
33
34 #include "lldb/Core/StreamString.h"
35 #include "lldb/Host/File.h"
36 #include "lldb/Host/FileSpec.h"
37 #include "lldb/Host/Host.h"
38 #include "lldb/Core/DataBufferHeap.h"
39 #include "lldb/Core/DataBufferMemoryMap.h"
40 #include "lldb/Core/RegularExpression.h"
41 #include "lldb/Core/Stream.h"
42 #include "lldb/Host/Host.h"
43 #include "lldb/Utility/CleanUp.h"
44
45 using namespace lldb;
46 using namespace lldb_private;
47
48 static bool
49 GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
50 {
51     char resolved_path[PATH_MAX];
52     if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
53         return ::stat (resolved_path, stats_ptr) == 0;
54     return false;
55 }
56
57 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
58
59 static const char*
60 GetCachedGlobTildeSlash()
61 {
62     static std::string g_tilde;
63     if (g_tilde.empty())
64     {
65         struct passwd *user_entry;
66         user_entry = getpwuid(geteuid());
67         if (user_entry != NULL)
68             g_tilde = user_entry->pw_dir;
69
70         if (g_tilde.empty())
71             return NULL;
72     }
73     return g_tilde.c_str();
74 }
75
76 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
77
78 // Resolves the username part of a path of the form ~user/other/directories, and
79 // writes the result into dst_path.
80 // Returns 0 if there WAS a ~ in the path but the username couldn't be resolved.
81 // Otherwise returns the number of characters copied into dst_path.  If the return
82 // is >= dst_len, then the resolved path is too long...
83 size_t
84 FileSpec::ResolveUsername (const char *src_path, char *dst_path, size_t dst_len)
85 {
86     if (src_path == NULL || src_path[0] == '\0')
87         return 0;
88
89 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
90
91     char user_home[PATH_MAX];
92     const char *user_name;
93     
94     
95     // If there's no ~, then just copy src_path straight to dst_path (they may be the same string...)
96     if (src_path[0] != '~')
97     {
98         size_t len = strlen (src_path);
99         if (len >= dst_len)
100         {
101             ::bcopy (src_path, dst_path, dst_len - 1);
102             dst_path[dst_len] = '\0';
103         }
104         else
105             ::bcopy (src_path, dst_path, len + 1);
106         
107         return len;
108     }
109     
110     const char *first_slash = ::strchr (src_path, '/');
111     char remainder[PATH_MAX];
112     
113     if (first_slash == NULL)
114     {
115         // The whole name is the username (minus the ~):
116         user_name = src_path + 1;
117         remainder[0] = '\0';
118     }
119     else
120     {
121         size_t user_name_len = first_slash - src_path - 1;
122         ::memcpy (user_home, src_path + 1, user_name_len);
123         user_home[user_name_len] = '\0';
124         user_name = user_home;
125         
126         ::strcpy (remainder, first_slash);
127     }
128     
129     if (user_name == NULL)
130         return 0;
131     // User name of "" means the current user...
132     
133     struct passwd *user_entry;
134     const char *home_dir = NULL;
135     
136     if (user_name[0] == '\0')
137     {
138         home_dir = GetCachedGlobTildeSlash();
139     }
140     else
141     {
142         user_entry = ::getpwnam (user_name);
143         if (user_entry != NULL)
144             home_dir = user_entry->pw_dir;
145     }
146     
147     if (home_dir == NULL)
148         return 0;
149     else 
150         return ::snprintf (dst_path, dst_len, "%s%s", home_dir, remainder);
151 #else
152     // Resolving home directories is not supported, just copy the path...
153     return ::snprintf (dst_path, dst_len, "%s", src_path);
154 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER    
155 }
156
157 size_t
158 FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
159 {
160 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
161     size_t extant_entries = matches.GetSize();
162     
163     setpwent();
164     struct passwd *user_entry;
165     const char *name_start = partial_name + 1;
166     std::set<std::string> name_list;
167     
168     while ((user_entry = getpwent()) != NULL)
169     {
170         if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
171         {
172             std::string tmp_buf("~");
173             tmp_buf.append(user_entry->pw_name);
174             tmp_buf.push_back('/');
175             name_list.insert(tmp_buf);                    
176         }
177     }
178     std::set<std::string>::iterator pos, end = name_list.end();
179     for (pos = name_list.begin(); pos != end; pos++)
180     {  
181         matches.AppendString((*pos).c_str());
182     }
183     return matches.GetSize() - extant_entries;
184 #else
185     // Resolving home directories is not supported, just copy the path...
186     return 0;
187 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER    
188 }
189
190
191
192 size_t
193 FileSpec::Resolve (const char *src_path, char *dst_path, size_t dst_len)
194 {
195     if (src_path == NULL || src_path[0] == '\0')
196         return 0;
197
198     // Glob if needed for ~/, otherwise copy in case src_path is same as dst_path...
199     char unglobbed_path[PATH_MAX];
200 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
201     if (src_path[0] == '~')
202     {
203         size_t return_count = ResolveUsername(src_path, unglobbed_path, sizeof(unglobbed_path));
204         
205         // If we couldn't find the user referred to, or the resultant path was too long,
206         // then just copy over the src_path.
207         if (return_count == 0 || return_count >= sizeof(unglobbed_path)) 
208             ::snprintf (unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
209     }
210     else
211 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
212     {
213         ::snprintf(unglobbed_path, sizeof(unglobbed_path), "%s", src_path);
214     }
215
216     // Now resolve the path if needed
217     char resolved_path[PATH_MAX];
218     if (::realpath (unglobbed_path, resolved_path))
219     {
220         // Success, copy the resolved path
221         return ::snprintf(dst_path, dst_len, "%s", resolved_path);
222     }
223     else
224     {
225         // Failed, just copy the unglobbed path
226         return ::snprintf(dst_path, dst_len, "%s", unglobbed_path);
227     }
228 }
229
230 FileSpec::FileSpec() :
231     m_directory(),
232     m_filename()
233 {
234 }
235
236 //------------------------------------------------------------------
237 // Default constructor that can take an optional full path to a
238 // file on disk.
239 //------------------------------------------------------------------
240 FileSpec::FileSpec(const char *pathname, bool resolve_path) :
241     m_directory(),
242     m_filename(),
243     m_is_resolved(false)
244 {
245     if (pathname && pathname[0])
246         SetFile(pathname, resolve_path);
247 }
248
249 //------------------------------------------------------------------
250 // Copy constructor
251 //------------------------------------------------------------------
252 FileSpec::FileSpec(const FileSpec& rhs) :
253     m_directory (rhs.m_directory),
254     m_filename (rhs.m_filename),
255     m_is_resolved (rhs.m_is_resolved)
256 {
257 }
258
259 //------------------------------------------------------------------
260 // Copy constructor
261 //------------------------------------------------------------------
262 FileSpec::FileSpec(const FileSpec* rhs) :
263     m_directory(),
264     m_filename()
265 {
266     if (rhs)
267         *this = *rhs;
268 }
269
270 //------------------------------------------------------------------
271 // Virtual destrcuctor in case anyone inherits from this class.
272 //------------------------------------------------------------------
273 FileSpec::~FileSpec()
274 {
275 }
276
277 //------------------------------------------------------------------
278 // Assignment operator.
279 //------------------------------------------------------------------
280 const FileSpec&
281 FileSpec::operator= (const FileSpec& rhs)
282 {
283     if (this != &rhs)
284     {
285         m_directory = rhs.m_directory;
286         m_filename = rhs.m_filename;
287         m_is_resolved = rhs.m_is_resolved;
288     }
289     return *this;
290 }
291
292 //------------------------------------------------------------------
293 // Update the contents of this object with a new path. The path will
294 // be split up into a directory and filename and stored as uniqued
295 // string values for quick comparison and efficient memory usage.
296 //------------------------------------------------------------------
297 void
298 FileSpec::SetFile (const char *pathname, bool resolve)
299 {
300     m_filename.Clear();
301     m_directory.Clear();
302     m_is_resolved = false;
303     if (pathname == NULL || pathname[0] == '\0')
304         return;
305
306     char resolved_path[PATH_MAX];
307     bool path_fit = true;
308     
309     if (resolve)
310     {
311         path_fit = (FileSpec::Resolve (pathname, resolved_path, sizeof(resolved_path)) < sizeof(resolved_path) - 1);
312         m_is_resolved = path_fit;
313     }
314     else
315     {
316         // Copy the path because "basename" and "dirname" want to muck with the
317         // path buffer
318         if (::strlen (pathname) > sizeof(resolved_path) - 1)
319             path_fit = false;
320         else
321             ::strcpy (resolved_path, pathname);
322     }
323
324     
325     if (path_fit)
326     {
327         char *filename = ::basename (resolved_path);
328         if (filename)
329         {
330             m_filename.SetCString (filename);
331             // Truncate the basename off the end of the resolved path
332
333             // Only attempt to get the dirname if it looks like we have a path
334             if (strchr(resolved_path, '/')
335 #ifdef _WIN32
336                 || strchr(resolved_path, '\\')
337 #endif
338                 )
339             {
340                 char *directory = ::dirname (resolved_path);
341
342                 // Make sure we didn't get our directory resolved to "." without having
343                 // specified
344                 if (directory)
345                     m_directory.SetCString(directory);
346                 else
347                 {
348                     char *last_resolved_path_slash = strrchr(resolved_path, '/');
349 #ifdef _WIN32
350                     char* last_resolved_path_slash_windows = strrchr(resolved_path, '\\');
351                     if (last_resolved_path_slash_windows > last_resolved_path_slash)
352                         last_resolved_path_slash = last_resolved_path_slash_windows;
353 #endif
354                     if (last_resolved_path_slash)
355                     {
356                         *last_resolved_path_slash = '\0';
357                         m_directory.SetCString(resolved_path);
358                     }
359                 }
360             }
361         }
362         else
363             m_directory.SetCString(resolved_path);
364     }
365 }
366
367 //----------------------------------------------------------------------
368 // Convert to pointer operator. This allows code to check any FileSpec
369 // objects to see if they contain anything valid using code such as:
370 //
371 //  if (file_spec)
372 //  {}
373 //----------------------------------------------------------------------
374 FileSpec::operator bool() const
375 {
376     return m_filename || m_directory;
377 }
378
379 //----------------------------------------------------------------------
380 // Logical NOT operator. This allows code to check any FileSpec
381 // objects to see if they are invalid using code such as:
382 //
383 //  if (!file_spec)
384 //  {}
385 //----------------------------------------------------------------------
386 bool
387 FileSpec::operator!() const
388 {
389     return !m_directory && !m_filename;
390 }
391
392 //------------------------------------------------------------------
393 // Equal to operator
394 //------------------------------------------------------------------
395 bool
396 FileSpec::operator== (const FileSpec& rhs) const
397 {
398     if (m_filename == rhs.m_filename)
399     {
400         if (m_directory == rhs.m_directory)
401             return true;
402         
403         // TODO: determine if we want to keep this code in here.
404         // The code below was added to handle a case where we were
405         // trying to set a file and line breakpoint and one path
406         // was resolved, and the other not and the directory was
407         // in a mount point that resolved to a more complete path:
408         // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
409         // this out...
410         if (IsResolved() && rhs.IsResolved())
411         {
412             // Both paths are resolved, no need to look further...
413             return false;
414         }
415         
416         FileSpec resolved_lhs(*this);
417
418         // If "this" isn't resolved, resolve it
419         if (!IsResolved())
420         {
421             if (resolved_lhs.ResolvePath())
422             {
423                 // This path wasn't resolved but now it is. Check if the resolved
424                 // directory is the same as our unresolved directory, and if so, 
425                 // we can mark this object as resolved to avoid more future resolves
426                 m_is_resolved = (m_directory == resolved_lhs.m_directory);
427             }
428             else
429                 return false;
430         }
431         
432         FileSpec resolved_rhs(rhs);
433         if (!rhs.IsResolved())
434         {
435             if (resolved_rhs.ResolvePath())
436             {
437                 // rhs's path wasn't resolved but now it is. Check if the resolved
438                 // directory is the same as rhs's unresolved directory, and if so, 
439                 // we can mark this object as resolved to avoid more future resolves
440                 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
441             }
442             else
443                 return false;
444         }
445
446         // If we reach this point in the code we were able to resolve both paths
447         // and since we only resolve the paths if the basenames are equal, then
448         // we can just check if both directories are equal...
449         return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory();
450     }
451     return false;
452 }
453
454 //------------------------------------------------------------------
455 // Not equal to operator
456 //------------------------------------------------------------------
457 bool
458 FileSpec::operator!= (const FileSpec& rhs) const
459 {
460     return !(*this == rhs);
461 }
462
463 //------------------------------------------------------------------
464 // Less than operator
465 //------------------------------------------------------------------
466 bool
467 FileSpec::operator< (const FileSpec& rhs) const
468 {
469     return FileSpec::Compare(*this, rhs, true) < 0;
470 }
471
472 //------------------------------------------------------------------
473 // Dump a FileSpec object to a stream
474 //------------------------------------------------------------------
475 Stream&
476 lldb_private::operator << (Stream &s, const FileSpec& f)
477 {
478     f.Dump(&s);
479     return s;
480 }
481
482 //------------------------------------------------------------------
483 // Clear this object by releasing both the directory and filename
484 // string values and making them both the empty string.
485 //------------------------------------------------------------------
486 void
487 FileSpec::Clear()
488 {
489     m_directory.Clear();
490     m_filename.Clear();
491 }
492
493 //------------------------------------------------------------------
494 // Compare two FileSpec objects. If "full" is true, then both
495 // the directory and the filename must match. If "full" is false,
496 // then the directory names for "a" and "b" are only compared if
497 // they are both non-empty. This allows a FileSpec object to only
498 // contain a filename and it can match FileSpec objects that have
499 // matching filenames with different paths.
500 //
501 // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
502 // and "1" if "a" is greater than "b".
503 //------------------------------------------------------------------
504 int
505 FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
506 {
507     int result = 0;
508
509     // If full is true, then we must compare both the directory and filename.
510
511     // If full is false, then if either directory is empty, then we match on
512     // the basename only, and if both directories have valid values, we still
513     // do a full compare. This allows for matching when we just have a filename
514     // in one of the FileSpec objects.
515
516     if (full || (a.m_directory && b.m_directory))
517     {
518         result = ConstString::Compare(a.m_directory, b.m_directory);
519         if (result)
520             return result;
521     }
522     return ConstString::Compare (a.m_filename, b.m_filename);
523 }
524
525 bool
526 FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full)
527 {
528     if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
529         return a.m_filename == b.m_filename;
530     else
531         return a == b;
532 }
533
534
535
536 //------------------------------------------------------------------
537 // Dump the object to the supplied stream. If the object contains
538 // a valid directory name, it will be displayed followed by a
539 // directory delimiter, and the filename.
540 //------------------------------------------------------------------
541 void
542 FileSpec::Dump(Stream *s) const
543 {
544     static ConstString g_slash_only ("/");
545     if (s)
546     {
547         m_directory.Dump(s);
548         if (m_directory && m_directory != g_slash_only)
549             s->PutChar('/');
550         m_filename.Dump(s);
551     }
552 }
553
554 //------------------------------------------------------------------
555 // Returns true if the file exists.
556 //------------------------------------------------------------------
557 bool
558 FileSpec::Exists () const
559 {
560     struct stat file_stats;
561     return GetFileStats (this, &file_stats);
562 }
563
564 bool
565 FileSpec::ResolveExecutableLocation ()
566 {
567     if (!m_directory)
568     {
569         const char *file_cstr = m_filename.GetCString();
570         if (file_cstr)
571         {
572             const std::string file_str (file_cstr);
573             llvm::sys::Path path = llvm::sys::Program::FindProgramByName (file_str);
574             const std::string &path_str = path.str();
575             llvm::StringRef dir_ref = llvm::sys::path::parent_path(path_str);
576             //llvm::StringRef dir_ref = path.getDirname();
577             if (! dir_ref.empty())
578             {
579                 // FindProgramByName returns "." if it can't find the file.
580                 if (strcmp (".", dir_ref.data()) == 0)
581                     return false;
582
583                 m_directory.SetCString (dir_ref.data());
584                 if (Exists())
585                     return true;
586                 else
587                 {
588                     // If FindProgramByName found the file, it returns the directory + filename in its return results.
589                     // We need to separate them.
590                     FileSpec tmp_file (dir_ref.data(), false);
591                     if (tmp_file.Exists())
592                     {
593                         m_directory = tmp_file.m_directory;
594                         return true;
595                     }
596                 }
597             }
598         }
599     }
600     
601     return false;
602 }
603
604 bool
605 FileSpec::ResolvePath ()
606 {
607     if (m_is_resolved)
608         return true;    // We have already resolved this path
609
610     char path_buf[PATH_MAX];    
611     if (!GetPath (path_buf, PATH_MAX))
612         return false;
613     // SetFile(...) will set m_is_resolved correctly if it can resolve the path
614     SetFile (path_buf, true);
615     return m_is_resolved; 
616 }
617
618 uint64_t
619 FileSpec::GetByteSize() const
620 {
621     struct stat file_stats;
622     if (GetFileStats (this, &file_stats))
623         return file_stats.st_size;
624     return 0;
625 }
626
627 FileSpec::FileType
628 FileSpec::GetFileType () const
629 {
630     struct stat file_stats;
631     if (GetFileStats (this, &file_stats))
632     {
633         mode_t file_type = file_stats.st_mode & S_IFMT;
634         switch (file_type)
635         {
636         case S_IFDIR:   return eFileTypeDirectory;
637         case S_IFREG:   return eFileTypeRegular;
638 #ifndef _WIN32
639         case S_IFIFO:   return eFileTypePipe;
640         case S_IFSOCK:  return eFileTypeSocket;
641         case S_IFLNK:   return eFileTypeSymbolicLink;
642 #endif
643         default:
644             break;
645         }
646         return eFileTypeUnknown;
647     }
648     return eFileTypeInvalid;
649 }
650
651 uint32_t
652 FileSpec::GetPermissions () const
653 {
654     uint32_t file_permissions = 0;
655     if (*this)
656         Host::GetFilePermissions(GetPath().c_str(), file_permissions);
657     return file_permissions;
658 }
659
660 TimeValue
661 FileSpec::GetModificationTime () const
662 {
663     TimeValue mod_time;
664     struct stat file_stats;
665     if (GetFileStats (this, &file_stats))
666         mod_time.OffsetWithSeconds(file_stats.st_mtime);
667     return mod_time;
668 }
669
670 //------------------------------------------------------------------
671 // Directory string get accessor.
672 //------------------------------------------------------------------
673 ConstString &
674 FileSpec::GetDirectory()
675 {
676     return m_directory;
677 }
678
679 //------------------------------------------------------------------
680 // Directory string const get accessor.
681 //------------------------------------------------------------------
682 const ConstString &
683 FileSpec::GetDirectory() const
684 {
685     return m_directory;
686 }
687
688 //------------------------------------------------------------------
689 // Filename string get accessor.
690 //------------------------------------------------------------------
691 ConstString &
692 FileSpec::GetFilename()
693 {
694     return m_filename;
695 }
696
697 //------------------------------------------------------------------
698 // Filename string const get accessor.
699 //------------------------------------------------------------------
700 const ConstString &
701 FileSpec::GetFilename() const
702 {
703     return m_filename;
704 }
705
706 //------------------------------------------------------------------
707 // Extract the directory and path into a fixed buffer. This is
708 // needed as the directory and path are stored in separate string
709 // values.
710 //------------------------------------------------------------------
711 size_t
712 FileSpec::GetPath(char *path, size_t path_max_len) const
713 {
714     if (path_max_len)
715     {
716         const char *dirname = m_directory.GetCString();
717         const char *filename = m_filename.GetCString();
718         if (dirname)
719         {
720             if (filename)
721                 return ::snprintf (path, path_max_len, "%s/%s", dirname, filename);
722             else
723                 return ::snprintf (path, path_max_len, "%s", dirname);
724         }
725         else if (filename)
726         {
727             return ::snprintf (path, path_max_len, "%s", filename);
728         }
729     }
730     if (path)
731         path[0] = '\0';
732     return 0;
733 }
734
735 std::string
736 FileSpec::GetPath (void) const
737 {
738     static ConstString g_slash_only ("/");
739     std::string path;
740     const char *dirname = m_directory.GetCString();
741     const char *filename = m_filename.GetCString();
742     if (dirname)
743     {
744         path.append (dirname);
745         if (filename && m_directory != g_slash_only)
746             path.append ("/");
747     }
748     if (filename)
749         path.append (filename);
750     return path;
751 }
752
753 ConstString
754 FileSpec::GetFileNameExtension () const
755 {
756     if (m_filename)
757     {
758         const char *filename = m_filename.GetCString();
759         const char* dot_pos = strrchr(filename, '.');
760         if (dot_pos && dot_pos[1] != '\0')
761             return ConstString(dot_pos+1);
762     }
763     return ConstString();
764 }
765
766 ConstString
767 FileSpec::GetFileNameStrippingExtension () const
768 {
769     const char *filename = m_filename.GetCString();
770     if (filename == NULL)
771         return ConstString();
772     
773     const char* dot_pos = strrchr(filename, '.');
774     if (dot_pos == NULL)
775         return m_filename;
776     
777     return ConstString(filename, dot_pos-filename);
778 }
779
780 //------------------------------------------------------------------
781 // Returns a shared pointer to a data buffer that contains all or
782 // part of the contents of a file. The data is memory mapped and
783 // will lazily page in data from the file as memory is accessed.
784 // The data that is mappped will start "file_offset" bytes into the
785 // file, and "file_size" bytes will be mapped. If "file_size" is
786 // greater than the number of bytes available in the file starting
787 // at "file_offset", the number of bytes will be appropriately
788 // truncated. The final number of bytes that get mapped can be
789 // verified using the DataBuffer::GetByteSize() function.
790 //------------------------------------------------------------------
791 DataBufferSP
792 FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
793 {
794     DataBufferSP data_sp;
795     std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
796     if (mmap_data.get())
797     {
798         const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
799         if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
800             data_sp.reset(mmap_data.release());
801     }
802     return data_sp;
803 }
804
805
806 //------------------------------------------------------------------
807 // Return the size in bytes that this object takes in memory. This
808 // returns the size in bytes of this object, not any shared string
809 // values it may refer to.
810 //------------------------------------------------------------------
811 size_t
812 FileSpec::MemorySize() const
813 {
814     return m_filename.MemorySize() + m_directory.MemorySize();
815 }
816
817
818 size_t
819 FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
820 {
821     Error error;
822     size_t bytes_read = 0;
823     char resolved_path[PATH_MAX];
824     if (GetPath(resolved_path, sizeof(resolved_path)))
825     {
826         File file;
827         error = file.Open(resolved_path, File::eOpenOptionRead);
828         if (error.Success())
829         {
830             off_t file_offset_after_seek = file_offset;
831             bytes_read = dst_len;
832             error = file.Read(dst, bytes_read, file_offset_after_seek);
833         }
834     }
835     else
836     {
837         error.SetErrorString("invalid file specification");
838     }
839     if (error_ptr)
840         *error_ptr = error;
841     return bytes_read;
842 }
843
844 //------------------------------------------------------------------
845 // Returns a shared pointer to a data buffer that contains all or
846 // part of the contents of a file. The data copies into a heap based
847 // buffer that lives in the DataBuffer shared pointer object returned.
848 // The data that is cached will start "file_offset" bytes into the
849 // file, and "file_size" bytes will be mapped. If "file_size" is
850 // greater than the number of bytes available in the file starting
851 // at "file_offset", the number of bytes will be appropriately
852 // truncated. The final number of bytes that get mapped can be
853 // verified using the DataBuffer::GetByteSize() function.
854 //------------------------------------------------------------------
855 DataBufferSP
856 FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
857 {
858     Error error;
859     DataBufferSP data_sp;
860     char resolved_path[PATH_MAX];
861     if (GetPath(resolved_path, sizeof(resolved_path)))
862     {
863         File file;
864         error = file.Open(resolved_path, File::eOpenOptionRead);
865         if (error.Success())
866         {
867             const bool null_terminate = false;
868             error = file.Read (file_size, file_offset, null_terminate, data_sp);
869         }
870     }
871     else
872     {
873         error.SetErrorString("invalid file specification");
874     }
875     if (error_ptr)
876         *error_ptr = error;
877     return data_sp;
878 }
879
880 DataBufferSP
881 FileSpec::ReadFileContentsAsCString(Error *error_ptr)
882 {
883     Error error;
884     DataBufferSP data_sp;
885     char resolved_path[PATH_MAX];
886     if (GetPath(resolved_path, sizeof(resolved_path)))
887     {
888         File file;
889         error = file.Open(resolved_path, File::eOpenOptionRead);
890         if (error.Success())
891         {
892             off_t offset = 0;
893             size_t length = SIZE_MAX;
894             const bool null_terminate = true;
895             error = file.Read (length, offset, null_terminate, data_sp);
896         }
897     }
898     else
899     {
900         error.SetErrorString("invalid file specification");
901     }
902     if (error_ptr)
903         *error_ptr = error;
904     return data_sp;
905 }
906
907 size_t
908 FileSpec::ReadFileLines (STLStringArray &lines)
909 {
910     lines.clear();
911     char path[PATH_MAX];
912     if (GetPath(path, sizeof(path)))
913     {
914         std::ifstream file_stream (path);
915
916         if (file_stream)
917         {
918             std::string line;
919             while (getline (file_stream, line))
920                 lines.push_back (line);
921         }
922     }
923     return lines.size();
924 }
925
926 FileSpec::EnumerateDirectoryResult
927 FileSpec::EnumerateDirectory
928 (
929     const char *dir_path, 
930     bool find_directories,
931     bool find_files,
932     bool find_other,
933     EnumerateDirectoryCallbackType callback,
934     void *callback_baton
935 )
936 {
937     if (dir_path && dir_path[0])
938     {
939 #if _WIN32
940         char szDir[MAX_PATH];
941         strcpy_s(szDir, MAX_PATH, dir_path);
942         strcat_s(szDir, MAX_PATH, "\\*");
943
944         WIN32_FIND_DATA ffd;
945         HANDLE hFind = FindFirstFile(szDir, &ffd);
946
947         if (hFind == INVALID_HANDLE_VALUE)
948         {
949             return eEnumerateDirectoryResultNext;
950         }
951
952         do
953         {
954             bool call_callback = false;
955             FileSpec::FileType file_type = eFileTypeUnknown;
956             if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
957             {
958                 size_t len = strlen(ffd.cFileName);
959
960                 if (len == 1 && ffd.cFileName[0] == '.')
961                     continue;
962
963                 if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.')
964                     continue;
965
966                 file_type = eFileTypeDirectory;
967                 call_callback = find_directories;
968             }
969             else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
970             {
971                 file_type = eFileTypeOther;
972                 call_callback = find_other;
973             }
974             else
975             {
976                 file_type = eFileTypeRegular;
977                 call_callback = find_files;
978             }
979             if (call_callback)
980             {
981                 char child_path[MAX_PATH];
982                 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName);
983                 if (child_path_len < (int)(sizeof(child_path) - 1))
984                 {
985                     // Don't resolve the file type or path
986                     FileSpec child_path_spec (child_path, false);
987
988                     EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
989
990                     switch (result)
991                     {
992                     case eEnumerateDirectoryResultNext:
993                         // Enumerate next entry in the current directory. We just
994                         // exit this switch and will continue enumerating the
995                         // current directory as we currently are...
996                         break;
997
998                     case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
999                         if (FileSpec::EnumerateDirectory(child_path,
1000                             find_directories,
1001                             find_files,
1002                             find_other,
1003                             callback,
1004                             callback_baton) == eEnumerateDirectoryResultQuit)
1005                         {
1006                             // The subdirectory returned Quit, which means to 
1007                             // stop all directory enumerations at all levels.
1008                             return eEnumerateDirectoryResultQuit;
1009                         }
1010                         break;
1011
1012                     case eEnumerateDirectoryResultExit:  // Exit from the current directory at the current level.
1013                         // Exit from this directory level and tell parent to 
1014                         // keep enumerating.
1015                         return eEnumerateDirectoryResultNext;
1016
1017                     case eEnumerateDirectoryResultQuit:  // Stop directory enumerations at any level
1018                         return eEnumerateDirectoryResultQuit;
1019                     }
1020                 }
1021             }
1022         } while (FindNextFile(hFind, &ffd) != 0);
1023
1024         FindClose(hFind);
1025 #else
1026         lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1027         if (dir_path_dir.is_valid())
1028         {
1029             long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1030 #if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1031             if (path_max < __DARWIN_MAXPATHLEN)
1032                 path_max = __DARWIN_MAXPATHLEN;
1033 #endif
1034             struct dirent *buf, *dp;
1035             buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1036
1037             while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1038             {
1039                 // Only search directories
1040                 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1041                 {
1042                     size_t len = strlen(dp->d_name);
1043
1044                     if (len == 1 && dp->d_name[0] == '.')
1045                         continue;
1046
1047                     if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1048                         continue;
1049                 }
1050             
1051                 bool call_callback = false;
1052                 FileSpec::FileType file_type = eFileTypeUnknown;
1053
1054                 switch (dp->d_type)
1055                 {
1056                 default:
1057                 case DT_UNKNOWN:    file_type = eFileTypeUnknown;       call_callback = true;               break;
1058                 case DT_FIFO:       file_type = eFileTypePipe;          call_callback = find_other;         break;
1059                 case DT_CHR:        file_type = eFileTypeOther;         call_callback = find_other;         break;
1060                 case DT_DIR:        file_type = eFileTypeDirectory;     call_callback = find_directories;   break;
1061                 case DT_BLK:        file_type = eFileTypeOther;         call_callback = find_other;         break;
1062                 case DT_REG:        file_type = eFileTypeRegular;       call_callback = find_files;         break;
1063                 case DT_LNK:        file_type = eFileTypeSymbolicLink;  call_callback = find_other;         break;
1064                 case DT_SOCK:       file_type = eFileTypeSocket;        call_callback = find_other;         break;
1065 #if !defined(__OpenBSD__)
1066                 case DT_WHT:        file_type = eFileTypeOther;         call_callback = find_other;         break;
1067 #endif
1068                 }
1069
1070                 if (call_callback)
1071                 {
1072                     char child_path[PATH_MAX];
1073                     const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1074                     if (child_path_len < (int)(sizeof(child_path) - 1))
1075                     {
1076                         // Don't resolve the file type or path
1077                         FileSpec child_path_spec (child_path, false);
1078
1079                         EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec);
1080                         
1081                         switch (result)
1082                         {
1083                         case eEnumerateDirectoryResultNext:  
1084                             // Enumerate next entry in the current directory. We just
1085                             // exit this switch and will continue enumerating the
1086                             // current directory as we currently are...
1087                             break;
1088
1089                         case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1090                             if (FileSpec::EnumerateDirectory (child_path, 
1091                                                               find_directories, 
1092                                                               find_files, 
1093                                                               find_other, 
1094                                                               callback, 
1095                                                               callback_baton) == eEnumerateDirectoryResultQuit)
1096                             {
1097                                 // The subdirectory returned Quit, which means to 
1098                                 // stop all directory enumerations at all levels.
1099                                 if (buf)
1100                                     free (buf);
1101                                 return eEnumerateDirectoryResultQuit;
1102                             }
1103                             break;
1104                         
1105                         case eEnumerateDirectoryResultExit:  // Exit from the current directory at the current level.
1106                             // Exit from this directory level and tell parent to 
1107                             // keep enumerating.
1108                             if (buf)
1109                                 free (buf);
1110                             return eEnumerateDirectoryResultNext;
1111
1112                         case eEnumerateDirectoryResultQuit:  // Stop directory enumerations at any level
1113                             if (buf)
1114                                 free (buf);
1115                             return eEnumerateDirectoryResultQuit;
1116                         }
1117                     }
1118                 }
1119             }
1120             if (buf)
1121             {
1122                 free (buf);
1123             }
1124         }
1125 #endif
1126     }
1127     // By default when exiting a directory, we tell the parent enumeration
1128     // to continue enumerating.
1129     return eEnumerateDirectoryResultNext;    
1130 }
1131
1132 FileSpec
1133 FileSpec::CopyByAppendingPathComponent (const char *new_path)  const
1134 {
1135     const bool resolve = false;
1136     if (m_filename.IsEmpty() && m_directory.IsEmpty())
1137         return FileSpec(new_path,resolve);
1138     StreamString stream;
1139     if (m_filename.IsEmpty())
1140         stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1141     else if (m_directory.IsEmpty())
1142         stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1143     else
1144         stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1145     return FileSpec(stream.GetData(),resolve);
1146 }
1147
1148 FileSpec
1149 FileSpec::CopyByRemovingLastPathComponent ()  const
1150 {
1151     const bool resolve = false;
1152     if (m_filename.IsEmpty() && m_directory.IsEmpty())
1153         return FileSpec("",resolve);
1154     if (m_directory.IsEmpty())
1155         return FileSpec("",resolve);
1156     if (m_filename.IsEmpty())
1157     {
1158         const char* dir_cstr = m_directory.GetCString();
1159         const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1160         
1161         // check for obvious cases before doing the full thing
1162         if (!last_slash_ptr)
1163             return FileSpec("",resolve);
1164         if (last_slash_ptr == dir_cstr)
1165             return FileSpec("/",resolve);
1166         
1167         size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1168         ConstString new_path(dir_cstr,last_slash_pos);
1169         return FileSpec(new_path.GetCString(),resolve);
1170     }
1171     else
1172         return FileSpec(m_directory.GetCString(),resolve);
1173 }
1174
1175 ConstString
1176 FileSpec::GetLastPathComponent () const
1177 {
1178     if (m_filename)
1179         return m_filename;
1180     if (m_directory)
1181     {
1182         const char* dir_cstr = m_directory.GetCString();
1183         const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1184         if (last_slash_ptr == NULL)
1185             return m_directory;
1186         if (last_slash_ptr == dir_cstr)
1187         {
1188             if (last_slash_ptr[1] == 0)
1189                 return ConstString(last_slash_ptr);
1190             else
1191                 return ConstString(last_slash_ptr+1);
1192         }
1193         if (last_slash_ptr[1] != 0)
1194             return ConstString(last_slash_ptr+1);
1195         const char* penultimate_slash_ptr = last_slash_ptr;
1196         while (*penultimate_slash_ptr)
1197         {
1198             --penultimate_slash_ptr;
1199             if (penultimate_slash_ptr == dir_cstr)
1200                 break;
1201             if (*penultimate_slash_ptr == '/')
1202                 break;
1203         }
1204         ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1205         return result;
1206     }
1207     return ConstString();
1208 }
1209
1210 void
1211 FileSpec::AppendPathComponent (const char *new_path)
1212 {
1213     const bool resolve = false;
1214     if (m_filename.IsEmpty() && m_directory.IsEmpty())
1215     {
1216         SetFile(new_path,resolve);
1217         return;
1218     }
1219     StreamString stream;
1220     if (m_filename.IsEmpty())
1221         stream.Printf("%s/%s",m_directory.GetCString(),new_path);
1222     else if (m_directory.IsEmpty())
1223         stream.Printf("%s/%s",m_filename.GetCString(),new_path);
1224     else
1225         stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path);
1226     SetFile(stream.GetData(), resolve);
1227 }
1228
1229 void
1230 FileSpec::RemoveLastPathComponent ()
1231 {
1232     const bool resolve = false;
1233     if (m_filename.IsEmpty() && m_directory.IsEmpty())
1234     {
1235         SetFile("",resolve);
1236         return;
1237     }
1238     if (m_directory.IsEmpty())
1239     {
1240         SetFile("",resolve);
1241         return;
1242     }
1243     if (m_filename.IsEmpty())
1244     {
1245         const char* dir_cstr = m_directory.GetCString();
1246         const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1247         
1248         // check for obvious cases before doing the full thing
1249         if (!last_slash_ptr)
1250         {
1251             SetFile("",resolve);
1252             return;
1253         }
1254         if (last_slash_ptr == dir_cstr)
1255         {
1256             SetFile("/",resolve);
1257             return;
1258         }        
1259         size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1260         ConstString new_path(dir_cstr,last_slash_pos);
1261         SetFile(new_path.GetCString(),resolve);
1262     }
1263     else
1264         SetFile(m_directory.GetCString(),resolve);
1265 }
1266 //------------------------------------------------------------------
1267 /// Returns true if the filespec represents an implementation source
1268 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1269 /// extension).
1270 ///
1271 /// @return
1272 ///     \b true if the filespec represents an implementation source
1273 ///     file, \b false otherwise.
1274 //------------------------------------------------------------------
1275 bool
1276 FileSpec::IsSourceImplementationFile () const
1277 {
1278     ConstString extension (GetFileNameExtension());
1279     if (extension)
1280     {
1281         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)$",
1282                                                       REG_EXTENDED | REG_ICASE);
1283         return g_source_file_regex.Execute (extension.GetCString());
1284     }
1285     return false;
1286 }
1287
1288 bool
1289 FileSpec::IsRelativeToCurrentWorkingDirectory () const
1290 {
1291     const char *directory = m_directory.GetCString();
1292     if (directory && directory[0])
1293     {
1294         // If the path doesn't start with '/' or '~', return true
1295         switch (directory[0])
1296         {
1297         case '/':
1298         case '~':
1299             return false;
1300         default:
1301             return true;
1302         }
1303     }
1304     else if (m_filename)
1305     {
1306         // No directory, just a basename, return true
1307         return true;
1308     }
1309     return false;
1310 }