1 //===-- SourceManager.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/SourceManager.h"
12 #include "lldb/Core/Address.h" // for Address
13 #include "lldb/Core/AddressRange.h" // for AddressRange
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/FormatEntity.h" // for FormatEntity
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h" // for ModuleList
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Symbol/CompileUnit.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/LineEntry.h" // for LineEntry
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Target/PathMappingList.h" // for PathMappingList
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/ConstString.h" // for ConstString
26 #include "lldb/Utility/DataBuffer.h"
27 #include "lldb/Utility/DataBufferLLVM.h"
28 #include "lldb/Utility/RegularExpression.h"
29 #include "lldb/Utility/Stream.h"
30 #include "lldb/lldb-enumerations.h" // for StopShowColumn::eStopSho...
32 #include "llvm/ADT/Twine.h" // for Twine
35 #include <utility> // for pair
37 #include <assert.h> // for assert
38 #include <stdio.h> // for size_t, NULL, snprintf
40 namespace lldb_private {
41 class ExecutionContext;
43 namespace lldb_private {
48 using namespace lldb_private;
50 static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; }
52 //----------------------------------------------------------------------
53 // SourceManager constructor
54 //----------------------------------------------------------------------
55 SourceManager::SourceManager(const TargetSP &target_sp)
56 : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false),
57 m_target_wp(target_sp),
58 m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}
60 SourceManager::SourceManager(const DebuggerSP &debugger_sp)
61 : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false),
62 m_target_wp(), m_debugger_wp(debugger_sp) {}
64 //----------------------------------------------------------------------
66 //----------------------------------------------------------------------
67 SourceManager::~SourceManager() {}
69 SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) {
70 bool same_as_previous =
71 m_last_file_sp && m_last_file_sp->FileSpecMatches(file_spec);
73 DebuggerSP debugger_sp(m_debugger_wp.lock());
76 file_sp = m_last_file_sp;
78 file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);
80 TargetSP target_sp(m_target_wp.lock());
82 // It the target source path map has been updated, get this file again so we
83 // can successfully remap the source file
84 if (target_sp && file_sp &&
85 file_sp->GetSourceMapModificationID() !=
86 target_sp->GetSourcePathMap().GetModificationID())
89 // Update the file contents if needed if we found a file
91 file_sp->UpdateIfNeeded();
93 // If file_sp is no good or it points to a non-existent file, reset it.
94 if (!file_sp || !file_sp->GetFileSpec().Exists()) {
96 file_sp = std::make_shared<File>(file_spec, target_sp.get());
98 file_sp = std::make_shared<File>(file_spec, debugger_sp);
101 debugger_sp->GetSourceFileCache().AddSourceFile(file_sp);
106 static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {
107 // We don't use ANSI stop column formatting if we can't lookup values from
112 // We don't use ANSI stop column formatting if the debugger doesn't think
113 // it should be using color.
114 if (!debugger_sp->GetUseColor())
117 // We only use ANSI stop column formatting if we're either supposed to show
118 // ANSI where available (which we know we have when we get to this point), or
119 // if we're only supposed to use ANSI.
120 const auto value = debugger_sp->GetStopShowColumn();
121 return ((value == eStopShowColumnAnsiOrCaret) ||
122 (value == eStopShowColumnAnsi));
125 static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {
126 // We don't use text-based stop column formatting if we can't lookup values
127 // from the debugger.
131 // If we're asked to show the first available of ANSI or caret, then
132 // we do show the caret when ANSI is not available.
133 const auto value = debugger_sp->GetStopShowColumn();
134 if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())
137 // The only other time we use caret is if we're explicitly asked to show
139 return value == eStopShowColumnCaret;
142 size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(
143 uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,
144 const char *current_line_cstr, Stream *s,
145 const SymbolContextList *bp_locs) {
148 size_t return_value = 0;
149 if (start_line == 0) {
150 if (m_last_line != 0 && m_last_line != UINT32_MAX)
151 start_line = m_last_line + m_last_count;
156 if (!m_default_set) {
159 GetDefaultFileAndLine(tmp_spec, tmp_line);
162 m_last_line = start_line;
163 m_last_count = count;
165 if (m_last_file_sp.get()) {
166 const uint32_t end_line = start_line + count - 1;
167 for (uint32_t line = start_line; line <= end_line; ++line) {
168 if (!m_last_file_sp->LineIsValid(line)) {
169 m_last_line = UINT32_MAX;
173 char prefix[32] = "";
175 uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);
178 ::snprintf(prefix, sizeof(prefix), "[%u] ", bp_count);
180 ::snprintf(prefix, sizeof(prefix), " ");
184 s->Printf("%s%2.2s %-4u\t", prefix,
185 line == curr_line ? current_line_cstr : "", line);
186 size_t this_line_size = m_last_file_sp->DisplaySourceLines(
187 line, line == curr_line ? column : 0, 0, 0, s);
188 if (column != 0 && line == curr_line &&
189 should_show_stop_column_with_caret(m_debugger_wp.lock())) {
190 // Display caret cursor.
191 std::string src_line;
192 m_last_file_sp->GetLine(line, src_line);
193 return_value += s->Printf(" \t");
194 // Insert a space for every non-tab character in the source line.
195 for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)
196 return_value += s->PutChar(src_line[i] == '\t' ? '\t' : ' ');
197 // Now add the caret.
198 return_value += s->Printf("^\n");
200 if (this_line_size == 0) {
201 m_last_line = UINT32_MAX;
204 return_value += this_line_size;
210 size_t SourceManager::DisplaySourceLinesWithLineNumbers(
211 const FileSpec &file_spec, uint32_t line, uint32_t column,
212 uint32_t context_before, uint32_t context_after,
213 const char *current_line_cstr, Stream *s,
214 const SymbolContextList *bp_locs) {
215 FileSP file_sp(GetFile(file_spec));
218 uint32_t count = context_before + context_after + 1;
219 if (line > context_before)
220 start_line = line - context_before;
224 if (m_last_file_sp.get() != file_sp.get()) {
227 m_last_file_sp = file_sp;
229 return DisplaySourceLinesWithLineNumbersUsingLastFile(
230 start_line, count, line, column, current_line_cstr, s, bp_locs);
233 size_t SourceManager::DisplayMoreWithLineNumbers(
234 Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {
235 // If we get called before anybody has set a default file and line, then try
236 // to figure it out here.
237 const bool have_default_file_line = m_last_file_sp && m_last_line > 0;
238 if (!m_default_set) {
241 GetDefaultFileAndLine(tmp_spec, tmp_line);
244 if (m_last_file_sp) {
245 if (m_last_line == UINT32_MAX)
248 if (reverse && m_last_line == 1)
252 m_last_count = count;
253 else if (m_last_count == 0)
256 if (m_last_line > 0) {
258 // If this is the first time we've done a reverse, then back up one more
260 // up showing the chunk before the last one we've shown:
261 if (m_last_line > m_last_count)
262 m_last_line -= m_last_count;
265 } else if (have_default_file_line)
266 m_last_line += m_last_count;
270 const uint32_t column = 0;
271 return DisplaySourceLinesWithLineNumbersUsingLastFile(
272 m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);
277 bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,
279 FileSP old_file_sp = m_last_file_sp;
280 m_last_file_sp = GetFile(file_spec);
282 m_default_set = true;
283 if (m_last_file_sp) {
287 m_last_file_sp = old_file_sp;
292 bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {
293 if (m_last_file_sp) {
294 file_spec = m_last_file_sp->GetFileSpec();
297 } else if (!m_default_set) {
298 TargetSP target_sp(m_target_wp.lock());
301 // If nobody has set the default file and line then try here. If there's
302 // no executable, then we
303 // will try again later when there is one. Otherwise, if we can't find it
304 // we won't look again,
305 // somebody will have to set it (for instance when we stop somewhere...)
306 Module *executable_ptr = target_sp->GetExecutableModulePointer();
307 if (executable_ptr) {
308 SymbolContextList sc_list;
309 ConstString main_name("main");
310 bool symbols_okay = false; // Force it to be a debug symbol.
311 bool inlines_okay = true;
313 size_t num_matches = executable_ptr->FindFunctions(
314 main_name, NULL, lldb::eFunctionNameTypeBase, inlines_okay,
315 symbols_okay, append, sc_list);
316 for (size_t idx = 0; idx < num_matches; idx++) {
318 sc_list.GetContextAtIndex(idx, sc);
320 lldb_private::LineEntry line_entry;
321 if (sc.function->GetAddressRange()
323 .CalculateSymbolContextLineEntry(line_entry)) {
324 SetDefaultFileAndLine(line_entry.file, line_entry.line);
325 file_spec = m_last_file_sp->GetFileSpec();
337 void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
338 RegularExpression ®ex,
341 std::vector<uint32_t> &match_lines) {
343 FileSP file_sp = GetFile(file_spec);
346 return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
350 SourceManager::File::File(const FileSpec &file_spec,
351 lldb::DebuggerSP debugger_sp)
352 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
353 m_mod_time(FileSystem::GetModificationTime(file_spec)),
354 m_debugger_wp(debugger_sp) {
355 CommonInitializer(file_spec, nullptr);
358 SourceManager::File::File(const FileSpec &file_spec, Target *target)
359 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
360 m_mod_time(FileSystem::GetModificationTime(file_spec)),
361 m_debugger_wp(target ? target->GetDebugger().shared_from_this()
363 CommonInitializer(file_spec, target);
366 void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
368 if (m_mod_time == llvm::sys::TimePoint<>()) {
370 m_source_map_mod_id = target->GetSourcePathMap().GetModificationID();
372 if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
373 // If this is just a file name, lets see if we can find it in the
375 bool check_inlines = false;
376 SymbolContextList sc_list;
378 target->GetImages().ResolveSymbolContextForFilePath(
379 file_spec.GetFilename().AsCString(), 0, check_inlines,
380 lldb::eSymbolContextModule | lldb::eSymbolContextCompUnit,
382 bool got_multiple = false;
383 if (num_matches != 0) {
384 if (num_matches > 1) {
386 FileSpec *test_cu_spec = NULL;
388 for (unsigned i = 0; i < num_matches; i++) {
389 sc_list.GetContextAtIndex(i, sc);
392 if (test_cu_spec != static_cast<FileSpec *>(sc.comp_unit))
396 test_cu_spec = sc.comp_unit;
402 sc_list.GetContextAtIndex(0, sc);
403 m_file_spec = sc.comp_unit;
404 m_mod_time = FileSystem::GetModificationTime(m_file_spec);
408 // Try remapping if m_file_spec does not correspond to an existing file.
409 if (!m_file_spec.Exists()) {
410 FileSpec new_file_spec;
411 // Check target specific source remappings first, then fall back to
412 // modules objects can have individual path remappings that were
414 // when the debug info for a module was found.
416 if (target->GetSourcePathMap().FindFile(m_file_spec, new_file_spec) ||
417 target->GetImages().FindSourceFile(m_file_spec, new_file_spec)) {
418 m_file_spec = new_file_spec;
419 m_mod_time = FileSystem::GetModificationTime(m_file_spec);
425 if (m_mod_time != llvm::sys::TimePoint<>())
426 m_data_sp = DataBufferLLVM::CreateFromPath(m_file_spec.GetPath());
429 uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
436 if (CalculateLineOffsets(line)) {
437 if (line < m_offsets.size())
438 return m_offsets[line - 1]; // yes we want "line - 1" in the index
443 uint32_t SourceManager::File::GetNumLines() {
444 CalculateLineOffsets();
445 return m_offsets.size();
448 const char *SourceManager::File::PeekLineData(uint32_t line) {
449 if (!LineIsValid(line))
452 size_t line_offset = GetLineOffset(line);
453 if (line_offset < m_data_sp->GetByteSize())
454 return (const char *)m_data_sp->GetBytes() + line_offset;
458 uint32_t SourceManager::File::GetLineLength(uint32_t line,
459 bool include_newline_chars) {
460 if (!LineIsValid(line))
463 size_t start_offset = GetLineOffset(line);
464 size_t end_offset = GetLineOffset(line + 1);
465 if (end_offset == UINT32_MAX)
466 end_offset = m_data_sp->GetByteSize();
468 if (end_offset > start_offset) {
469 uint32_t length = end_offset - start_offset;
470 if (include_newline_chars == false) {
471 const char *line_start =
472 (const char *)m_data_sp->GetBytes() + start_offset;
474 const char last_char = line_start[length - 1];
475 if ((last_char == '\r') || (last_char == '\n'))
486 bool SourceManager::File::LineIsValid(uint32_t line) {
490 if (CalculateLineOffsets(line))
491 return line < m_offsets.size();
495 void SourceManager::File::UpdateIfNeeded() {
496 // TODO: use host API to sign up for file modifications to anything in our
497 // source cache and only update when we determine a file has been updated.
498 // For now we check each time we want to display info for the file.
499 auto curr_mod_time = FileSystem::GetModificationTime(m_file_spec);
501 if (curr_mod_time != llvm::sys::TimePoint<>() &&
502 m_mod_time != curr_mod_time) {
503 m_mod_time = curr_mod_time;
504 m_data_sp = DataBufferLLVM::CreateFromPath(m_file_spec.GetPath());
509 size_t SourceManager::File::DisplaySourceLines(uint32_t line, uint32_t column,
510 uint32_t context_before,
511 uint32_t context_after,
513 // Nothing to write if there's no stream.
517 // Sanity check m_data_sp before proceeding.
521 const uint32_t start_line =
522 line <= context_before ? 1 : line - context_before;
523 const uint32_t start_line_offset = GetLineOffset(start_line);
524 if (start_line_offset != UINT32_MAX) {
525 const uint32_t end_line = line + context_after;
526 uint32_t end_line_offset = GetLineOffset(end_line + 1);
527 if (end_line_offset == UINT32_MAX)
528 end_line_offset = m_data_sp->GetByteSize();
530 assert(start_line_offset <= end_line_offset);
531 size_t bytes_written = 0;
532 if (start_line_offset < end_line_offset) {
533 size_t count = end_line_offset - start_line_offset;
534 const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
536 bool displayed_line = false;
538 if (column && (column < count)) {
539 auto debugger_sp = m_debugger_wp.lock();
540 if (should_show_stop_column_with_ansi(debugger_sp) && debugger_sp) {
541 // Check if we have any ANSI codes with which to mark this column.
542 // If not, no need to do this work.
543 auto ansi_prefix_entry = debugger_sp->GetStopShowColumnAnsiPrefix();
544 auto ansi_suffix_entry = debugger_sp->GetStopShowColumnAnsiSuffix();
546 // We only bother breaking up the line to format the marked column if
547 // there is any marking specified on both sides of the marked column.
548 // In ANSI-terminal-sequence land, there must be a post if there is a
549 // pre format, and vice versa.
550 if (ansi_prefix_entry && ansi_suffix_entry) {
551 // Mark the current column with the desired escape sequence for
552 // formatting the column (e.g. underline, inverse, etc.)
554 // First print the part before the column to mark.
555 bytes_written = s->Write(cstr, column - 1);
557 // Write the pre escape sequence.
558 const SymbolContext *sc = nullptr;
559 const ExecutionContext *exe_ctx = nullptr;
560 const Address addr = LLDB_INVALID_ADDRESS;
561 ValueObject *valobj = nullptr;
562 const bool function_changed = false;
563 const bool initial_function = false;
565 FormatEntity::Format(*ansi_prefix_entry, *s, sc, exe_ctx, &addr,
566 valobj, function_changed, initial_function);
568 // Write the marked column.
569 bytes_written += s->Write(cstr + column - 1, 1);
571 // Write the post escape sequence.
572 FormatEntity::Format(*ansi_suffix_entry, *s, sc, exe_ctx, &addr,
573 valobj, function_changed, initial_function);
575 // And finish up with the rest of the line.
576 bytes_written += s->Write(cstr + column, count - column);
578 // Keep track of the fact that we just wrote the line.
579 displayed_line = true;
584 // If we didn't end up displaying the line with ANSI codes for whatever
585 // reason, display it now sans codes.
587 bytes_written = s->Write(cstr, count);
589 // Ensure we get an end of line character one way or another.
590 if (!is_newline_char(cstr[count - 1]))
591 bytes_written += s->EOL();
593 return bytes_written;
598 void SourceManager::File::FindLinesMatchingRegex(
599 RegularExpression ®ex, uint32_t start_line, uint32_t end_line,
600 std::vector<uint32_t> &match_lines) {
603 if (!LineIsValid(start_line) ||
604 (end_line != UINT32_MAX && !LineIsValid(end_line)))
606 if (start_line > end_line)
609 for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
611 if (!GetLine(line_no, buffer))
613 if (regex.Execute(buffer)) {
614 match_lines.push_back(line_no);
619 bool SourceManager::File::FileSpecMatches(const FileSpec &file_spec) {
620 return FileSpec::Equal(m_file_spec, file_spec, false);
623 bool lldb_private::operator==(const SourceManager::File &lhs,
624 const SourceManager::File &rhs) {
625 if (lhs.m_file_spec != rhs.m_file_spec)
627 return lhs.m_mod_time == rhs.m_mod_time;
630 bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
632 UINT32_MAX; // TODO: take this line out when we support partial indexing
633 if (line == UINT32_MAX) {
635 if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
638 if (m_offsets.empty()) {
639 if (m_data_sp.get() == NULL)
642 const char *start = (char *)m_data_sp->GetBytes();
644 const char *end = start + m_data_sp->GetByteSize();
646 // Calculate all line offsets from scratch
648 // Push a 1 at index zero to indicate the file has been completely
650 m_offsets.push_back(UINT32_MAX);
652 for (s = start; s < end; ++s) {
654 if (is_newline_char(curr_ch)) {
657 if (is_newline_char(next_ch)) {
658 if (curr_ch != next_ch)
662 m_offsets.push_back(s + 1 - start);
665 if (!m_offsets.empty()) {
666 if (m_offsets.back() < size_t(end - start))
667 m_offsets.push_back(end - start);
672 // Some lines have been populated, start where we last left off
673 assert("Not implemented yet" && false);
677 // Calculate all line offsets up to "line"
678 assert("Not implemented yet" && false);
683 bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
684 if (!LineIsValid(line_no))
687 size_t start_offset = GetLineOffset(line_no);
688 size_t end_offset = GetLineOffset(line_no + 1);
689 if (end_offset == UINT32_MAX) {
690 end_offset = m_data_sp->GetByteSize();
692 buffer.assign((char *)m_data_sp->GetBytes() + start_offset,
693 end_offset - start_offset);
698 void SourceManager::SourceFileCache::AddSourceFile(const FileSP &file_sp) {
700 FileCache::iterator pos = m_file_cache.find(file_spec);
701 if (pos == m_file_cache.end())
702 m_file_cache[file_spec] = file_sp;
704 if (file_sp != pos->second)
705 m_file_cache[file_spec] = file_sp;
709 SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
710 const FileSpec &file_spec) const {
712 FileCache::const_iterator pos = m_file_cache.find(file_spec);
713 if (pos != m_file_cache.end())
714 file_sp = pos->second;