LLDB mainline
SourceManager.cpp
Go to the documentation of this file.
1//===-- SourceManager.cpp -------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "lldb/Core/Address.h"
13#include "lldb/Core/Debugger.h"
16#include "lldb/Core/Module.h"
24#include "lldb/Target/Process.h"
25#include "lldb/Target/Target.h"
30#include "lldb/Utility/Log.h"
32#include "lldb/Utility/Stream.h"
35
36#include "llvm/ADT/Twine.h"
37
38#include <future>
39#include <memory>
40#include <optional>
41#include <utility>
42
43#include <cassert>
44#include <cstdio>
45
46namespace lldb_private {
48}
49namespace lldb_private {
50class ValueObject;
51}
52
53using namespace lldb;
54using namespace lldb_private;
55
56static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; }
57
58static void resolve_tilde(FileSpec &file_spec) {
59 if (!FileSystem::Instance().Exists(file_spec) && file_spec.GetDirectory() &&
60 file_spec.GetDirectory().GetCString()[0] == '~') {
61 FileSystem::Instance().Resolve(file_spec);
62 }
63}
64
65static std::string toString(const Checksum &checksum) {
66 if (!checksum)
67 return "";
68 return std::string(llvm::formatv("{0}", checksum.digest()));
69}
70
71// SourceManager constructor
73 : m_last_support_file_nsp(std::make_shared<SupportFile>()), m_last_line(0),
74 m_last_count(0), m_default_set(false), m_target_wp(target_sp),
75 m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}
76
78 : m_last_support_file_nsp(std::make_shared<SupportFile>()), m_last_line(0),
79 m_last_count(0), m_default_set(false), m_target_wp(),
80 m_debugger_wp(debugger_sp) {}
81
82// Destructor
84
86 FileSpec file_spec = support_file_nsp->GetSpecOnly();
87 if (!file_spec)
88 return {};
89
91
92 DebuggerSP debugger_sp(m_debugger_wp.lock());
93 TargetSP target_sp(m_target_wp.lock());
94
95 if (!debugger_sp || !debugger_sp->GetUseSourceCache()) {
96 LLDB_LOG(log, "Source file caching disabled: creating new source file: {0}",
97 file_spec);
98 if (target_sp)
99 return std::make_shared<File>(support_file_nsp, target_sp);
100 return std::make_shared<File>(support_file_nsp, debugger_sp);
101 }
102
103 ProcessSP process_sp = target_sp ? target_sp->GetProcessSP() : ProcessSP();
104
105 // Check the process source cache first. This is the fast path which avoids
106 // touching the file system unless the path remapping has changed.
107 if (process_sp) {
108 if (FileSP file_sp =
109 process_sp->GetSourceFileCache().FindSourceFile(file_spec)) {
110 LLDB_LOG(log, "Found source file in the process cache: {0}", file_spec);
111 if (file_sp->PathRemappingIsStale()) {
112 LLDB_LOG(log, "Path remapping is stale: removing file from caches: {0}",
113 file_spec);
114
115 // Remove the file from the debugger and process cache. Otherwise we'll
116 // hit the same issue again below when querying the debugger cache.
117 debugger_sp->GetSourceFileCache().RemoveSourceFile(file_sp);
118 process_sp->GetSourceFileCache().RemoveSourceFile(file_sp);
119
120 file_sp.reset();
121 } else {
122 return file_sp;
123 }
124 }
125 }
126
127 // Cache miss in the process cache. Check the debugger source cache.
128 FileSP file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);
129
130 // We found the file in the debugger cache. Check if anything invalidated our
131 // cache result.
132 if (file_sp)
133 LLDB_LOG(log, "Found source file in the debugger cache: {0}", file_spec);
134
135 // Check if the path remapping has changed.
136 if (file_sp && file_sp->PathRemappingIsStale()) {
137 LLDB_LOG(log, "Path remapping is stale: {0}", file_spec);
138 file_sp.reset();
139 }
140
141 // Check if the modification time has changed.
142 if (file_sp && file_sp->ModificationTimeIsStale()) {
143 LLDB_LOG(log, "Modification time is stale: {0}", file_spec);
144 file_sp.reset();
145 }
146
147 // Check if the file exists on disk.
148 if (file_sp && !FileSystem::Instance().Exists(
149 file_sp->GetSupportFile()->GetSpecOnly())) {
150 LLDB_LOG(log, "File doesn't exist on disk: {0}", file_spec);
151 file_sp.reset();
152 }
153
154 // If at this point we don't have a valid file, it means we either didn't find
155 // it in the debugger cache or something caused it to be invalidated.
156 if (!file_sp) {
157 LLDB_LOG(log, "Creating and caching new source file: {0}", file_spec);
158
159 // (Re)create the file.
160 if (target_sp)
161 file_sp = std::make_shared<File>(support_file_nsp, target_sp);
162 else
163 file_sp = std::make_shared<File>(support_file_nsp, debugger_sp);
164
165 // Add the file to the debugger and process cache. If the file was
166 // invalidated, this will overwrite it.
167 debugger_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);
168 if (process_sp)
169 process_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);
170 }
171
172 return file_sp;
173}
174
175static bool should_highlight_source(DebuggerSP debugger_sp) {
176 if (!debugger_sp)
177 return false;
178
179 // We don't use ANSI stop column formatting if the debugger doesn't think it
180 // should be using color.
181 if (!debugger_sp->GetUseColor())
182 return false;
183
184 return debugger_sp->GetHighlightSource();
185}
186
188 // We don't use ANSI stop column formatting if we can't lookup values from
189 // the debugger.
190 if (!debugger_sp)
191 return false;
192
193 // We don't use ANSI stop column formatting if the debugger doesn't think it
194 // should be using color.
195 if (!debugger_sp->GetUseColor())
196 return false;
197
198 // We only use ANSI stop column formatting if we're either supposed to show
199 // ANSI where available (which we know we have when we get to this point), or
200 // if we're only supposed to use ANSI.
201 const auto value = debugger_sp->GetStopShowColumn();
202 return ((value == eStopShowColumnAnsiOrCaret) ||
203 (value == eStopShowColumnAnsi));
204}
205
207 // We don't use text-based stop column formatting if we can't lookup values
208 // from the debugger.
209 if (!debugger_sp)
210 return false;
211
212 // If we're asked to show the first available of ANSI or caret, then we do
213 // show the caret when ANSI is not available.
214 const auto value = debugger_sp->GetStopShowColumn();
215 if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())
216 return true;
217
218 // The only other time we use caret is if we're explicitly asked to show
219 // caret.
220 return value == eStopShowColumnCaret;
221}
222
224 return debugger_sp && debugger_sp->GetUseColor();
225}
226
228 uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,
229 const char *current_line_cstr, Stream *s, const SymbolContextList *bp_locs,
230 lldb::LanguageType language_type) {
231 if (count == 0)
232 return 0;
233
234 Stream::ByteDelta delta(*s);
235
236 if (start_line == 0) {
237 if (m_last_line != 0 && m_last_line != UINT32_MAX)
238 start_line = m_last_line + m_last_count;
239 else
240 start_line = 1;
241 }
242
243 if (!m_default_set)
245
246 m_last_line = start_line;
247 m_last_count = count;
248
249 if (FileSP last_file_sp = GetLastFile()) {
250 const uint32_t end_line = start_line + count - 1;
251 for (uint32_t line = start_line; line <= end_line; ++line) {
252 if (!last_file_sp->LineIsValid(line)) {
254 break;
255 }
256
257 std::string prefix;
258 if (bp_locs) {
259 uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);
260
261 if (bp_count > 0)
262 prefix = llvm::formatv("[{0}]", bp_count);
263 else
264 prefix = " ";
265 }
266
267 char buffer[3];
268 snprintf(buffer, sizeof(buffer), "%2.2s",
269 (line == curr_line) ? current_line_cstr : "");
270 std::string current_line_highlight(buffer);
271
272 auto debugger_sp = m_debugger_wp.lock();
273 if (should_show_stop_line_with_ansi(debugger_sp)) {
274 current_line_highlight = ansi::FormatAnsiTerminalCodes(
275 (debugger_sp->GetStopShowLineMarkerAnsiPrefix() +
276 current_line_highlight +
277 debugger_sp->GetStopShowLineMarkerAnsiSuffix())
278 .str());
279 }
280
281 s->Printf("%s%s %-4u\t", prefix.c_str(), current_line_highlight.c_str(),
282 line);
283
284 // So far we treated column 0 as a special 'no column value', but
285 // DisplaySourceLines starts counting columns from 0 (and no column is
286 // expressed by passing an empty optional).
287 std::optional<size_t> columnToHighlight;
288 if (line == curr_line && column)
289 columnToHighlight = column - 1;
290
291 size_t this_line_size = last_file_sp->DisplaySourceLines(
292 line, columnToHighlight, 0, 0, s, language_type);
293 if (column != 0 && line == curr_line &&
295 // Display caret cursor.
296 std::string src_line;
297 last_file_sp->GetLine(line, src_line);
298 s->Printf(" \t");
299 // Insert a space for every non-tab character in the source line.
300 for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)
301 s->PutChar(src_line[i] == '\t' ? '\t' : ' ');
302 // Now add the caret.
303 s->Printf("^\n");
304 }
305 if (this_line_size == 0) {
307 break;
308 }
309 }
310
311 Checksum line_table_checksum =
312 last_file_sp->GetSupportFile()->GetChecksum();
313 Checksum on_disk_checksum = last_file_sp->GetChecksum();
314 if (line_table_checksum && line_table_checksum != on_disk_checksum)
316 llvm::formatv(
317 "{0}: source file checksum mismatch between line table "
318 "({1}) and file on disk ({2})",
319 last_file_sp->GetSupportFile()->GetSpecOnly().GetFilename(),
320 toString(line_table_checksum), toString(on_disk_checksum)),
321 std::nullopt, &last_file_sp->GetChecksumWarningOnceFlag());
322 }
323 return *delta;
324}
325
327 SupportFileNSP support_file_nsp, uint32_t line, uint32_t column,
328 uint32_t context_before, uint32_t context_after,
329 const char *current_line_cstr, Stream *s, const SymbolContextList *bp_locs,
330 lldb::LanguageType language_type) {
331 assert(support_file_nsp && "SupportFile must be valid");
332 FileSP file_sp(GetFile(support_file_nsp));
333
334 uint32_t start_line;
335 uint32_t count = context_before + context_after + 1;
336 if (line > context_before)
337 start_line = line - context_before;
338 else
339 start_line = 1;
340
341 FileSP last_file_sp(GetLastFile());
342 if (last_file_sp.get() != file_sp.get()) {
343 if (line == 0)
344 m_last_line = 0;
345 m_last_support_file_nsp = support_file_nsp;
346 }
347
349 start_line, count, line, column, current_line_cstr, s, bp_locs,
350 language_type);
351}
352
354 Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs,
355 lldb::LanguageType language_type) {
356 // If we get called before anybody has set a default file and line, then try
357 // to figure it out here.
358 FileSP last_file_sp(GetLastFile());
359 const bool have_default_file_line = last_file_sp && m_last_line > 0;
360 if (!m_default_set)
362
363 if (last_file_sp) {
364 if (AtLastLine(reverse))
365 return 0;
366
367 if (count > 0)
368 m_last_count = count;
369 else if (m_last_count == 0)
370 m_last_count = 10;
371
372 if (m_last_line > 0) {
373 if (reverse) {
374 // If this is the first time we've done a reverse, then back up one
375 // more time so we end up showing the chunk before the last one we've
376 // shown:
379 else
380 m_last_line = 1;
381 } else if (have_default_file_line)
383 } else
384 m_last_line = 1;
385
386 const uint32_t column = 0;
388 m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs,
389 language_type);
390 }
391 return 0;
392}
393
395 uint32_t line) {
396 assert(support_file_nsp && "SupportFile must be valid");
397
398 m_default_set = true;
399
400 if (FileSP file_sp = GetFile(support_file_nsp)) {
401 m_last_line = line;
402 m_last_support_file_nsp = support_file_nsp;
403 return true;
404 }
405
406 return false;
407}
408
409std::optional<SourceManager::SupportFileAndLine>
411 if (FileSP last_file_sp = GetLastFile())
413
414 if (!m_default_set) {
415 TargetSP target_sp(m_target_wp.lock());
416
417 if (target_sp) {
418 // If nobody has set the default file and line then try here. If there's
419 // no executable, then we will try again later when there is one.
420 // Otherwise, if we can't find it we won't look again, somebody will have
421 // to set it (for instance when we stop somewhere...)
422 Module *executable_ptr = target_sp->GetExecutableModulePointer();
423 if (executable_ptr) {
424 SymbolContextList sc_list;
425 ConstString main_name("main");
426
427 ModuleFunctionSearchOptions function_options;
428 function_options.include_symbols =
429 false; // Force it to be a debug symbol.
430 function_options.include_inlines = true;
431 executable_ptr->FindFunctions(main_name, CompilerDeclContext(),
432 lldb::eFunctionNameTypeFull,
433 function_options, sc_list);
434 for (const SymbolContext &sc : sc_list) {
435 if (sc.function) {
436 lldb_private::LineEntry line_entry;
437 if (sc.function->GetAddress().CalculateSymbolContextLineEntry(
438 line_entry)) {
439 SetDefaultFileAndLine(line_entry.file_sp, line_entry.line);
440 return SupportFileAndLine(line_entry.file_sp, m_last_line);
441 }
442 }
443 }
444 }
445 }
446 }
447
448 return std::nullopt;
449}
450
452 RegularExpression &regex,
453 uint32_t start_line,
454 uint32_t end_line,
455 std::vector<uint32_t> &match_lines) {
456 match_lines.clear();
457 FileSP file_sp = GetFile(support_file_nsp);
458 if (!file_sp)
459 return;
460 return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
461 match_lines);
462}
463
465 lldb::DebuggerSP debugger_sp)
466 : m_support_file_nsp(std::make_shared<SupportFile>()), m_checksum(),
467 m_mod_time(), m_debugger_wp(debugger_sp), m_target_wp(TargetSP()) {
468 CommonInitializer(support_file_nsp, {});
469}
470
471SourceManager::File::File(SupportFileNSP support_file_nsp, TargetSP target_sp)
472 : m_support_file_nsp(std::make_shared<SupportFile>()), m_checksum(),
473 m_mod_time(),
474 m_debugger_wp(target_sp ? target_sp->GetDebugger().shared_from_this()
475 : DebuggerSP()),
476 m_target_wp(target_sp) {
477 CommonInitializer(support_file_nsp, target_sp);
478}
479
481 TargetSP target_sp) {
482 // It might take a while to read a source file, for example because it's
483 // coming from a virtual file system that's fetching the data on demand. When
484 // reading the data exceeds a certain threshold, show a progress event to let
485 // the user know what's going on.
486 static constexpr auto g_progress_delay = std::chrono::milliseconds(500);
487
488 std::future<void> future = std::async(std::launch::async, [=]() {
489 CommonInitializerImpl(support_file_nsp, target_sp);
490 });
491
492 std::optional<Progress> progress;
493 if (future.wait_for(g_progress_delay) == std::future_status::timeout) {
494 Debugger *debugger = target_sp ? &target_sp->GetDebugger() : nullptr;
495 progress.emplace("Loading source file",
496 support_file_nsp->GetSpecOnly().GetFilename().GetString(),
497 1, debugger);
498 }
499 future.wait();
500}
501
503 TargetSP target_sp) {
504 // Set the file and update the modification time.
505 SetSupportFile(support_file_nsp);
506
507 // Always update the source map modification ID if we have a target.
508 if (target_sp)
509 m_source_map_mod_id = target_sp->GetSourcePathMap().GetModificationID();
510
511 // File doesn't exist.
512 if (m_mod_time == llvm::sys::TimePoint<>()) {
513 if (target_sp) {
514 // If this is just a file name, try finding it in the target.
515 {
516 FileSpec file_spec = support_file_nsp->GetSpecOnly();
517 if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
518 bool check_inlines = false;
519 SymbolContextList sc_list;
520 size_t num_matches =
521 target_sp->GetImages().ResolveSymbolContextForFilePath(
522 file_spec.GetFilename().AsCString(nullptr), 0, check_inlines,
523 SymbolContextItem(eSymbolContextModule |
524 eSymbolContextCompUnit),
525 sc_list);
526 bool got_multiple = false;
527 if (num_matches != 0) {
528 if (num_matches > 1) {
529 CompileUnit *test_cu = nullptr;
530 for (const SymbolContext &sc : sc_list) {
531 if (sc.comp_unit) {
532 if (test_cu) {
533 if (test_cu != sc.comp_unit)
534 got_multiple = true;
535 break;
536 } else
537 test_cu = sc.comp_unit;
538 }
539 }
540 }
541 if (!got_multiple) {
542 SymbolContext sc;
543 sc_list.GetContextAtIndex(0, sc);
544 if (sc.comp_unit)
546 }
547 }
548 }
549 }
550
551 // Try remapping the file if it doesn't exist.
552 {
553 FileSpec file_spec = support_file_nsp->GetSpecOnly();
554 if (!FileSystem::Instance().Exists(file_spec)) {
555 // Check target specific source remappings (i.e., the
556 // target.source-map setting), then fall back to the module
557 // specific remapping (i.e., the .dSYM remapping dictionary).
558 auto remapped = target_sp->GetSourcePathMap().FindFile(file_spec);
559 if (!remapped) {
560 FileSpec new_spec;
561 if (target_sp->GetImages().FindSourceFile(file_spec, new_spec))
562 remapped = new_spec;
563 }
564 if (remapped)
565 SetSupportFile(std::make_shared<SupportFile>(
566 *remapped, support_file_nsp->GetChecksum()));
567 }
568 }
569 }
570 }
571
572 // If the file exists, read in the data.
573 if (m_mod_time != llvm::sys::TimePoint<>()) {
575 m_support_file_nsp->GetSpecOnly());
576 // Even if we have a valid modification time, reading the data might fail.
577 // Use the checksum from the line entry so we don't show a checksum
578 // mismatch.
579 m_checksum = m_data_sp ? llvm::MD5::hash(m_data_sp->GetData())
580 : m_support_file_nsp->GetChecksum();
581 }
582}
583
585 // Use Materialize here to allow for the possibility of support files
586 // that may have special semantics for "generating" a file spec from
587 // a support file (e.g., DWARF with embedded source through
588 // DW_LNCT_LLVM_source).
589 FileSpec file_spec = support_file_nsp->Materialize();
590
591 resolve_tilde(file_spec);
593 std::make_shared<SupportFile>(file_spec, support_file_nsp->GetChecksum());
595}
596
597uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
598 if (line == 0)
599 return UINT32_MAX;
600
601 if (line == 1)
602 return 0;
603
604 if (CalculateLineOffsets(line)) {
605 if (line < m_offsets.size())
606 return m_offsets[line - 1]; // yes we want "line - 1" in the index
607 }
608 return UINT32_MAX;
609}
610
613 return m_offsets.size();
614}
615
616const char *SourceManager::File::PeekLineData(uint32_t line) {
617 if (!LineIsValid(line))
618 return nullptr;
619
620 assert(m_data_sp);
621
622 size_t line_offset = GetLineOffset(line);
623 if (line_offset < m_data_sp->GetByteSize())
624 return (const char *)m_data_sp->GetBytes() + line_offset;
625 return nullptr;
626}
627
629 bool include_newline_chars) {
630 if (!LineIsValid(line))
631 return false;
632
633 assert(m_data_sp);
634
635 size_t start_offset = GetLineOffset(line);
636 size_t end_offset = GetLineOffset(line + 1);
637 if (end_offset == UINT32_MAX)
638 end_offset = m_data_sp->GetByteSize();
639
640 if (end_offset > start_offset) {
641 uint32_t length = end_offset - start_offset;
642 if (!include_newline_chars) {
643 const char *line_start =
644 (const char *)m_data_sp->GetBytes() + start_offset;
645 while (length > 0) {
646 const char last_char = line_start[length - 1];
647 if ((last_char == '\r') || (last_char == '\n'))
648 --length;
649 else
650 break;
651 }
652 }
653 return length;
654 }
655 return 0;
656}
657
659 if (line == 0)
660 return false;
661
662 if (CalculateLineOffsets(line))
663 return line < m_offsets.size();
664 return false;
665}
666
668 // TODO: use host API to sign up for file modifications to anything in our
669 // source cache and only update when we determine a file has been updated.
670 // For now we check each time we want to display info for the file.
671 auto curr_mod_time = FileSystem::Instance().GetModificationTime(
672 m_support_file_nsp->GetSpecOnly());
673 return curr_mod_time != llvm::sys::TimePoint<>() &&
674 m_mod_time != curr_mod_time;
675}
676
678 if (TargetSP target_sp = m_target_wp.lock())
680 target_sp->GetSourcePathMap().GetModificationID();
681 return false;
682}
683
685 uint32_t line, std::optional<size_t> column, uint32_t context_before,
686 uint32_t context_after, Stream *s, lldb::LanguageType language_type) {
687 // Nothing to write if there's no stream.
688 if (!s)
689 return 0;
690
691 // Sanity check m_data_sp before proceeding.
692 if (!m_data_sp)
693 return 0;
694
695 size_t bytes_written = s->GetWrittenBytes();
696
697 auto debugger_sp = m_debugger_wp.lock();
698
699 HighlightStyle style;
700 // Use the default Vim style if source highlighting is enabled.
701 if (should_highlight_source(debugger_sp))
703
704 // If we should mark the stop column with color codes, then copy the prefix
705 // and suffix to our color style.
706 if (should_show_stop_column_with_ansi(debugger_sp))
707 style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),
708 debugger_sp->GetStopShowColumnAnsiSuffix());
709
711 std::string path =
712 GetSupportFile()->GetSpecOnly().GetPath(/*denormalize*/ false);
713 // FIXME: Find a way to get the definitive language this file was written in
714 // and pass it to the highlighter.
715 const auto &h = mgr.getHighlighterFor(language_type, path);
716
717 const uint32_t start_line =
718 line <= context_before ? 1 : line - context_before;
719 const uint32_t start_line_offset = GetLineOffset(start_line);
720 if (start_line_offset != UINT32_MAX) {
721 const uint32_t end_line = line + context_after;
722 uint32_t end_line_offset = GetLineOffset(end_line + 1);
723 if (end_line_offset == UINT32_MAX)
724 end_line_offset = m_data_sp->GetByteSize();
725
726 assert(start_line_offset <= end_line_offset);
727 if (start_line_offset < end_line_offset) {
728 size_t count = end_line_offset - start_line_offset;
729 const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
730
731 auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);
732
733 h.Highlight(style, ref, column, "", *s);
734
735 // Ensure we get an end of line character one way or another.
736 if (!is_newline_char(ref.back()))
737 s->EOL();
738 }
739 }
740 return s->GetWrittenBytes() - bytes_written;
741}
742
744 RegularExpression &regex, uint32_t start_line, uint32_t end_line,
745 std::vector<uint32_t> &match_lines) {
746 match_lines.clear();
747
748 if (!LineIsValid(start_line) ||
749 (end_line != UINT32_MAX && !LineIsValid(end_line)))
750 return;
751 if (start_line > end_line)
752 return;
753
754 for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
755 std::string buffer;
756 if (!GetLine(line_no, buffer))
757 break;
758 if (regex.Execute(buffer)) {
759 match_lines.push_back(line_no);
760 }
761 }
762}
763
765 const SourceManager::File &rhs) {
766 if (!lhs.GetSupportFile()->Equal(*rhs.GetSupportFile(),
768 return false;
769 return lhs.m_mod_time == rhs.m_mod_time;
770}
771
773 line =
774 UINT32_MAX; // TODO: take this line out when we support partial indexing
775 if (line == UINT32_MAX) {
776 // Already done?
777 if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
778 return true;
779
780 if (m_offsets.empty()) {
781 if (!m_data_sp)
782 return false;
783
784 const char *start = (const char *)m_data_sp->GetBytes();
785 if (start) {
786 const char *end = start + m_data_sp->GetByteSize();
787
788 // Calculate all line offsets from scratch
789
790 // Push a 1 at index zero to indicate the file has been completely
791 // indexed.
792 m_offsets.push_back(UINT32_MAX);
793 const char *s;
794 for (s = start; s < end; ++s) {
795 char curr_ch = *s;
796 if (is_newline_char(curr_ch)) {
797 if (s + 1 < end) {
798 char next_ch = s[1];
799 if (is_newline_char(next_ch)) {
800 if (curr_ch != next_ch)
801 ++s;
802 }
803 }
804 m_offsets.push_back(s + 1 - start);
805 }
806 }
807 if (!m_offsets.empty()) {
808 if (m_offsets.back() < size_t(end - start))
809 m_offsets.push_back(end - start);
810 }
811 return true;
812 }
813 } else {
814 // Some lines have been populated, start where we last left off
815 assert("Not implemented yet" && false);
816 }
817
818 } else {
819 // Calculate all line offsets up to "line"
820 assert("Not implemented yet" && false);
821 }
822 return false;
823}
824
825bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
826 if (!LineIsValid(line_no))
827 return false;
828
829 assert(m_data_sp);
830 size_t start_offset = GetLineOffset(line_no);
831 size_t end_offset = GetLineOffset(line_no + 1);
832 if (end_offset == UINT32_MAX) {
833 end_offset = m_data_sp->GetByteSize();
834 }
835 buffer.assign((const char *)m_data_sp->GetBytes() + start_offset,
836 end_offset - start_offset);
837
838 return true;
839}
840
842 FileSP file_sp) {
843 llvm::sys::ScopedWriter guard(m_mutex);
844
845 assert(file_sp && "invalid FileSP");
846
847 AddSourceFileImpl(file_spec, file_sp);
848 const FileSpec &resolved_file_spec = file_sp->GetSupportFile()->GetSpecOnly();
849 if (file_spec != resolved_file_spec)
850 AddSourceFileImpl(file_sp->GetSupportFile()->GetSpecOnly(), file_sp);
851}
852
854 llvm::sys::ScopedWriter guard(m_mutex);
855
856 assert(file_sp && "invalid FileSP");
857
858 // Iterate over all the elements in the cache.
859 // This is expensive but a relatively uncommon operation.
860 auto it = m_file_cache.begin();
861 while (it != m_file_cache.end()) {
862 if (it->second == file_sp)
863 it = m_file_cache.erase(it);
864 else
865 it++;
866 }
867}
868
870 const FileSpec &file_spec, FileSP file_sp) {
871 FileCache::iterator pos = m_file_cache.find(file_spec);
872 if (pos == m_file_cache.end()) {
873 m_file_cache[file_spec] = file_sp;
874 } else {
875 if (file_sp != pos->second)
876 m_file_cache[file_spec] = file_sp;
877 }
878}
879
881 const FileSpec &file_spec) const {
882 llvm::sys::ScopedReader guard(m_mutex);
883
884 FileCache::const_iterator pos = m_file_cache.find(file_spec);
885 if (pos != m_file_cache.end())
886 return pos->second;
887 return {};
888}
889
891 // clang-format off
892 stream << "Modification time MD5 Checksum (on-disk) MD5 Checksum (line table) Lines Path\n";
893 stream << "------------------- -------------------------------- -------------------------------- -------- --------------------------------\n";
894 // clang-format on
895 for (auto &entry : m_file_cache) {
896 if (!entry.second)
897 continue;
898 FileSP file = entry.second;
899 stream.Format("{0:%Y-%m-%d %H:%M:%S} {1,32} {2,32} {3,8:d} {4}\n",
900 file->GetTimestamp(), toString(file->GetChecksum()),
901 toString(file->GetSupportFile()->GetChecksum()),
902 file->GetNumLines(), entry.first.GetPath());
903 }
904}
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
static void resolve_tilde(FileSpec &file_spec)
static bool should_highlight_source(DebuggerSP debugger_sp)
static bool is_newline_char(char ch)
static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp)
static bool should_show_stop_line_with_ansi(DebuggerSP debugger_sp)
static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp)
std::string digest() const
Definition Checksum.cpp:36
A class that describes a compilation unit.
Definition CompileUnit.h:43
SupportFileNSP GetPrimarySupportFile() const
Return the primary source file associated with this compile unit.
Represents a generic declaration context in a program.
A uniqued constant string class.
Definition ConstString.h:40
const char * GetCString() const
Get the string value as a C string.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
A class to manage flag bits.
Definition Debugger.h:100
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
llvm::sys::TimePoint GetModificationTime(const FileSpec &file_spec) const
Returns the modification time of the given file.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
void Set(llvm::StringRef prefix, llvm::StringRef suffix)
Sets the prefix and suffix strings.
Manages the available highlighters.
const Highlighter & getHighlighterFor(lldb::LanguageType language_type, llvm::StringRef path) const
Queries all known highlighter for one that can highlight some source code.
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
void FindFunctions(llvm::ArrayRef< LookupInfo > lookup_infos, const CompilerDeclContext &parent_decl_ctx, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list)
Find functions by a vector of lookup infos.
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
void CommonInitializerImpl(SupportFileNSP support_file_nsp, lldb::TargetSP target_sp)
File(SupportFileNSP support_file_nsp, lldb::TargetSP target_sp)
uint32_t GetSourceMapModificationID() const
void FindLinesMatchingRegex(RegularExpression &regex, uint32_t start_line, uint32_t end_line, std::vector< uint32_t > &match_lines)
void CommonInitializer(SupportFileNSP support_file_nsp, lldb::TargetSP target_sp)
const char * PeekLineData(uint32_t line)
size_t DisplaySourceLines(uint32_t line, std::optional< size_t > column, uint32_t context_before, uint32_t context_after, Stream *s, lldb::LanguageType language_type=lldb::eLanguageTypeUnknown)
SupportFileNSP GetSupportFile() const
Checksum m_checksum
Keep track of the on-disk checksum.
uint32_t GetLineLength(uint32_t line, bool include_newline_chars)
bool CalculateLineOffsets(uint32_t line=UINT32_MAX)
SupportFileNSP m_support_file_nsp
The support file.
bool GetLine(uint32_t line_no, std::string &buffer)
uint32_t GetLineOffset(uint32_t line)
void SetSupportFile(SupportFileNSP support_file_nsp)
Set file and update modification time.
void AddSourceFileImpl(const FileSpec &file_spec, FileSP file_sp)
FileSP FindSourceFile(const FileSpec &file_spec) const
void AddSourceFile(const FileSpec &file_spec, FileSP file_sp)
void FindLinesMatchingRegex(SupportFileNSP support_file_nsp, RegularExpression &regex, uint32_t start_line, uint32_t end_line, std::vector< uint32_t > &match_lines)
std::shared_ptr< File > FileSP
std::optional< SupportFileAndLine > GetDefaultFileAndLine()
size_t DisplayMoreWithLineNumbers(Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs=nullptr, lldb::LanguageType language_type=lldb::eLanguageTypeUnknown)
bool AtLastLine(bool reverse)
SourceManager(const lldb::DebuggerSP &debugger_sp)
A source manager can be made with a valid Target, in which case it can use the path remappings to fin...
lldb::DebuggerWP m_debugger_wp
FileSP GetFile(SupportFileNSP support_file_nsp)
size_t DisplaySourceLinesWithLineNumbers(SupportFileNSP support_file_nsp, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, const char *current_line_cstr, Stream *s, const SymbolContextList *bp_locs=nullptr, lldb::LanguageType language_type=lldb::eLanguageTypeUnknown)
bool SetDefaultFileAndLine(SupportFileNSP support_file_nsp, uint32_t line)
SupportFileNSP m_last_support_file_nsp
size_t DisplaySourceLinesWithLineNumbersUsingLastFile(uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column, const char *current_line_cstr, Stream *s, const SymbolContextList *bp_locs=nullptr, lldb::LanguageType language_type=lldb::eLanguageTypeUnknown)
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
size_t GetWrittenBytes() const
Definition Stream.h:117
Wraps a FileSpec and an optional Checksum.
Definition SupportFile.h:22
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t NumLineEntriesWithLine(uint32_t line) const
Defines a symbol context baton that can be handed other debug core functions.
CompileUnit * comp_unit
The CompileUnit for a given query.
#define UINT32_MAX
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
NonNullSharedPtr< lldb_private::SupportFile > SupportFileNSP
Definition SupportFile.h:80
bool operator==(const Address &lhs, const Address &rhs)
Definition Address.cpp:1010
std::string toString(FormatterBytecode::OpCodes op)
LanguageType
Programming language type.
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
@ eStopShowColumnAnsi
@ eStopShowColumnCaret
@ eStopShowColumnAnsiOrCaret
std::shared_ptr< lldb_private::Target > TargetSP
Represents style that the highlighter should apply to the given source code.
Definition Highlighter.h:25
static HighlightStyle MakeVimStyle()
Returns a HighlightStyle that is based on vim's default highlight style.
ColorStyle selected
The style for the token which is below the cursor of the user.
Definition Highlighter.h:58
A line table entry class.
Definition LineEntry.h:21
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
SupportFileNSP file_sp
The source file, possibly mapped by the target.source-map setting.
Definition LineEntry.h:144
Options used by Module::FindFunctions.
Definition Module.h:66
bool include_inlines
Include inlined functions.
Definition Module.h:70
bool include_symbols
Include the symbol table.
Definition Module.h:68