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"
13 #include "lldb/Core/AddressRange.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/FormatEntity.h"
16 #include "lldb/Core/Highlighter.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Host/FileSystem.h"
20 #include "lldb/Symbol/CompileUnit.h"
21 #include "lldb/Symbol/Function.h"
22 #include "lldb/Symbol/LineEntry.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Target/PathMappingList.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Utility/ConstString.h"
27 #include "lldb/Utility/DataBuffer.h"
28 #include "lldb/Utility/DataBufferLLVM.h"
29 #include "lldb/Utility/RegularExpression.h"
30 #include "lldb/Utility/Stream.h"
31 #include "lldb/lldb-enumerations.h"
33 #include "llvm/ADT/Twine.h"
41 namespace lldb_private {
42 class ExecutionContext;
44 namespace lldb_private {
49 using namespace lldb_private;
51 static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; }
53 //----------------------------------------------------------------------
54 // SourceManager constructor
55 //----------------------------------------------------------------------
56 SourceManager::SourceManager(const TargetSP &target_sp)
57 : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false),
58 m_target_wp(target_sp),
59 m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}
61 SourceManager::SourceManager(const DebuggerSP &debugger_sp)
62 : m_last_file_sp(), m_last_line(0), m_last_count(0), m_default_set(false),
63 m_target_wp(), m_debugger_wp(debugger_sp) {}
65 //----------------------------------------------------------------------
67 //----------------------------------------------------------------------
68 SourceManager::~SourceManager() {}
70 SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) {
71 bool same_as_previous =
72 m_last_file_sp && m_last_file_sp->FileSpecMatches(file_spec);
74 DebuggerSP debugger_sp(m_debugger_wp.lock());
77 file_sp = m_last_file_sp;
79 file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);
81 TargetSP target_sp(m_target_wp.lock());
83 // It the target source path map has been updated, get this file again so we
84 // can successfully remap the source file
85 if (target_sp && file_sp &&
86 file_sp->GetSourceMapModificationID() !=
87 target_sp->GetSourcePathMap().GetModificationID())
90 // Update the file contents if needed if we found a file
92 file_sp->UpdateIfNeeded();
94 // If file_sp is no good or it points to a non-existent file, reset it.
95 if (!file_sp || !FileSystem::Instance().Exists(file_sp->GetFileSpec())) {
97 file_sp = std::make_shared<File>(file_spec, target_sp.get());
99 file_sp = std::make_shared<File>(file_spec, debugger_sp);
102 debugger_sp->GetSourceFileCache().AddSourceFile(file_sp);
107 static bool should_highlight_source(DebuggerSP debugger_sp) {
111 // We don't use ANSI stop column formatting if the debugger doesn't think it
112 // should be using color.
113 if (!debugger_sp->GetUseColor())
116 return debugger_sp->GetHighlightSource();
119 static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {
120 // We don't use ANSI stop column formatting if we can't lookup values from
125 // We don't use ANSI stop column formatting if the debugger doesn't think it
126 // should be using color.
127 if (!debugger_sp->GetUseColor())
130 // We only use ANSI stop column formatting if we're either supposed to show
131 // ANSI where available (which we know we have when we get to this point), or
132 // if we're only supposed to use ANSI.
133 const auto value = debugger_sp->GetStopShowColumn();
134 return ((value == eStopShowColumnAnsiOrCaret) ||
135 (value == eStopShowColumnAnsi));
138 static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {
139 // We don't use text-based stop column formatting if we can't lookup values
140 // from the debugger.
144 // If we're asked to show the first available of ANSI or caret, then we do
145 // show the caret when ANSI is not available.
146 const auto value = debugger_sp->GetStopShowColumn();
147 if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())
150 // The only other time we use caret is if we're explicitly asked to show
152 return value == eStopShowColumnCaret;
155 size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(
156 uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,
157 const char *current_line_cstr, Stream *s,
158 const SymbolContextList *bp_locs) {
162 Stream::ByteDelta delta(*s);
164 if (start_line == 0) {
165 if (m_last_line != 0 && m_last_line != UINT32_MAX)
166 start_line = m_last_line + m_last_count;
171 if (!m_default_set) {
174 GetDefaultFileAndLine(tmp_spec, tmp_line);
177 m_last_line = start_line;
178 m_last_count = count;
180 if (m_last_file_sp.get()) {
181 const uint32_t end_line = start_line + count - 1;
182 for (uint32_t line = start_line; line <= end_line; ++line) {
183 if (!m_last_file_sp->LineIsValid(line)) {
184 m_last_line = UINT32_MAX;
188 char prefix[32] = "";
190 uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);
193 ::snprintf(prefix, sizeof(prefix), "[%u] ", bp_count);
195 ::snprintf(prefix, sizeof(prefix), " ");
198 s->Printf("%s%2.2s %-4u\t", prefix,
199 line == curr_line ? current_line_cstr : "", line);
201 // So far we treated column 0 as a special 'no column value', but
202 // DisplaySourceLines starts counting columns from 0 (and no column is
203 // expressed by passing an empty optional).
204 llvm::Optional<size_t> columnToHighlight;
205 if (line == curr_line && column)
206 columnToHighlight = column - 1;
208 size_t this_line_size =
209 m_last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);
210 if (column != 0 && line == curr_line &&
211 should_show_stop_column_with_caret(m_debugger_wp.lock())) {
212 // Display caret cursor.
213 std::string src_line;
214 m_last_file_sp->GetLine(line, src_line);
216 // Insert a space for every non-tab character in the source line.
217 for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)
218 s->PutChar(src_line[i] == '\t' ? '\t' : ' ');
219 // Now add the caret.
222 if (this_line_size == 0) {
223 m_last_line = UINT32_MAX;
231 size_t SourceManager::DisplaySourceLinesWithLineNumbers(
232 const FileSpec &file_spec, uint32_t line, uint32_t column,
233 uint32_t context_before, uint32_t context_after,
234 const char *current_line_cstr, Stream *s,
235 const SymbolContextList *bp_locs) {
236 FileSP file_sp(GetFile(file_spec));
239 uint32_t count = context_before + context_after + 1;
240 if (line > context_before)
241 start_line = line - context_before;
245 if (m_last_file_sp.get() != file_sp.get()) {
248 m_last_file_sp = file_sp;
250 return DisplaySourceLinesWithLineNumbersUsingLastFile(
251 start_line, count, line, column, current_line_cstr, s, bp_locs);
254 size_t SourceManager::DisplayMoreWithLineNumbers(
255 Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {
256 // If we get called before anybody has set a default file and line, then try
257 // to figure it out here.
258 const bool have_default_file_line = m_last_file_sp && m_last_line > 0;
259 if (!m_default_set) {
262 GetDefaultFileAndLine(tmp_spec, tmp_line);
265 if (m_last_file_sp) {
266 if (m_last_line == UINT32_MAX)
269 if (reverse && m_last_line == 1)
273 m_last_count = count;
274 else if (m_last_count == 0)
277 if (m_last_line > 0) {
279 // If this is the first time we've done a reverse, then back up one
280 // more time so we end up showing the chunk before the last one we've
282 if (m_last_line > m_last_count)
283 m_last_line -= m_last_count;
286 } else if (have_default_file_line)
287 m_last_line += m_last_count;
291 const uint32_t column = 0;
292 return DisplaySourceLinesWithLineNumbersUsingLastFile(
293 m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);
298 bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,
300 FileSP old_file_sp = m_last_file_sp;
301 m_last_file_sp = GetFile(file_spec);
303 m_default_set = true;
304 if (m_last_file_sp) {
308 m_last_file_sp = old_file_sp;
313 bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {
314 if (m_last_file_sp) {
315 file_spec = m_last_file_sp->GetFileSpec();
318 } else if (!m_default_set) {
319 TargetSP target_sp(m_target_wp.lock());
322 // If nobody has set the default file and line then try here. If there's
323 // no executable, then we will try again later when there is one.
324 // Otherwise, if we can't find it we won't look again, somebody will have
325 // to set it (for instance when we stop somewhere...)
326 Module *executable_ptr = target_sp->GetExecutableModulePointer();
327 if (executable_ptr) {
328 SymbolContextList sc_list;
329 ConstString main_name("main");
330 bool symbols_okay = false; // Force it to be a debug symbol.
331 bool inlines_okay = true;
333 size_t num_matches = executable_ptr->FindFunctions(
334 main_name, NULL, lldb::eFunctionNameTypeBase, inlines_okay,
335 symbols_okay, append, sc_list);
336 for (size_t idx = 0; idx < num_matches; idx++) {
338 sc_list.GetContextAtIndex(idx, sc);
340 lldb_private::LineEntry line_entry;
341 if (sc.function->GetAddressRange()
343 .CalculateSymbolContextLineEntry(line_entry)) {
344 SetDefaultFileAndLine(line_entry.file, line_entry.line);
345 file_spec = m_last_file_sp->GetFileSpec();
357 void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
358 RegularExpression ®ex,
361 std::vector<uint32_t> &match_lines) {
363 FileSP file_sp = GetFile(file_spec);
366 return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
370 SourceManager::File::File(const FileSpec &file_spec,
371 lldb::DebuggerSP debugger_sp)
372 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
373 m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
374 m_debugger_wp(debugger_sp) {
375 CommonInitializer(file_spec, nullptr);
378 SourceManager::File::File(const FileSpec &file_spec, Target *target)
379 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
380 m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
381 m_debugger_wp(target ? target->GetDebugger().shared_from_this()
383 CommonInitializer(file_spec, target);
386 void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
388 if (m_mod_time == llvm::sys::TimePoint<>()) {
390 m_source_map_mod_id = target->GetSourcePathMap().GetModificationID();
392 if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
393 // If this is just a file name, lets see if we can find it in the
395 bool check_inlines = false;
396 SymbolContextList sc_list;
398 target->GetImages().ResolveSymbolContextForFilePath(
399 file_spec.GetFilename().AsCString(), 0, check_inlines,
400 SymbolContextItem(eSymbolContextModule |
401 eSymbolContextCompUnit),
403 bool got_multiple = false;
404 if (num_matches != 0) {
405 if (num_matches > 1) {
407 FileSpec *test_cu_spec = NULL;
409 for (unsigned i = 0; i < num_matches; i++) {
410 sc_list.GetContextAtIndex(i, sc);
413 if (test_cu_spec != static_cast<FileSpec *>(sc.comp_unit))
417 test_cu_spec = sc.comp_unit;
423 sc_list.GetContextAtIndex(0, sc);
424 m_file_spec = sc.comp_unit;
425 m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
429 // Try remapping if m_file_spec does not correspond to an existing file.
430 if (!FileSystem::Instance().Exists(m_file_spec)) {
431 FileSpec new_file_spec;
432 // Check target specific source remappings first, then fall back to
433 // modules objects can have individual path remappings that were
434 // detected when the debug info for a module was found. then
435 if (target->GetSourcePathMap().FindFile(m_file_spec, new_file_spec) ||
436 target->GetImages().FindSourceFile(m_file_spec, new_file_spec)) {
437 m_file_spec = new_file_spec;
438 m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
444 if (m_mod_time != llvm::sys::TimePoint<>())
445 m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
448 uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
455 if (CalculateLineOffsets(line)) {
456 if (line < m_offsets.size())
457 return m_offsets[line - 1]; // yes we want "line - 1" in the index
462 uint32_t SourceManager::File::GetNumLines() {
463 CalculateLineOffsets();
464 return m_offsets.size();
467 const char *SourceManager::File::PeekLineData(uint32_t line) {
468 if (!LineIsValid(line))
471 size_t line_offset = GetLineOffset(line);
472 if (line_offset < m_data_sp->GetByteSize())
473 return (const char *)m_data_sp->GetBytes() + line_offset;
477 uint32_t SourceManager::File::GetLineLength(uint32_t line,
478 bool include_newline_chars) {
479 if (!LineIsValid(line))
482 size_t start_offset = GetLineOffset(line);
483 size_t end_offset = GetLineOffset(line + 1);
484 if (end_offset == UINT32_MAX)
485 end_offset = m_data_sp->GetByteSize();
487 if (end_offset > start_offset) {
488 uint32_t length = end_offset - start_offset;
489 if (!include_newline_chars) {
490 const char *line_start =
491 (const char *)m_data_sp->GetBytes() + start_offset;
493 const char last_char = line_start[length - 1];
494 if ((last_char == '\r') || (last_char == '\n'))
505 bool SourceManager::File::LineIsValid(uint32_t line) {
509 if (CalculateLineOffsets(line))
510 return line < m_offsets.size();
514 void SourceManager::File::UpdateIfNeeded() {
515 // TODO: use host API to sign up for file modifications to anything in our
516 // source cache and only update when we determine a file has been updated.
517 // For now we check each time we want to display info for the file.
518 auto curr_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
520 if (curr_mod_time != llvm::sys::TimePoint<>() &&
521 m_mod_time != curr_mod_time) {
522 m_mod_time = curr_mod_time;
523 m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
528 size_t SourceManager::File::DisplaySourceLines(uint32_t line,
529 llvm::Optional<size_t> column,
530 uint32_t context_before,
531 uint32_t context_after,
533 // Nothing to write if there's no stream.
537 // Sanity check m_data_sp before proceeding.
541 size_t bytes_written = s->GetWrittenBytes();
543 auto debugger_sp = m_debugger_wp.lock();
545 HighlightStyle style;
546 // Use the default Vim style if source highlighting is enabled.
547 if (should_highlight_source(debugger_sp))
548 style = HighlightStyle::MakeVimStyle();
550 // If we should mark the stop column with color codes, then copy the prefix
551 // and suffix to our color style.
552 if (should_show_stop_column_with_ansi(debugger_sp))
553 style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),
554 debugger_sp->GetStopShowColumnAnsiSuffix());
556 HighlighterManager mgr;
557 std::string path = GetFileSpec().GetPath(/*denormalize*/ false);
558 // FIXME: Find a way to get the definitive language this file was written in
559 // and pass it to the highlighter.
560 const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);
562 const uint32_t start_line =
563 line <= context_before ? 1 : line - context_before;
564 const uint32_t start_line_offset = GetLineOffset(start_line);
565 if (start_line_offset != UINT32_MAX) {
566 const uint32_t end_line = line + context_after;
567 uint32_t end_line_offset = GetLineOffset(end_line + 1);
568 if (end_line_offset == UINT32_MAX)
569 end_line_offset = m_data_sp->GetByteSize();
571 assert(start_line_offset <= end_line_offset);
572 if (start_line_offset < end_line_offset) {
573 size_t count = end_line_offset - start_line_offset;
574 const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
576 auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);
578 h.Highlight(style, ref, column, "", *s);
580 // Ensure we get an end of line character one way or another.
581 if (!is_newline_char(ref.back()))
585 return s->GetWrittenBytes() - bytes_written;
588 void SourceManager::File::FindLinesMatchingRegex(
589 RegularExpression ®ex, uint32_t start_line, uint32_t end_line,
590 std::vector<uint32_t> &match_lines) {
593 if (!LineIsValid(start_line) ||
594 (end_line != UINT32_MAX && !LineIsValid(end_line)))
596 if (start_line > end_line)
599 for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
601 if (!GetLine(line_no, buffer))
603 if (regex.Execute(buffer)) {
604 match_lines.push_back(line_no);
609 bool SourceManager::File::FileSpecMatches(const FileSpec &file_spec) {
610 return FileSpec::Equal(m_file_spec, file_spec, false);
613 bool lldb_private::operator==(const SourceManager::File &lhs,
614 const SourceManager::File &rhs) {
615 if (lhs.m_file_spec != rhs.m_file_spec)
617 return lhs.m_mod_time == rhs.m_mod_time;
620 bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
622 UINT32_MAX; // TODO: take this line out when we support partial indexing
623 if (line == UINT32_MAX) {
625 if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
628 if (m_offsets.empty()) {
629 if (m_data_sp.get() == NULL)
632 const char *start = (char *)m_data_sp->GetBytes();
634 const char *end = start + m_data_sp->GetByteSize();
636 // Calculate all line offsets from scratch
638 // Push a 1 at index zero to indicate the file has been completely
640 m_offsets.push_back(UINT32_MAX);
642 for (s = start; s < end; ++s) {
644 if (is_newline_char(curr_ch)) {
647 if (is_newline_char(next_ch)) {
648 if (curr_ch != next_ch)
652 m_offsets.push_back(s + 1 - start);
655 if (!m_offsets.empty()) {
656 if (m_offsets.back() < size_t(end - start))
657 m_offsets.push_back(end - start);
662 // Some lines have been populated, start where we last left off
663 assert("Not implemented yet" && false);
667 // Calculate all line offsets up to "line"
668 assert("Not implemented yet" && false);
673 bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
674 if (!LineIsValid(line_no))
677 size_t start_offset = GetLineOffset(line_no);
678 size_t end_offset = GetLineOffset(line_no + 1);
679 if (end_offset == UINT32_MAX) {
680 end_offset = m_data_sp->GetByteSize();
682 buffer.assign((char *)m_data_sp->GetBytes() + start_offset,
683 end_offset - start_offset);
688 void SourceManager::SourceFileCache::AddSourceFile(const FileSP &file_sp) {
690 FileCache::iterator pos = m_file_cache.find(file_spec);
691 if (pos == m_file_cache.end())
692 m_file_cache[file_spec] = file_sp;
694 if (file_sp != pos->second)
695 m_file_cache[file_spec] = file_sp;
699 SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
700 const FileSpec &file_spec) const {
702 FileCache::const_iterator pos = m_file_cache.find(file_spec);
703 if (pos != m_file_cache.end())
704 file_sp = pos->second;