Bug Summary

File:tools/lldb/source/Host/common/FileSpec.cpp
Location:line 670, column 9
Description:Function call argument is an uninitialized value

Annotated Source Code

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