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