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