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 it
113 // 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 we do
132 // 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
259 // more time so we end up showing the chunk before the last one we've
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 will try again later when there is one.
303 // Otherwise, if we can't find it we won't look again, somebody will have
304 // to set it (for instance when we stop somewhere...)
305 Module *executable_ptr = target_sp->GetExecutableModulePointer();
306 if (executable_ptr) {
307 SymbolContextList sc_list;
308 ConstString main_name("main");
309 bool symbols_okay = false; // Force it to be a debug symbol.
310 bool inlines_okay = true;
312 size_t num_matches = executable_ptr->FindFunctions(
313 main_name, NULL, lldb::eFunctionNameTypeBase, inlines_okay,
314 symbols_okay, append, sc_list);
315 for (size_t idx = 0; idx < num_matches; idx++) {
317 sc_list.GetContextAtIndex(idx, sc);
319 lldb_private::LineEntry line_entry;
320 if (sc.function->GetAddressRange()
322 .CalculateSymbolContextLineEntry(line_entry)) {
323 SetDefaultFileAndLine(line_entry.file, line_entry.line);
324 file_spec = m_last_file_sp->GetFileSpec();
336 void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
337 RegularExpression ®ex,
340 std::vector<uint32_t> &match_lines) {
342 FileSP file_sp = GetFile(file_spec);
345 return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
349 SourceManager::File::File(const FileSpec &file_spec,
350 lldb::DebuggerSP debugger_sp)
351 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
352 m_mod_time(FileSystem::GetModificationTime(file_spec)),
353 m_debugger_wp(debugger_sp) {
354 CommonInitializer(file_spec, nullptr);
357 SourceManager::File::File(const FileSpec &file_spec, Target *target)
358 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
359 m_mod_time(FileSystem::GetModificationTime(file_spec)),
360 m_debugger_wp(target ? target->GetDebugger().shared_from_this()
362 CommonInitializer(file_spec, target);
365 void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
367 if (m_mod_time == llvm::sys::TimePoint<>()) {
369 m_source_map_mod_id = target->GetSourcePathMap().GetModificationID();
371 if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
372 // If this is just a file name, lets see if we can find it in the
374 bool check_inlines = false;
375 SymbolContextList sc_list;
377 target->GetImages().ResolveSymbolContextForFilePath(
378 file_spec.GetFilename().AsCString(), 0, check_inlines,
379 lldb::eSymbolContextModule | lldb::eSymbolContextCompUnit,
381 bool got_multiple = false;
382 if (num_matches != 0) {
383 if (num_matches > 1) {
385 FileSpec *test_cu_spec = NULL;
387 for (unsigned i = 0; i < num_matches; i++) {
388 sc_list.GetContextAtIndex(i, sc);
391 if (test_cu_spec != static_cast<FileSpec *>(sc.comp_unit))
395 test_cu_spec = sc.comp_unit;
401 sc_list.GetContextAtIndex(0, sc);
402 m_file_spec = sc.comp_unit;
403 m_mod_time = FileSystem::GetModificationTime(m_file_spec);
407 // Try remapping if m_file_spec does not correspond to an existing file.
408 if (!m_file_spec.Exists()) {
409 FileSpec new_file_spec;
410 // Check target specific source remappings first, then fall back to
411 // modules objects can have individual path remappings that were
412 // detected when the debug info for a module was found. then
413 if (target->GetSourcePathMap().FindFile(m_file_spec, new_file_spec) ||
414 target->GetImages().FindSourceFile(m_file_spec, new_file_spec)) {
415 m_file_spec = new_file_spec;
416 m_mod_time = FileSystem::GetModificationTime(m_file_spec);
422 if (m_mod_time != llvm::sys::TimePoint<>())
423 m_data_sp = DataBufferLLVM::CreateFromPath(m_file_spec.GetPath());
426 uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
433 if (CalculateLineOffsets(line)) {
434 if (line < m_offsets.size())
435 return m_offsets[line - 1]; // yes we want "line - 1" in the index
440 uint32_t SourceManager::File::GetNumLines() {
441 CalculateLineOffsets();
442 return m_offsets.size();
445 const char *SourceManager::File::PeekLineData(uint32_t line) {
446 if (!LineIsValid(line))
449 size_t line_offset = GetLineOffset(line);
450 if (line_offset < m_data_sp->GetByteSize())
451 return (const char *)m_data_sp->GetBytes() + line_offset;
455 uint32_t SourceManager::File::GetLineLength(uint32_t line,
456 bool include_newline_chars) {
457 if (!LineIsValid(line))
460 size_t start_offset = GetLineOffset(line);
461 size_t end_offset = GetLineOffset(line + 1);
462 if (end_offset == UINT32_MAX)
463 end_offset = m_data_sp->GetByteSize();
465 if (end_offset > start_offset) {
466 uint32_t length = end_offset - start_offset;
467 if (include_newline_chars == false) {
468 const char *line_start =
469 (const char *)m_data_sp->GetBytes() + start_offset;
471 const char last_char = line_start[length - 1];
472 if ((last_char == '\r') || (last_char == '\n'))
483 bool SourceManager::File::LineIsValid(uint32_t line) {
487 if (CalculateLineOffsets(line))
488 return line < m_offsets.size();
492 void SourceManager::File::UpdateIfNeeded() {
493 // TODO: use host API to sign up for file modifications to anything in our
494 // source cache and only update when we determine a file has been updated.
495 // For now we check each time we want to display info for the file.
496 auto curr_mod_time = FileSystem::GetModificationTime(m_file_spec);
498 if (curr_mod_time != llvm::sys::TimePoint<>() &&
499 m_mod_time != curr_mod_time) {
500 m_mod_time = curr_mod_time;
501 m_data_sp = DataBufferLLVM::CreateFromPath(m_file_spec.GetPath());
506 size_t SourceManager::File::DisplaySourceLines(uint32_t line, uint32_t column,
507 uint32_t context_before,
508 uint32_t context_after,
510 // Nothing to write if there's no stream.
514 // Sanity check m_data_sp before proceeding.
518 const uint32_t start_line =
519 line <= context_before ? 1 : line - context_before;
520 const uint32_t start_line_offset = GetLineOffset(start_line);
521 if (start_line_offset != UINT32_MAX) {
522 const uint32_t end_line = line + context_after;
523 uint32_t end_line_offset = GetLineOffset(end_line + 1);
524 if (end_line_offset == UINT32_MAX)
525 end_line_offset = m_data_sp->GetByteSize();
527 assert(start_line_offset <= end_line_offset);
528 size_t bytes_written = 0;
529 if (start_line_offset < end_line_offset) {
530 size_t count = end_line_offset - start_line_offset;
531 const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
533 bool displayed_line = false;
535 if (column && (column < count)) {
536 auto debugger_sp = m_debugger_wp.lock();
537 if (should_show_stop_column_with_ansi(debugger_sp) && debugger_sp) {
538 // Check if we have any ANSI codes with which to mark this column. If
539 // not, no need to do this work.
540 auto ansi_prefix_entry = debugger_sp->GetStopShowColumnAnsiPrefix();
541 auto ansi_suffix_entry = debugger_sp->GetStopShowColumnAnsiSuffix();
543 // We only bother breaking up the line to format the marked column if
544 // there is any marking specified on both sides of the marked column.
545 // In ANSI-terminal-sequence land, there must be a post if there is a
546 // pre format, and vice versa.
547 if (ansi_prefix_entry && ansi_suffix_entry) {
548 // Mark the current column with the desired escape sequence for
549 // formatting the column (e.g. underline, inverse, etc.)
551 // First print the part before the column to mark.
552 bytes_written = s->Write(cstr, column - 1);
554 // Write the pre escape sequence.
555 const SymbolContext *sc = nullptr;
556 const ExecutionContext *exe_ctx = nullptr;
557 const Address addr = LLDB_INVALID_ADDRESS;
558 ValueObject *valobj = nullptr;
559 const bool function_changed = false;
560 const bool initial_function = false;
562 FormatEntity::Format(*ansi_prefix_entry, *s, sc, exe_ctx, &addr,
563 valobj, function_changed, initial_function);
565 // Write the marked column.
566 bytes_written += s->Write(cstr + column - 1, 1);
568 // Write the post escape sequence.
569 FormatEntity::Format(*ansi_suffix_entry, *s, sc, exe_ctx, &addr,
570 valobj, function_changed, initial_function);
572 // And finish up with the rest of the line.
573 bytes_written += s->Write(cstr + column, count - column);
575 // Keep track of the fact that we just wrote the line.
576 displayed_line = true;
581 // If we didn't end up displaying the line with ANSI codes for whatever
582 // reason, display it now sans codes.
584 bytes_written = s->Write(cstr, count);
586 // Ensure we get an end of line character one way or another.
587 if (!is_newline_char(cstr[count - 1]))
588 bytes_written += s->EOL();
590 return bytes_written;
595 void SourceManager::File::FindLinesMatchingRegex(
596 RegularExpression ®ex, uint32_t start_line, uint32_t end_line,
597 std::vector<uint32_t> &match_lines) {
600 if (!LineIsValid(start_line) ||
601 (end_line != UINT32_MAX && !LineIsValid(end_line)))
603 if (start_line > end_line)
606 for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
608 if (!GetLine(line_no, buffer))
610 if (regex.Execute(buffer)) {
611 match_lines.push_back(line_no);
616 bool SourceManager::File::FileSpecMatches(const FileSpec &file_spec) {
617 return FileSpec::Equal(m_file_spec, file_spec, false);
620 bool lldb_private::operator==(const SourceManager::File &lhs,
621 const SourceManager::File &rhs) {
622 if (lhs.m_file_spec != rhs.m_file_spec)
624 return lhs.m_mod_time == rhs.m_mod_time;
627 bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
629 UINT32_MAX; // TODO: take this line out when we support partial indexing
630 if (line == UINT32_MAX) {
632 if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
635 if (m_offsets.empty()) {
636 if (m_data_sp.get() == NULL)
639 const char *start = (char *)m_data_sp->GetBytes();
641 const char *end = start + m_data_sp->GetByteSize();
643 // Calculate all line offsets from scratch
645 // Push a 1 at index zero to indicate the file has been completely
647 m_offsets.push_back(UINT32_MAX);
649 for (s = start; s < end; ++s) {
651 if (is_newline_char(curr_ch)) {
654 if (is_newline_char(next_ch)) {
655 if (curr_ch != next_ch)
659 m_offsets.push_back(s + 1 - start);
662 if (!m_offsets.empty()) {
663 if (m_offsets.back() < size_t(end - start))
664 m_offsets.push_back(end - start);
669 // Some lines have been populated, start where we last left off
670 assert("Not implemented yet" && false);
674 // Calculate all line offsets up to "line"
675 assert("Not implemented yet" && false);
680 bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
681 if (!LineIsValid(line_no))
684 size_t start_offset = GetLineOffset(line_no);
685 size_t end_offset = GetLineOffset(line_no + 1);
686 if (end_offset == UINT32_MAX) {
687 end_offset = m_data_sp->GetByteSize();
689 buffer.assign((char *)m_data_sp->GetBytes() + start_offset,
690 end_offset - start_offset);
695 void SourceManager::SourceFileCache::AddSourceFile(const FileSP &file_sp) {
697 FileCache::iterator pos = m_file_cache.find(file_spec);
698 if (pos == m_file_cache.end())
699 m_file_cache[file_spec] = file_sp;
701 if (file_sp != pos->second)
702 m_file_cache[file_spec] = file_sp;
706 SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
707 const FileSpec &file_spec) const {
709 FileCache::const_iterator pos = m_file_cache.find(file_spec);
710 if (pos != m_file_cache.end())
711 file_sp = pos->second;