brintos

brintos / llvm-project-archived public Read only

0
0
Text · 29.8 KiB · c60288c Raw
890 lines · cpp
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-exception6//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/Utility/SupportFile.h"34#include "lldb/lldb-enumerations.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 {47class ExecutionContext;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 constructor72SourceManager::SourceManager(const TargetSP &target_sp)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 77SourceManager::SourceManager(const DebuggerSP &debugger_sp)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// Destructor83SourceManager::~SourceManager() = default;84 85SourceManager::FileSP SourceManager::GetFile(SupportFileNSP support_file_nsp) {86  FileSpec file_spec = support_file_nsp->GetSpecOnly();87  if (!file_spec)88    return {};89 90  Log *log = GetLog(LLDBLog::Source);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 avoids106  // 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'll116        // 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 our131  // 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 find155  // 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    else163      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 was166    // 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 it180  // should be using color.181  if (!debugger_sp->GetUseColor())182    return false;183 184  return debugger_sp->GetHighlightSource();185}186 187static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {188  // We don't use ANSI stop column formatting if we can't lookup values from189  // 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 it194  // 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 show199  // ANSI where available (which we know we have when we get to this point), or200  // if we're only supposed to use ANSI.201  const auto value = debugger_sp->GetStopShowColumn();202  return ((value == eStopShowColumnAnsiOrCaret) ||203          (value == eStopShowColumnAnsi));204}205 206static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {207  // We don't use text-based stop column formatting if we can't lookup values208  // 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 do213  // 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 show219  // caret.220  return value == eStopShowColumnCaret;221}222 223static bool should_show_stop_line_with_ansi(DebuggerSP debugger_sp) {224  return debugger_sp && debugger_sp->GetUseColor();225}226 227size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(228    uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,229    const char *current_line_cstr, Stream *s,230    const SymbolContextList *bp_locs) {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    else240      start_line = 1;241  }242 243  if (!m_default_set)244    GetDefaultFileAndLine();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)) {253        m_last_line = UINT32_MAX;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        else264          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', but285      // DisplaySourceLines starts counting columns from 0 (and no column is286      // 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 =292          last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);293      if (column != 0 && line == curr_line &&294          should_show_stop_column_with_caret(debugger_sp)) {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) {306        m_last_line = UINT32_MAX;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)315      Debugger::ReportWarning(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 326size_t SourceManager::DisplaySourceLinesWithLineNumbers(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,330    const SymbolContextList *bp_locs) {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  else339    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 348  return DisplaySourceLinesWithLineNumbersUsingLastFile(349      start_line, count, line, column, current_line_cstr, s, bp_locs);350}351 352size_t SourceManager::DisplayMoreWithLineNumbers(353    Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {354  // If we get called before anybody has set a default file and line, then try355  // to figure it out here.356  FileSP last_file_sp(GetLastFile());357  const bool have_default_file_line = last_file_sp && m_last_line > 0;358  if (!m_default_set)359    GetDefaultFileAndLine();360 361  if (last_file_sp) {362    if (AtLastLine(reverse))363      return 0;364 365    if (count > 0)366      m_last_count = count;367    else if (m_last_count == 0)368      m_last_count = 10;369 370    if (m_last_line > 0) {371      if (reverse) {372        // If this is the first time we've done a reverse, then back up one373        // more time so we end up showing the chunk before the last one we've374        // shown:375        if (m_last_line > m_last_count)376          m_last_line -= m_last_count;377        else378          m_last_line = 1;379      } else if (have_default_file_line)380        m_last_line += m_last_count;381    } else382      m_last_line = 1;383 384    const uint32_t column = 0;385    return DisplaySourceLinesWithLineNumbersUsingLastFile(386        m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);387  }388  return 0;389}390 391bool SourceManager::SetDefaultFileAndLine(SupportFileNSP support_file_nsp,392                                          uint32_t line) {393  assert(support_file_nsp && "SupportFile must be valid");394 395  m_default_set = true;396 397  if (FileSP file_sp = GetFile(support_file_nsp)) {398    m_last_line = line;399    m_last_support_file_nsp = support_file_nsp;400    return true;401  }402 403  return false;404}405 406std::optional<SourceManager::SupportFileAndLine>407SourceManager::GetDefaultFileAndLine() {408  if (FileSP last_file_sp = GetLastFile())409    return SupportFileAndLine(m_last_support_file_nsp, m_last_line);410 411  if (!m_default_set) {412    TargetSP target_sp(m_target_wp.lock());413 414    if (target_sp) {415      // If nobody has set the default file and line then try here.  If there's416      // no executable, then we will try again later when there is one.417      // Otherwise, if we can't find it we won't look again, somebody will have418      // to set it (for instance when we stop somewhere...)419      Module *executable_ptr = target_sp->GetExecutableModulePointer();420      if (executable_ptr) {421        SymbolContextList sc_list;422        ConstString main_name("main");423 424        ModuleFunctionSearchOptions function_options;425        function_options.include_symbols =426            false; // Force it to be a debug symbol.427        function_options.include_inlines = true;428        executable_ptr->FindFunctions(main_name, CompilerDeclContext(),429                                      lldb::eFunctionNameTypeFull,430                                      function_options, sc_list);431        for (const SymbolContext &sc : sc_list) {432          if (sc.function) {433            lldb_private::LineEntry line_entry;434            if (sc.function->GetAddress().CalculateSymbolContextLineEntry(435                    line_entry)) {436              SetDefaultFileAndLine(line_entry.file_sp, line_entry.line);437              return SupportFileAndLine(line_entry.file_sp, m_last_line);438            }439          }440        }441      }442    }443  }444 445  return std::nullopt;446}447 448void SourceManager::FindLinesMatchingRegex(SupportFileNSP support_file_nsp,449                                           RegularExpression &regex,450                                           uint32_t start_line,451                                           uint32_t end_line,452                                           std::vector<uint32_t> &match_lines) {453  match_lines.clear();454  FileSP file_sp = GetFile(support_file_nsp);455  if (!file_sp)456    return;457  return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,458                                         match_lines);459}460 461SourceManager::File::File(SupportFileNSP support_file_nsp,462                          lldb::DebuggerSP debugger_sp)463    : m_support_file_nsp(std::make_shared<SupportFile>()), m_checksum(),464      m_mod_time(), m_debugger_wp(debugger_sp), m_target_wp(TargetSP()) {465  CommonInitializer(support_file_nsp, {});466}467 468SourceManager::File::File(SupportFileNSP support_file_nsp, TargetSP target_sp)469    : m_support_file_nsp(std::make_shared<SupportFile>()), m_checksum(),470      m_mod_time(),471      m_debugger_wp(target_sp ? target_sp->GetDebugger().shared_from_this()472                              : DebuggerSP()),473      m_target_wp(target_sp) {474  CommonInitializer(support_file_nsp, target_sp);475}476 477void SourceManager::File::CommonInitializer(SupportFileNSP support_file_nsp,478                                            TargetSP target_sp) {479  // It might take a while to read a source file, for example because it's480  // coming from a virtual file system that's fetching the data on demand. When481  // reading the data exceeds a certain threshold, show a progress event to let482  // the user know what's going on.483  static constexpr auto g_progress_delay = std::chrono::milliseconds(500);484 485  std::future<void> future = std::async(std::launch::async, [=]() {486    CommonInitializerImpl(support_file_nsp, target_sp);487  });488 489  std::optional<Progress> progress;490  if (future.wait_for(g_progress_delay) == std::future_status::timeout) {491    Debugger *debugger = target_sp ? &target_sp->GetDebugger() : nullptr;492    progress.emplace("Loading source file",493                     support_file_nsp->GetSpecOnly().GetFilename().GetString(),494                     1, debugger);495  }496  future.wait();497}498 499void SourceManager::File::CommonInitializerImpl(SupportFileNSP support_file_nsp,500                                                TargetSP target_sp) {501  // Set the file and update the modification time.502  SetSupportFile(support_file_nsp);503 504  // Always update the source map modification ID if we have a target.505  if (target_sp)506    m_source_map_mod_id = target_sp->GetSourcePathMap().GetModificationID();507 508  // File doesn't exist.509  if (m_mod_time == llvm::sys::TimePoint<>()) {510    if (target_sp) {511      // If this is just a file name, try finding it in the target.512      {513        FileSpec file_spec = support_file_nsp->GetSpecOnly();514        if (!file_spec.GetDirectory() && file_spec.GetFilename()) {515          bool check_inlines = false;516          SymbolContextList sc_list;517          size_t num_matches =518              target_sp->GetImages().ResolveSymbolContextForFilePath(519                  file_spec.GetFilename().AsCString(), 0, check_inlines,520                  SymbolContextItem(eSymbolContextModule |521                                    eSymbolContextCompUnit),522                  sc_list);523          bool got_multiple = false;524          if (num_matches != 0) {525            if (num_matches > 1) {526              CompileUnit *test_cu = nullptr;527              for (const SymbolContext &sc : sc_list) {528                if (sc.comp_unit) {529                  if (test_cu) {530                    if (test_cu != sc.comp_unit)531                      got_multiple = true;532                    break;533                  } else534                    test_cu = sc.comp_unit;535                }536              }537            }538            if (!got_multiple) {539              SymbolContext sc;540              sc_list.GetContextAtIndex(0, sc);541              if (sc.comp_unit)542                SetSupportFile(sc.comp_unit->GetPrimarySupportFile());543            }544          }545        }546      }547 548      // Try remapping the file if it doesn't exist.549      {550        FileSpec file_spec = support_file_nsp->GetSpecOnly();551        if (!FileSystem::Instance().Exists(file_spec)) {552          // Check target specific source remappings (i.e., the553          // target.source-map setting), then fall back to the module554          // specific remapping (i.e., the .dSYM remapping dictionary).555          auto remapped = target_sp->GetSourcePathMap().FindFile(file_spec);556          if (!remapped) {557            FileSpec new_spec;558            if (target_sp->GetImages().FindSourceFile(file_spec, new_spec))559              remapped = new_spec;560          }561          if (remapped)562            SetSupportFile(std::make_shared<SupportFile>(563                *remapped, support_file_nsp->GetChecksum()));564        }565      }566    }567  }568 569  // If the file exists, read in the data.570  if (m_mod_time != llvm::sys::TimePoint<>()) {571    m_data_sp = FileSystem::Instance().CreateDataBuffer(572        m_support_file_nsp->GetSpecOnly());573    m_checksum = llvm::MD5::hash(m_data_sp->GetData());574  }575}576 577void SourceManager::File::SetSupportFile(SupportFileNSP support_file_nsp) {578  FileSpec file_spec = support_file_nsp->GetSpecOnly();579  resolve_tilde(file_spec);580  m_support_file_nsp =581      std::make_shared<SupportFile>(file_spec, support_file_nsp->GetChecksum());582  m_mod_time = FileSystem::Instance().GetModificationTime(file_spec);583}584 585uint32_t SourceManager::File::GetLineOffset(uint32_t line) {586  if (line == 0)587    return UINT32_MAX;588 589  if (line == 1)590    return 0;591 592  if (CalculateLineOffsets(line)) {593    if (line < m_offsets.size())594      return m_offsets[line - 1]; // yes we want "line - 1" in the index595  }596  return UINT32_MAX;597}598 599uint32_t SourceManager::File::GetNumLines() {600  CalculateLineOffsets();601  return m_offsets.size();602}603 604const char *SourceManager::File::PeekLineData(uint32_t line) {605  if (!LineIsValid(line))606    return nullptr;607 608  size_t line_offset = GetLineOffset(line);609  if (line_offset < m_data_sp->GetByteSize())610    return (const char *)m_data_sp->GetBytes() + line_offset;611  return nullptr;612}613 614uint32_t SourceManager::File::GetLineLength(uint32_t line,615                                            bool include_newline_chars) {616  if (!LineIsValid(line))617    return false;618 619  size_t start_offset = GetLineOffset(line);620  size_t end_offset = GetLineOffset(line + 1);621  if (end_offset == UINT32_MAX)622    end_offset = m_data_sp->GetByteSize();623 624  if (end_offset > start_offset) {625    uint32_t length = end_offset - start_offset;626    if (!include_newline_chars) {627      const char *line_start =628          (const char *)m_data_sp->GetBytes() + start_offset;629      while (length > 0) {630        const char last_char = line_start[length - 1];631        if ((last_char == '\r') || (last_char == '\n'))632          --length;633        else634          break;635      }636    }637    return length;638  }639  return 0;640}641 642bool SourceManager::File::LineIsValid(uint32_t line) {643  if (line == 0)644    return false;645 646  if (CalculateLineOffsets(line))647    return line < m_offsets.size();648  return false;649}650 651bool SourceManager::File::ModificationTimeIsStale() const {652  // TODO: use host API to sign up for file modifications to anything in our653  // source cache and only update when we determine a file has been updated.654  // For now we check each time we want to display info for the file.655  auto curr_mod_time = FileSystem::Instance().GetModificationTime(656      m_support_file_nsp->GetSpecOnly());657  return curr_mod_time != llvm::sys::TimePoint<>() &&658         m_mod_time != curr_mod_time;659}660 661bool SourceManager::File::PathRemappingIsStale() const {662  if (TargetSP target_sp = m_target_wp.lock())663    return GetSourceMapModificationID() !=664           target_sp->GetSourcePathMap().GetModificationID();665  return false;666}667 668size_t SourceManager::File::DisplaySourceLines(uint32_t line,669                                               std::optional<size_t> column,670                                               uint32_t context_before,671                                               uint32_t context_after,672                                               Stream *s) {673  // Nothing to write if there's no stream.674  if (!s)675    return 0;676 677  // Sanity check m_data_sp before proceeding.678  if (!m_data_sp)679    return 0;680 681  size_t bytes_written = s->GetWrittenBytes();682 683  auto debugger_sp = m_debugger_wp.lock();684 685  HighlightStyle style;686  // Use the default Vim style if source highlighting is enabled.687  if (should_highlight_source(debugger_sp))688    style = HighlightStyle::MakeVimStyle();689 690  // If we should mark the stop column with color codes, then copy the prefix691  // and suffix to our color style.692  if (should_show_stop_column_with_ansi(debugger_sp))693    style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),694                       debugger_sp->GetStopShowColumnAnsiSuffix());695 696  HighlighterManager mgr;697  std::string path =698      GetSupportFile()->GetSpecOnly().GetPath(/*denormalize*/ false);699  // FIXME: Find a way to get the definitive language this file was written in700  // and pass it to the highlighter.701  const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);702 703  const uint32_t start_line =704      line <= context_before ? 1 : line - context_before;705  const uint32_t start_line_offset = GetLineOffset(start_line);706  if (start_line_offset != UINT32_MAX) {707    const uint32_t end_line = line + context_after;708    uint32_t end_line_offset = GetLineOffset(end_line + 1);709    if (end_line_offset == UINT32_MAX)710      end_line_offset = m_data_sp->GetByteSize();711 712    assert(start_line_offset <= end_line_offset);713    if (start_line_offset < end_line_offset) {714      size_t count = end_line_offset - start_line_offset;715      const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;716 717      auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);718 719      h.Highlight(style, ref, column, "", *s);720 721      // Ensure we get an end of line character one way or another.722      if (!is_newline_char(ref.back()))723        s->EOL();724    }725  }726  return s->GetWrittenBytes() - bytes_written;727}728 729void SourceManager::File::FindLinesMatchingRegex(730    RegularExpression &regex, uint32_t start_line, uint32_t end_line,731    std::vector<uint32_t> &match_lines) {732  match_lines.clear();733 734  if (!LineIsValid(start_line) ||735      (end_line != UINT32_MAX && !LineIsValid(end_line)))736    return;737  if (start_line > end_line)738    return;739 740  for (uint32_t line_no = start_line; line_no < end_line; line_no++) {741    std::string buffer;742    if (!GetLine(line_no, buffer))743      break;744    if (regex.Execute(buffer)) {745      match_lines.push_back(line_no);746    }747  }748}749 750bool lldb_private::operator==(const SourceManager::File &lhs,751                              const SourceManager::File &rhs) {752  if (!lhs.GetSupportFile()->Equal(*rhs.GetSupportFile(),753                                   SupportFile::eEqualChecksumIfSet))754    return false;755  return lhs.m_mod_time == rhs.m_mod_time;756}757 758bool SourceManager::File::CalculateLineOffsets(uint32_t line) {759  line =760      UINT32_MAX; // TODO: take this line out when we support partial indexing761  if (line == UINT32_MAX) {762    // Already done?763    if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)764      return true;765 766    if (m_offsets.empty()) {767      if (m_data_sp.get() == nullptr)768        return false;769 770      const char *start = (const char *)m_data_sp->GetBytes();771      if (start) {772        const char *end = start + m_data_sp->GetByteSize();773 774        // Calculate all line offsets from scratch775 776        // Push a 1 at index zero to indicate the file has been completely777        // indexed.778        m_offsets.push_back(UINT32_MAX);779        const char *s;780        for (s = start; s < end; ++s) {781          char curr_ch = *s;782          if (is_newline_char(curr_ch)) {783            if (s + 1 < end) {784              char next_ch = s[1];785              if (is_newline_char(next_ch)) {786                if (curr_ch != next_ch)787                  ++s;788              }789            }790            m_offsets.push_back(s + 1 - start);791          }792        }793        if (!m_offsets.empty()) {794          if (m_offsets.back() < size_t(end - start))795            m_offsets.push_back(end - start);796        }797        return true;798      }799    } else {800      // Some lines have been populated, start where we last left off801      assert("Not implemented yet" && false);802    }803 804  } else {805    // Calculate all line offsets up to "line"806    assert("Not implemented yet" && false);807  }808  return false;809}810 811bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {812  if (!LineIsValid(line_no))813    return false;814 815  size_t start_offset = GetLineOffset(line_no);816  size_t end_offset = GetLineOffset(line_no + 1);817  if (end_offset == UINT32_MAX) {818    end_offset = m_data_sp->GetByteSize();819  }820  buffer.assign((const char *)m_data_sp->GetBytes() + start_offset,821                end_offset - start_offset);822 823  return true;824}825 826void SourceManager::SourceFileCache::AddSourceFile(const FileSpec &file_spec,827                                                   FileSP file_sp) {828  llvm::sys::ScopedWriter guard(m_mutex);829 830  assert(file_sp && "invalid FileSP");831 832  AddSourceFileImpl(file_spec, file_sp);833  const FileSpec &resolved_file_spec = file_sp->GetSupportFile()->GetSpecOnly();834  if (file_spec != resolved_file_spec)835    AddSourceFileImpl(file_sp->GetSupportFile()->GetSpecOnly(), file_sp);836}837 838void SourceManager::SourceFileCache::RemoveSourceFile(const FileSP &file_sp) {839  llvm::sys::ScopedWriter guard(m_mutex);840 841  assert(file_sp && "invalid FileSP");842 843  // Iterate over all the elements in the cache.844  // This is expensive but a relatively uncommon operation.845  auto it = m_file_cache.begin();846  while (it != m_file_cache.end()) {847    if (it->second == file_sp)848      it = m_file_cache.erase(it);849    else850      it++;851  }852}853 854void SourceManager::SourceFileCache::AddSourceFileImpl(855    const FileSpec &file_spec, FileSP file_sp) {856  FileCache::iterator pos = m_file_cache.find(file_spec);857  if (pos == m_file_cache.end()) {858    m_file_cache[file_spec] = file_sp;859  } else {860    if (file_sp != pos->second)861      m_file_cache[file_spec] = file_sp;862  }863}864 865SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(866    const FileSpec &file_spec) const {867  llvm::sys::ScopedReader guard(m_mutex);868 869  FileCache::const_iterator pos = m_file_cache.find(file_spec);870  if (pos != m_file_cache.end())871    return pos->second;872  return {};873}874 875void SourceManager::SourceFileCache::Dump(Stream &stream) const {876  // clang-format off877  stream << "Modification time   MD5 Checksum (on-disk)           MD5 Checksum (line table)        Lines    Path\n";878  stream << "------------------- -------------------------------- -------------------------------- -------- --------------------------------\n";879  // clang-format on880  for (auto &entry : m_file_cache) {881    if (!entry.second)882      continue;883    FileSP file = entry.second;884    stream.Format("{0:%Y-%m-%d %H:%M:%S} {1,32} {2,32} {3,8:d} {4}\n",885                  file->GetTimestamp(), toString(file->GetChecksum()),886                  toString(file->GetSupportFile()->GetChecksum()),887                  file->GetNumLines(), entry.first.GetPath());888  }889}890