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
9 #include "lldb/Core/SourceManager.h"
10
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/AddressRange.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/FormatEntity.h"
15 #include "lldb/Core/Highlighter.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Symbol/CompileUnit.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/LineEntry.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Target/PathMappingList.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/AnsiTerminal.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"
32
33 #include "llvm/ADT/Twine.h"
34
35 #include <memory>
36 #include <utility>
37
38 #include <assert.h>
39 #include <stdio.h>
40
41 namespace lldb_private {
42 class ExecutionContext;
43 }
44 namespace lldb_private {
45 class ValueObject;
46 }
47
48 using namespace lldb;
49 using namespace lldb_private;
50
is_newline_char(char ch)51 static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; }
52
53 // SourceManager constructor
SourceManager(const TargetSP & target_sp)54 SourceManager::SourceManager(const TargetSP &target_sp)
55 : m_last_line(0), m_last_count(0), m_default_set(false),
56 m_target_wp(target_sp),
57 m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}
58
SourceManager(const DebuggerSP & debugger_sp)59 SourceManager::SourceManager(const DebuggerSP &debugger_sp)
60 : m_last_line(0), m_last_count(0), m_default_set(false), m_target_wp(),
61 m_debugger_wp(debugger_sp) {}
62
63 // Destructor
~SourceManager()64 SourceManager::~SourceManager() {}
65
GetFile(const FileSpec & file_spec)66 SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) {
67 if (!file_spec)
68 return nullptr;
69
70 DebuggerSP debugger_sp(m_debugger_wp.lock());
71 FileSP file_sp;
72 if (debugger_sp && debugger_sp->GetUseSourceCache())
73 file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);
74
75 TargetSP target_sp(m_target_wp.lock());
76
77 // It the target source path map has been updated, get this file again so we
78 // can successfully remap the source file
79 if (target_sp && file_sp &&
80 file_sp->GetSourceMapModificationID() !=
81 target_sp->GetSourcePathMap().GetModificationID())
82 file_sp.reset();
83
84 // Update the file contents if needed if we found a file
85 if (file_sp)
86 file_sp->UpdateIfNeeded();
87
88 // If file_sp is no good or it points to a non-existent file, reset it.
89 if (!file_sp || !FileSystem::Instance().Exists(file_sp->GetFileSpec())) {
90 if (target_sp)
91 file_sp = std::make_shared<File>(file_spec, target_sp.get());
92 else
93 file_sp = std::make_shared<File>(file_spec, debugger_sp);
94
95 if (debugger_sp && debugger_sp->GetUseSourceCache())
96 debugger_sp->GetSourceFileCache().AddSourceFile(file_sp);
97 }
98 return file_sp;
99 }
100
should_highlight_source(DebuggerSP debugger_sp)101 static bool should_highlight_source(DebuggerSP debugger_sp) {
102 if (!debugger_sp)
103 return false;
104
105 // We don't use ANSI stop column formatting if the debugger doesn't think it
106 // should be using color.
107 if (!debugger_sp->GetUseColor())
108 return false;
109
110 return debugger_sp->GetHighlightSource();
111 }
112
should_show_stop_column_with_ansi(DebuggerSP debugger_sp)113 static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {
114 // We don't use ANSI stop column formatting if we can't lookup values from
115 // the debugger.
116 if (!debugger_sp)
117 return false;
118
119 // We don't use ANSI stop column formatting if the debugger doesn't think it
120 // should be using color.
121 if (!debugger_sp->GetUseColor())
122 return false;
123
124 // We only use ANSI stop column formatting if we're either supposed to show
125 // ANSI where available (which we know we have when we get to this point), or
126 // if we're only supposed to use ANSI.
127 const auto value = debugger_sp->GetStopShowColumn();
128 return ((value == eStopShowColumnAnsiOrCaret) ||
129 (value == eStopShowColumnAnsi));
130 }
131
should_show_stop_column_with_caret(DebuggerSP debugger_sp)132 static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {
133 // We don't use text-based stop column formatting if we can't lookup values
134 // from the debugger.
135 if (!debugger_sp)
136 return false;
137
138 // If we're asked to show the first available of ANSI or caret, then we do
139 // show the caret when ANSI is not available.
140 const auto value = debugger_sp->GetStopShowColumn();
141 if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())
142 return true;
143
144 // The only other time we use caret is if we're explicitly asked to show
145 // caret.
146 return value == eStopShowColumnCaret;
147 }
148
should_show_stop_line_with_ansi(DebuggerSP debugger_sp)149 static bool should_show_stop_line_with_ansi(DebuggerSP debugger_sp) {
150 return debugger_sp && debugger_sp->GetUseColor();
151 }
152
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)153 size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(
154 uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,
155 const char *current_line_cstr, Stream *s,
156 const SymbolContextList *bp_locs) {
157 if (count == 0)
158 return 0;
159
160 Stream::ByteDelta delta(*s);
161
162 if (start_line == 0) {
163 if (m_last_line != 0 && m_last_line != UINT32_MAX)
164 start_line = m_last_line + m_last_count;
165 else
166 start_line = 1;
167 }
168
169 if (!m_default_set) {
170 FileSpec tmp_spec;
171 uint32_t tmp_line;
172 GetDefaultFileAndLine(tmp_spec, tmp_line);
173 }
174
175 m_last_line = start_line;
176 m_last_count = count;
177
178 if (FileSP last_file_sp = GetLastFile()) {
179 const uint32_t end_line = start_line + count - 1;
180 for (uint32_t line = start_line; line <= end_line; ++line) {
181 if (!last_file_sp->LineIsValid(line)) {
182 m_last_line = UINT32_MAX;
183 break;
184 }
185
186 std::string prefix;
187 if (bp_locs) {
188 uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);
189
190 if (bp_count > 0)
191 prefix = llvm::formatv("[{0}]", bp_count);
192 else
193 prefix = " ";
194 }
195
196 char buffer[3];
197 sprintf(buffer, "%2.2s", (line == curr_line) ? current_line_cstr : "");
198 std::string current_line_highlight(buffer);
199
200 auto debugger_sp = m_debugger_wp.lock();
201 if (should_show_stop_line_with_ansi(debugger_sp)) {
202 current_line_highlight = ansi::FormatAnsiTerminalCodes(
203 (debugger_sp->GetStopShowLineMarkerAnsiPrefix() +
204 current_line_highlight +
205 debugger_sp->GetStopShowLineMarkerAnsiSuffix())
206 .str());
207 }
208
209 s->Printf("%s%s %-4u\t", prefix.c_str(), current_line_highlight.c_str(),
210 line);
211
212 // So far we treated column 0 as a special 'no column value', but
213 // DisplaySourceLines starts counting columns from 0 (and no column is
214 // expressed by passing an empty optional).
215 llvm::Optional<size_t> columnToHighlight;
216 if (line == curr_line && column)
217 columnToHighlight = column - 1;
218
219 size_t this_line_size =
220 last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);
221 if (column != 0 && line == curr_line &&
222 should_show_stop_column_with_caret(debugger_sp)) {
223 // Display caret cursor.
224 std::string src_line;
225 last_file_sp->GetLine(line, src_line);
226 s->Printf(" \t");
227 // Insert a space for every non-tab character in the source line.
228 for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)
229 s->PutChar(src_line[i] == '\t' ? '\t' : ' ');
230 // Now add the caret.
231 s->Printf("^\n");
232 }
233 if (this_line_size == 0) {
234 m_last_line = UINT32_MAX;
235 break;
236 }
237 }
238 }
239 return *delta;
240 }
241
DisplaySourceLinesWithLineNumbers(const FileSpec & file_spec,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)242 size_t SourceManager::DisplaySourceLinesWithLineNumbers(
243 const FileSpec &file_spec, uint32_t line, uint32_t column,
244 uint32_t context_before, uint32_t context_after,
245 const char *current_line_cstr, Stream *s,
246 const SymbolContextList *bp_locs) {
247 FileSP file_sp(GetFile(file_spec));
248
249 uint32_t start_line;
250 uint32_t count = context_before + context_after + 1;
251 if (line > context_before)
252 start_line = line - context_before;
253 else
254 start_line = 1;
255
256 FileSP last_file_sp(GetLastFile());
257 if (last_file_sp.get() != file_sp.get()) {
258 if (line == 0)
259 m_last_line = 0;
260 m_last_file_spec = file_spec;
261 }
262 return DisplaySourceLinesWithLineNumbersUsingLastFile(
263 start_line, count, line, column, current_line_cstr, s, bp_locs);
264 }
265
DisplayMoreWithLineNumbers(Stream * s,uint32_t count,bool reverse,const SymbolContextList * bp_locs)266 size_t SourceManager::DisplayMoreWithLineNumbers(
267 Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {
268 // If we get called before anybody has set a default file and line, then try
269 // to figure it out here.
270 FileSP last_file_sp(GetLastFile());
271 const bool have_default_file_line = last_file_sp && m_last_line > 0;
272 if (!m_default_set) {
273 FileSpec tmp_spec;
274 uint32_t tmp_line;
275 GetDefaultFileAndLine(tmp_spec, tmp_line);
276 }
277
278 if (last_file_sp) {
279 if (m_last_line == UINT32_MAX)
280 return 0;
281
282 if (reverse && m_last_line == 1)
283 return 0;
284
285 if (count > 0)
286 m_last_count = count;
287 else if (m_last_count == 0)
288 m_last_count = 10;
289
290 if (m_last_line > 0) {
291 if (reverse) {
292 // If this is the first time we've done a reverse, then back up one
293 // more time so we end up showing the chunk before the last one we've
294 // shown:
295 if (m_last_line > m_last_count)
296 m_last_line -= m_last_count;
297 else
298 m_last_line = 1;
299 } else if (have_default_file_line)
300 m_last_line += m_last_count;
301 } else
302 m_last_line = 1;
303
304 const uint32_t column = 0;
305 return DisplaySourceLinesWithLineNumbersUsingLastFile(
306 m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);
307 }
308 return 0;
309 }
310
SetDefaultFileAndLine(const FileSpec & file_spec,uint32_t line)311 bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,
312 uint32_t line) {
313 m_default_set = true;
314 FileSP file_sp(GetFile(file_spec));
315
316 if (file_sp) {
317 m_last_line = line;
318 m_last_file_spec = file_spec;
319 return true;
320 } else {
321 return false;
322 }
323 }
324
GetDefaultFileAndLine(FileSpec & file_spec,uint32_t & line)325 bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {
326 if (FileSP last_file_sp = GetLastFile()) {
327 file_spec = m_last_file_spec;
328 line = m_last_line;
329 return true;
330 } else if (!m_default_set) {
331 TargetSP target_sp(m_target_wp.lock());
332
333 if (target_sp) {
334 // If nobody has set the default file and line then try here. If there's
335 // no executable, then we will try again later when there is one.
336 // Otherwise, if we can't find it we won't look again, somebody will have
337 // to set it (for instance when we stop somewhere...)
338 Module *executable_ptr = target_sp->GetExecutableModulePointer();
339 if (executable_ptr) {
340 SymbolContextList sc_list;
341 ConstString main_name("main");
342 bool symbols_okay = false; // Force it to be a debug symbol.
343 bool inlines_okay = true;
344 executable_ptr->FindFunctions(main_name, CompilerDeclContext(),
345 lldb::eFunctionNameTypeBase, inlines_okay,
346 symbols_okay, sc_list);
347 size_t num_matches = sc_list.GetSize();
348 for (size_t idx = 0; idx < num_matches; idx++) {
349 SymbolContext sc;
350 sc_list.GetContextAtIndex(idx, sc);
351 if (sc.function) {
352 lldb_private::LineEntry line_entry;
353 if (sc.function->GetAddressRange()
354 .GetBaseAddress()
355 .CalculateSymbolContextLineEntry(line_entry)) {
356 SetDefaultFileAndLine(line_entry.file, line_entry.line);
357 file_spec = m_last_file_spec;
358 line = m_last_line;
359 return true;
360 }
361 }
362 }
363 }
364 }
365 }
366 return false;
367 }
368
FindLinesMatchingRegex(FileSpec & file_spec,RegularExpression & regex,uint32_t start_line,uint32_t end_line,std::vector<uint32_t> & match_lines)369 void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
370 RegularExpression ®ex,
371 uint32_t start_line,
372 uint32_t end_line,
373 std::vector<uint32_t> &match_lines) {
374 match_lines.clear();
375 FileSP file_sp = GetFile(file_spec);
376 if (!file_sp)
377 return;
378 return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
379 match_lines);
380 }
381
File(const FileSpec & file_spec,lldb::DebuggerSP debugger_sp)382 SourceManager::File::File(const FileSpec &file_spec,
383 lldb::DebuggerSP debugger_sp)
384 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
385 m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
386 m_debugger_wp(debugger_sp) {
387 CommonInitializer(file_spec, nullptr);
388 }
389
File(const FileSpec & file_spec,Target * target)390 SourceManager::File::File(const FileSpec &file_spec, Target *target)
391 : m_file_spec_orig(file_spec), m_file_spec(file_spec),
392 m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
393 m_debugger_wp(target ? target->GetDebugger().shared_from_this()
394 : DebuggerSP()) {
395 CommonInitializer(file_spec, target);
396 }
397
CommonInitializer(const FileSpec & file_spec,Target * target)398 void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
399 Target *target) {
400 if (m_mod_time == llvm::sys::TimePoint<>()) {
401 if (target) {
402 m_source_map_mod_id = target->GetSourcePathMap().GetModificationID();
403
404 if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
405 // If this is just a file name, lets see if we can find it in the
406 // target:
407 bool check_inlines = false;
408 SymbolContextList sc_list;
409 size_t num_matches =
410 target->GetImages().ResolveSymbolContextForFilePath(
411 file_spec.GetFilename().AsCString(), 0, check_inlines,
412 SymbolContextItem(eSymbolContextModule |
413 eSymbolContextCompUnit),
414 sc_list);
415 bool got_multiple = false;
416 if (num_matches != 0) {
417 if (num_matches > 1) {
418 SymbolContext sc;
419 CompileUnit *test_cu = nullptr;
420
421 for (unsigned i = 0; i < num_matches; i++) {
422 sc_list.GetContextAtIndex(i, sc);
423 if (sc.comp_unit) {
424 if (test_cu) {
425 if (test_cu != sc.comp_unit)
426 got_multiple = true;
427 break;
428 } else
429 test_cu = sc.comp_unit;
430 }
431 }
432 }
433 if (!got_multiple) {
434 SymbolContext sc;
435 sc_list.GetContextAtIndex(0, sc);
436 if (sc.comp_unit)
437 m_file_spec = sc.comp_unit->GetPrimaryFile();
438 m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
439 }
440 }
441 }
442 // Try remapping if m_file_spec does not correspond to an existing file.
443 if (!FileSystem::Instance().Exists(m_file_spec)) {
444 FileSpec new_file_spec;
445 // Check target specific source remappings first, then fall back to
446 // modules objects can have individual path remappings that were
447 // detected when the debug info for a module was found. then
448 if (target->GetSourcePathMap().FindFile(m_file_spec, new_file_spec) ||
449 target->GetImages().FindSourceFile(m_file_spec, new_file_spec)) {
450 m_file_spec = new_file_spec;
451 m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
452 }
453 }
454 }
455 }
456
457 if (m_mod_time != llvm::sys::TimePoint<>())
458 m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
459 }
460
GetLineOffset(uint32_t line)461 uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
462 if (line == 0)
463 return UINT32_MAX;
464
465 if (line == 1)
466 return 0;
467
468 if (CalculateLineOffsets(line)) {
469 if (line < m_offsets.size())
470 return m_offsets[line - 1]; // yes we want "line - 1" in the index
471 }
472 return UINT32_MAX;
473 }
474
GetNumLines()475 uint32_t SourceManager::File::GetNumLines() {
476 CalculateLineOffsets();
477 return m_offsets.size();
478 }
479
PeekLineData(uint32_t line)480 const char *SourceManager::File::PeekLineData(uint32_t line) {
481 if (!LineIsValid(line))
482 return nullptr;
483
484 size_t line_offset = GetLineOffset(line);
485 if (line_offset < m_data_sp->GetByteSize())
486 return (const char *)m_data_sp->GetBytes() + line_offset;
487 return nullptr;
488 }
489
GetLineLength(uint32_t line,bool include_newline_chars)490 uint32_t SourceManager::File::GetLineLength(uint32_t line,
491 bool include_newline_chars) {
492 if (!LineIsValid(line))
493 return false;
494
495 size_t start_offset = GetLineOffset(line);
496 size_t end_offset = GetLineOffset(line + 1);
497 if (end_offset == UINT32_MAX)
498 end_offset = m_data_sp->GetByteSize();
499
500 if (end_offset > start_offset) {
501 uint32_t length = end_offset - start_offset;
502 if (!include_newline_chars) {
503 const char *line_start =
504 (const char *)m_data_sp->GetBytes() + start_offset;
505 while (length > 0) {
506 const char last_char = line_start[length - 1];
507 if ((last_char == '\r') || (last_char == '\n'))
508 --length;
509 else
510 break;
511 }
512 }
513 return length;
514 }
515 return 0;
516 }
517
LineIsValid(uint32_t line)518 bool SourceManager::File::LineIsValid(uint32_t line) {
519 if (line == 0)
520 return false;
521
522 if (CalculateLineOffsets(line))
523 return line < m_offsets.size();
524 return false;
525 }
526
UpdateIfNeeded()527 void SourceManager::File::UpdateIfNeeded() {
528 // TODO: use host API to sign up for file modifications to anything in our
529 // source cache and only update when we determine a file has been updated.
530 // For now we check each time we want to display info for the file.
531 auto curr_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
532
533 if (curr_mod_time != llvm::sys::TimePoint<>() &&
534 m_mod_time != curr_mod_time) {
535 m_mod_time = curr_mod_time;
536 m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
537 m_offsets.clear();
538 }
539 }
540
DisplaySourceLines(uint32_t line,llvm::Optional<size_t> column,uint32_t context_before,uint32_t context_after,Stream * s)541 size_t SourceManager::File::DisplaySourceLines(uint32_t line,
542 llvm::Optional<size_t> column,
543 uint32_t context_before,
544 uint32_t context_after,
545 Stream *s) {
546 // Nothing to write if there's no stream.
547 if (!s)
548 return 0;
549
550 // Sanity check m_data_sp before proceeding.
551 if (!m_data_sp)
552 return 0;
553
554 size_t bytes_written = s->GetWrittenBytes();
555
556 auto debugger_sp = m_debugger_wp.lock();
557
558 HighlightStyle style;
559 // Use the default Vim style if source highlighting is enabled.
560 if (should_highlight_source(debugger_sp))
561 style = HighlightStyle::MakeVimStyle();
562
563 // If we should mark the stop column with color codes, then copy the prefix
564 // and suffix to our color style.
565 if (should_show_stop_column_with_ansi(debugger_sp))
566 style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),
567 debugger_sp->GetStopShowColumnAnsiSuffix());
568
569 HighlighterManager mgr;
570 std::string path = GetFileSpec().GetPath(/*denormalize*/ false);
571 // FIXME: Find a way to get the definitive language this file was written in
572 // and pass it to the highlighter.
573 const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);
574
575 const uint32_t start_line =
576 line <= context_before ? 1 : line - context_before;
577 const uint32_t start_line_offset = GetLineOffset(start_line);
578 if (start_line_offset != UINT32_MAX) {
579 const uint32_t end_line = line + context_after;
580 uint32_t end_line_offset = GetLineOffset(end_line + 1);
581 if (end_line_offset == UINT32_MAX)
582 end_line_offset = m_data_sp->GetByteSize();
583
584 assert(start_line_offset <= end_line_offset);
585 if (start_line_offset < end_line_offset) {
586 size_t count = end_line_offset - start_line_offset;
587 const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
588
589 auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);
590
591 h.Highlight(style, ref, column, "", *s);
592
593 // Ensure we get an end of line character one way or another.
594 if (!is_newline_char(ref.back()))
595 s->EOL();
596 }
597 }
598 return s->GetWrittenBytes() - bytes_written;
599 }
600
FindLinesMatchingRegex(RegularExpression & regex,uint32_t start_line,uint32_t end_line,std::vector<uint32_t> & match_lines)601 void SourceManager::File::FindLinesMatchingRegex(
602 RegularExpression ®ex, uint32_t start_line, uint32_t end_line,
603 std::vector<uint32_t> &match_lines) {
604 match_lines.clear();
605
606 if (!LineIsValid(start_line) ||
607 (end_line != UINT32_MAX && !LineIsValid(end_line)))
608 return;
609 if (start_line > end_line)
610 return;
611
612 for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
613 std::string buffer;
614 if (!GetLine(line_no, buffer))
615 break;
616 if (regex.Execute(buffer)) {
617 match_lines.push_back(line_no);
618 }
619 }
620 }
621
operator ==(const SourceManager::File & lhs,const SourceManager::File & rhs)622 bool lldb_private::operator==(const SourceManager::File &lhs,
623 const SourceManager::File &rhs) {
624 if (lhs.m_file_spec != rhs.m_file_spec)
625 return false;
626 return lhs.m_mod_time == rhs.m_mod_time;
627 }
628
CalculateLineOffsets(uint32_t line)629 bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
630 line =
631 UINT32_MAX; // TODO: take this line out when we support partial indexing
632 if (line == UINT32_MAX) {
633 // Already done?
634 if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
635 return true;
636
637 if (m_offsets.empty()) {
638 if (m_data_sp.get() == nullptr)
639 return false;
640
641 const char *start = (char *)m_data_sp->GetBytes();
642 if (start) {
643 const char *end = start + m_data_sp->GetByteSize();
644
645 // Calculate all line offsets from scratch
646
647 // Push a 1 at index zero to indicate the file has been completely
648 // indexed.
649 m_offsets.push_back(UINT32_MAX);
650 const char *s;
651 for (s = start; s < end; ++s) {
652 char curr_ch = *s;
653 if (is_newline_char(curr_ch)) {
654 if (s + 1 < end) {
655 char next_ch = s[1];
656 if (is_newline_char(next_ch)) {
657 if (curr_ch != next_ch)
658 ++s;
659 }
660 }
661 m_offsets.push_back(s + 1 - start);
662 }
663 }
664 if (!m_offsets.empty()) {
665 if (m_offsets.back() < size_t(end - start))
666 m_offsets.push_back(end - start);
667 }
668 return true;
669 }
670 } else {
671 // Some lines have been populated, start where we last left off
672 assert("Not implemented yet" && false);
673 }
674
675 } else {
676 // Calculate all line offsets up to "line"
677 assert("Not implemented yet" && false);
678 }
679 return false;
680 }
681
GetLine(uint32_t line_no,std::string & buffer)682 bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
683 if (!LineIsValid(line_no))
684 return false;
685
686 size_t start_offset = GetLineOffset(line_no);
687 size_t end_offset = GetLineOffset(line_no + 1);
688 if (end_offset == UINT32_MAX) {
689 end_offset = m_data_sp->GetByteSize();
690 }
691 buffer.assign((char *)m_data_sp->GetBytes() + start_offset,
692 end_offset - start_offset);
693
694 return true;
695 }
696
AddSourceFile(const FileSP & file_sp)697 void SourceManager::SourceFileCache::AddSourceFile(const FileSP &file_sp) {
698 FileSpec file_spec = file_sp->GetFileSpec();
699 FileCache::iterator pos = m_file_cache.find(file_spec);
700 if (pos == m_file_cache.end())
701 m_file_cache[file_spec] = file_sp;
702 else {
703 if (file_sp != pos->second)
704 m_file_cache[file_spec] = file_sp;
705 }
706 }
707
FindSourceFile(const FileSpec & file_spec) const708 SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
709 const FileSpec &file_spec) const {
710 FileSP file_sp;
711 FileCache::const_iterator pos = m_file_cache.find(file_spec);
712 if (pos != m_file_cache.end())
713 file_sp = pos->second;
714 return file_sp;
715 }
716