Path: blob/main/contrib/llvm-project/lldb/source/Core/SourceManager.cpp
39587 views
//===-- SourceManager.cpp -------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Core/SourceManager.h"910#include "lldb/Core/Address.h"11#include "lldb/Core/AddressRange.h"12#include "lldb/Core/Debugger.h"13#include "lldb/Core/FormatEntity.h"14#include "lldb/Core/Highlighter.h"15#include "lldb/Core/Module.h"16#include "lldb/Core/ModuleList.h"17#include "lldb/Host/FileSystem.h"18#include "lldb/Symbol/CompileUnit.h"19#include "lldb/Symbol/Function.h"20#include "lldb/Symbol/LineEntry.h"21#include "lldb/Symbol/SymbolContext.h"22#include "lldb/Target/PathMappingList.h"23#include "lldb/Target/Process.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/LLDBLog.h"29#include "lldb/Utility/Log.h"30#include "lldb/Utility/RegularExpression.h"31#include "lldb/Utility/Stream.h"32#include "lldb/lldb-enumerations.h"3334#include "llvm/ADT/Twine.h"3536#include <memory>37#include <optional>38#include <utility>3940#include <cassert>41#include <cstdio>4243namespace lldb_private {44class ExecutionContext;45}46namespace lldb_private {47class ValueObject;48}4950using namespace lldb;51using namespace lldb_private;5253static inline bool is_newline_char(char ch) { return ch == '\n' || ch == '\r'; }5455static void resolve_tilde(FileSpec &file_spec) {56if (!FileSystem::Instance().Exists(file_spec) &&57file_spec.GetDirectory() &&58file_spec.GetDirectory().GetCString()[0] == '~') {59FileSystem::Instance().Resolve(file_spec);60}61}6263// SourceManager constructor64SourceManager::SourceManager(const TargetSP &target_sp)65: m_last_line(0), m_last_count(0), m_default_set(false),66m_target_wp(target_sp),67m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}6869SourceManager::SourceManager(const DebuggerSP &debugger_sp)70: m_last_line(0), m_last_count(0), m_default_set(false), m_target_wp(),71m_debugger_wp(debugger_sp) {}7273// Destructor74SourceManager::~SourceManager() = default;7576SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) {77if (!file_spec)78return {};7980Log *log = GetLog(LLDBLog::Source);8182DebuggerSP debugger_sp(m_debugger_wp.lock());83TargetSP target_sp(m_target_wp.lock());8485if (!debugger_sp || !debugger_sp->GetUseSourceCache()) {86LLDB_LOG(log, "Source file caching disabled: creating new source file: {0}",87file_spec);88if (target_sp)89return std::make_shared<File>(file_spec, target_sp);90return std::make_shared<File>(file_spec, debugger_sp);91}9293ProcessSP process_sp = target_sp ? target_sp->GetProcessSP() : ProcessSP();9495// Check the process source cache first. This is the fast path which avoids96// touching the file system unless the path remapping has changed.97if (process_sp) {98if (FileSP file_sp =99process_sp->GetSourceFileCache().FindSourceFile(file_spec)) {100LLDB_LOG(log, "Found source file in the process cache: {0}", file_spec);101if (file_sp->PathRemappingIsStale()) {102LLDB_LOG(log, "Path remapping is stale: removing file from caches: {0}",103file_spec);104105// Remove the file from the debugger and process cache. Otherwise we'll106// hit the same issue again below when querying the debugger cache.107debugger_sp->GetSourceFileCache().RemoveSourceFile(file_sp);108process_sp->GetSourceFileCache().RemoveSourceFile(file_sp);109110file_sp.reset();111} else {112return file_sp;113}114}115}116117// Cache miss in the process cache. Check the debugger source cache.118FileSP file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);119120// We found the file in the debugger cache. Check if anything invalidated our121// cache result.122if (file_sp)123LLDB_LOG(log, "Found source file in the debugger cache: {0}", file_spec);124125// Check if the path remapping has changed.126if (file_sp && file_sp->PathRemappingIsStale()) {127LLDB_LOG(log, "Path remapping is stale: {0}", file_spec);128file_sp.reset();129}130131// Check if the modification time has changed.132if (file_sp && file_sp->ModificationTimeIsStale()) {133LLDB_LOG(log, "Modification time is stale: {0}", file_spec);134file_sp.reset();135}136137// Check if the file exists on disk.138if (file_sp && !FileSystem::Instance().Exists(file_sp->GetFileSpec())) {139LLDB_LOG(log, "File doesn't exist on disk: {0}", file_spec);140file_sp.reset();141}142143// If at this point we don't have a valid file, it means we either didn't find144// it in the debugger cache or something caused it to be invalidated.145if (!file_sp) {146LLDB_LOG(log, "Creating and caching new source file: {0}", file_spec);147148// (Re)create the file.149if (target_sp)150file_sp = std::make_shared<File>(file_spec, target_sp);151else152file_sp = std::make_shared<File>(file_spec, debugger_sp);153154// Add the file to the debugger and process cache. If the file was155// invalidated, this will overwrite it.156debugger_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);157if (process_sp)158process_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);159}160161return file_sp;162}163164static bool should_highlight_source(DebuggerSP debugger_sp) {165if (!debugger_sp)166return false;167168// We don't use ANSI stop column formatting if the debugger doesn't think it169// should be using color.170if (!debugger_sp->GetUseColor())171return false;172173return debugger_sp->GetHighlightSource();174}175176static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {177// We don't use ANSI stop column formatting if we can't lookup values from178// the debugger.179if (!debugger_sp)180return false;181182// We don't use ANSI stop column formatting if the debugger doesn't think it183// should be using color.184if (!debugger_sp->GetUseColor())185return false;186187// We only use ANSI stop column formatting if we're either supposed to show188// ANSI where available (which we know we have when we get to this point), or189// if we're only supposed to use ANSI.190const auto value = debugger_sp->GetStopShowColumn();191return ((value == eStopShowColumnAnsiOrCaret) ||192(value == eStopShowColumnAnsi));193}194195static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {196// We don't use text-based stop column formatting if we can't lookup values197// from the debugger.198if (!debugger_sp)199return false;200201// If we're asked to show the first available of ANSI or caret, then we do202// show the caret when ANSI is not available.203const auto value = debugger_sp->GetStopShowColumn();204if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())205return true;206207// The only other time we use caret is if we're explicitly asked to show208// caret.209return value == eStopShowColumnCaret;210}211212static bool should_show_stop_line_with_ansi(DebuggerSP debugger_sp) {213return debugger_sp && debugger_sp->GetUseColor();214}215216size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(217uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,218const char *current_line_cstr, Stream *s,219const SymbolContextList *bp_locs) {220if (count == 0)221return 0;222223Stream::ByteDelta delta(*s);224225if (start_line == 0) {226if (m_last_line != 0 && m_last_line != UINT32_MAX)227start_line = m_last_line + m_last_count;228else229start_line = 1;230}231232if (!m_default_set) {233FileSpec tmp_spec;234uint32_t tmp_line;235GetDefaultFileAndLine(tmp_spec, tmp_line);236}237238m_last_line = start_line;239m_last_count = count;240241if (FileSP last_file_sp = GetLastFile()) {242const uint32_t end_line = start_line + count - 1;243for (uint32_t line = start_line; line <= end_line; ++line) {244if (!last_file_sp->LineIsValid(line)) {245m_last_line = UINT32_MAX;246break;247}248249std::string prefix;250if (bp_locs) {251uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);252253if (bp_count > 0)254prefix = llvm::formatv("[{0}]", bp_count);255else256prefix = " ";257}258259char buffer[3];260snprintf(buffer, sizeof(buffer), "%2.2s",261(line == curr_line) ? current_line_cstr : "");262std::string current_line_highlight(buffer);263264auto debugger_sp = m_debugger_wp.lock();265if (should_show_stop_line_with_ansi(debugger_sp)) {266current_line_highlight = ansi::FormatAnsiTerminalCodes(267(debugger_sp->GetStopShowLineMarkerAnsiPrefix() +268current_line_highlight +269debugger_sp->GetStopShowLineMarkerAnsiSuffix())270.str());271}272273s->Printf("%s%s %-4u\t", prefix.c_str(), current_line_highlight.c_str(),274line);275276// So far we treated column 0 as a special 'no column value', but277// DisplaySourceLines starts counting columns from 0 (and no column is278// expressed by passing an empty optional).279std::optional<size_t> columnToHighlight;280if (line == curr_line && column)281columnToHighlight = column - 1;282283size_t this_line_size =284last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);285if (column != 0 && line == curr_line &&286should_show_stop_column_with_caret(debugger_sp)) {287// Display caret cursor.288std::string src_line;289last_file_sp->GetLine(line, src_line);290s->Printf(" \t");291// Insert a space for every non-tab character in the source line.292for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)293s->PutChar(src_line[i] == '\t' ? '\t' : ' ');294// Now add the caret.295s->Printf("^\n");296}297if (this_line_size == 0) {298m_last_line = UINT32_MAX;299break;300}301}302}303return *delta;304}305306size_t SourceManager::DisplaySourceLinesWithLineNumbers(307const FileSpec &file_spec, uint32_t line, uint32_t column,308uint32_t context_before, uint32_t context_after,309const char *current_line_cstr, Stream *s,310const SymbolContextList *bp_locs) {311FileSP file_sp(GetFile(file_spec));312313uint32_t start_line;314uint32_t count = context_before + context_after + 1;315if (line > context_before)316start_line = line - context_before;317else318start_line = 1;319320FileSP last_file_sp(GetLastFile());321if (last_file_sp.get() != file_sp.get()) {322if (line == 0)323m_last_line = 0;324m_last_file_spec = file_spec;325}326return DisplaySourceLinesWithLineNumbersUsingLastFile(327start_line, count, line, column, current_line_cstr, s, bp_locs);328}329330size_t SourceManager::DisplayMoreWithLineNumbers(331Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {332// If we get called before anybody has set a default file and line, then try333// to figure it out here.334FileSP last_file_sp(GetLastFile());335const bool have_default_file_line = last_file_sp && m_last_line > 0;336if (!m_default_set) {337FileSpec tmp_spec;338uint32_t tmp_line;339GetDefaultFileAndLine(tmp_spec, tmp_line);340}341342if (last_file_sp) {343if (m_last_line == UINT32_MAX)344return 0;345346if (reverse && m_last_line == 1)347return 0;348349if (count > 0)350m_last_count = count;351else if (m_last_count == 0)352m_last_count = 10;353354if (m_last_line > 0) {355if (reverse) {356// If this is the first time we've done a reverse, then back up one357// more time so we end up showing the chunk before the last one we've358// shown:359if (m_last_line > m_last_count)360m_last_line -= m_last_count;361else362m_last_line = 1;363} else if (have_default_file_line)364m_last_line += m_last_count;365} else366m_last_line = 1;367368const uint32_t column = 0;369return DisplaySourceLinesWithLineNumbersUsingLastFile(370m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);371}372return 0;373}374375bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,376uint32_t line) {377m_default_set = true;378FileSP file_sp(GetFile(file_spec));379380if (file_sp) {381m_last_line = line;382m_last_file_spec = file_spec;383return true;384} else {385return false;386}387}388389bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {390if (FileSP last_file_sp = GetLastFile()) {391file_spec = m_last_file_spec;392line = m_last_line;393return true;394} else if (!m_default_set) {395TargetSP target_sp(m_target_wp.lock());396397if (target_sp) {398// If nobody has set the default file and line then try here. If there's399// no executable, then we will try again later when there is one.400// Otherwise, if we can't find it we won't look again, somebody will have401// to set it (for instance when we stop somewhere...)402Module *executable_ptr = target_sp->GetExecutableModulePointer();403if (executable_ptr) {404SymbolContextList sc_list;405ConstString main_name("main");406407ModuleFunctionSearchOptions function_options;408function_options.include_symbols =409false; // Force it to be a debug symbol.410function_options.include_inlines = true;411executable_ptr->FindFunctions(main_name, CompilerDeclContext(),412lldb::eFunctionNameTypeBase,413function_options, sc_list);414for (const SymbolContext &sc : sc_list) {415if (sc.function) {416lldb_private::LineEntry line_entry;417if (sc.function->GetAddressRange()418.GetBaseAddress()419.CalculateSymbolContextLineEntry(line_entry)) {420SetDefaultFileAndLine(line_entry.GetFile(), line_entry.line);421file_spec = m_last_file_spec;422line = m_last_line;423return true;424}425}426}427}428}429}430return false;431}432433void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,434RegularExpression ®ex,435uint32_t start_line,436uint32_t end_line,437std::vector<uint32_t> &match_lines) {438match_lines.clear();439FileSP file_sp = GetFile(file_spec);440if (!file_sp)441return;442return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,443match_lines);444}445446SourceManager::File::File(const FileSpec &file_spec,447lldb::DebuggerSP debugger_sp)448: m_file_spec_orig(file_spec), m_file_spec(), m_mod_time(),449m_debugger_wp(debugger_sp), m_target_wp(TargetSP()) {450CommonInitializer(file_spec, {});451}452453SourceManager::File::File(const FileSpec &file_spec, TargetSP target_sp)454: m_file_spec_orig(file_spec), m_file_spec(), m_mod_time(),455m_debugger_wp(target_sp ? target_sp->GetDebugger().shared_from_this()456: DebuggerSP()),457m_target_wp(target_sp) {458CommonInitializer(file_spec, target_sp);459}460461void SourceManager::File::CommonInitializer(const FileSpec &file_spec,462TargetSP target_sp) {463// Set the file and update the modification time.464SetFileSpec(file_spec);465466// Always update the source map modification ID if we have a target.467if (target_sp)468m_source_map_mod_id = target_sp->GetSourcePathMap().GetModificationID();469470// File doesn't exist.471if (m_mod_time == llvm::sys::TimePoint<>()) {472if (target_sp) {473// If this is just a file name, try finding it in the target.474if (!file_spec.GetDirectory() && file_spec.GetFilename()) {475bool check_inlines = false;476SymbolContextList sc_list;477size_t num_matches =478target_sp->GetImages().ResolveSymbolContextForFilePath(479file_spec.GetFilename().AsCString(), 0, check_inlines,480SymbolContextItem(eSymbolContextModule |481eSymbolContextCompUnit),482sc_list);483bool got_multiple = false;484if (num_matches != 0) {485if (num_matches > 1) {486CompileUnit *test_cu = nullptr;487for (const SymbolContext &sc : sc_list) {488if (sc.comp_unit) {489if (test_cu) {490if (test_cu != sc.comp_unit)491got_multiple = true;492break;493} else494test_cu = sc.comp_unit;495}496}497}498if (!got_multiple) {499SymbolContext sc;500sc_list.GetContextAtIndex(0, sc);501if (sc.comp_unit)502SetFileSpec(sc.comp_unit->GetPrimaryFile());503}504}505}506507// Try remapping the file if it doesn't exist.508if (!FileSystem::Instance().Exists(m_file_spec)) {509// Check target specific source remappings (i.e., the510// target.source-map setting), then fall back to the module511// specific remapping (i.e., the .dSYM remapping dictionary).512auto remapped = target_sp->GetSourcePathMap().FindFile(m_file_spec);513if (!remapped) {514FileSpec new_spec;515if (target_sp->GetImages().FindSourceFile(m_file_spec, new_spec))516remapped = new_spec;517}518if (remapped)519SetFileSpec(*remapped);520}521}522}523524// If the file exists, read in the data.525if (m_mod_time != llvm::sys::TimePoint<>())526m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);527}528529void SourceManager::File::SetFileSpec(FileSpec file_spec) {530resolve_tilde(file_spec);531m_file_spec = std::move(file_spec);532m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);533}534535uint32_t SourceManager::File::GetLineOffset(uint32_t line) {536if (line == 0)537return UINT32_MAX;538539if (line == 1)540return 0;541542if (CalculateLineOffsets(line)) {543if (line < m_offsets.size())544return m_offsets[line - 1]; // yes we want "line - 1" in the index545}546return UINT32_MAX;547}548549uint32_t SourceManager::File::GetNumLines() {550CalculateLineOffsets();551return m_offsets.size();552}553554const char *SourceManager::File::PeekLineData(uint32_t line) {555if (!LineIsValid(line))556return nullptr;557558size_t line_offset = GetLineOffset(line);559if (line_offset < m_data_sp->GetByteSize())560return (const char *)m_data_sp->GetBytes() + line_offset;561return nullptr;562}563564uint32_t SourceManager::File::GetLineLength(uint32_t line,565bool include_newline_chars) {566if (!LineIsValid(line))567return false;568569size_t start_offset = GetLineOffset(line);570size_t end_offset = GetLineOffset(line + 1);571if (end_offset == UINT32_MAX)572end_offset = m_data_sp->GetByteSize();573574if (end_offset > start_offset) {575uint32_t length = end_offset - start_offset;576if (!include_newline_chars) {577const char *line_start =578(const char *)m_data_sp->GetBytes() + start_offset;579while (length > 0) {580const char last_char = line_start[length - 1];581if ((last_char == '\r') || (last_char == '\n'))582--length;583else584break;585}586}587return length;588}589return 0;590}591592bool SourceManager::File::LineIsValid(uint32_t line) {593if (line == 0)594return false;595596if (CalculateLineOffsets(line))597return line < m_offsets.size();598return false;599}600601bool SourceManager::File::ModificationTimeIsStale() const {602// TODO: use host API to sign up for file modifications to anything in our603// source cache and only update when we determine a file has been updated.604// For now we check each time we want to display info for the file.605auto curr_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);606return curr_mod_time != llvm::sys::TimePoint<>() &&607m_mod_time != curr_mod_time;608}609610bool SourceManager::File::PathRemappingIsStale() const {611if (TargetSP target_sp = m_target_wp.lock())612return GetSourceMapModificationID() !=613target_sp->GetSourcePathMap().GetModificationID();614return false;615}616617size_t SourceManager::File::DisplaySourceLines(uint32_t line,618std::optional<size_t> column,619uint32_t context_before,620uint32_t context_after,621Stream *s) {622// Nothing to write if there's no stream.623if (!s)624return 0;625626// Sanity check m_data_sp before proceeding.627if (!m_data_sp)628return 0;629630size_t bytes_written = s->GetWrittenBytes();631632auto debugger_sp = m_debugger_wp.lock();633634HighlightStyle style;635// Use the default Vim style if source highlighting is enabled.636if (should_highlight_source(debugger_sp))637style = HighlightStyle::MakeVimStyle();638639// If we should mark the stop column with color codes, then copy the prefix640// and suffix to our color style.641if (should_show_stop_column_with_ansi(debugger_sp))642style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),643debugger_sp->GetStopShowColumnAnsiSuffix());644645HighlighterManager mgr;646std::string path = GetFileSpec().GetPath(/*denormalize*/ false);647// FIXME: Find a way to get the definitive language this file was written in648// and pass it to the highlighter.649const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);650651const uint32_t start_line =652line <= context_before ? 1 : line - context_before;653const uint32_t start_line_offset = GetLineOffset(start_line);654if (start_line_offset != UINT32_MAX) {655const uint32_t end_line = line + context_after;656uint32_t end_line_offset = GetLineOffset(end_line + 1);657if (end_line_offset == UINT32_MAX)658end_line_offset = m_data_sp->GetByteSize();659660assert(start_line_offset <= end_line_offset);661if (start_line_offset < end_line_offset) {662size_t count = end_line_offset - start_line_offset;663const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;664665auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);666667h.Highlight(style, ref, column, "", *s);668669// Ensure we get an end of line character one way or another.670if (!is_newline_char(ref.back()))671s->EOL();672}673}674return s->GetWrittenBytes() - bytes_written;675}676677void SourceManager::File::FindLinesMatchingRegex(678RegularExpression ®ex, uint32_t start_line, uint32_t end_line,679std::vector<uint32_t> &match_lines) {680match_lines.clear();681682if (!LineIsValid(start_line) ||683(end_line != UINT32_MAX && !LineIsValid(end_line)))684return;685if (start_line > end_line)686return;687688for (uint32_t line_no = start_line; line_no < end_line; line_no++) {689std::string buffer;690if (!GetLine(line_no, buffer))691break;692if (regex.Execute(buffer)) {693match_lines.push_back(line_no);694}695}696}697698bool lldb_private::operator==(const SourceManager::File &lhs,699const SourceManager::File &rhs) {700if (lhs.m_file_spec != rhs.m_file_spec)701return false;702return lhs.m_mod_time == rhs.m_mod_time;703}704705bool SourceManager::File::CalculateLineOffsets(uint32_t line) {706line =707UINT32_MAX; // TODO: take this line out when we support partial indexing708if (line == UINT32_MAX) {709// Already done?710if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)711return true;712713if (m_offsets.empty()) {714if (m_data_sp.get() == nullptr)715return false;716717const char *start = (const char *)m_data_sp->GetBytes();718if (start) {719const char *end = start + m_data_sp->GetByteSize();720721// Calculate all line offsets from scratch722723// Push a 1 at index zero to indicate the file has been completely724// indexed.725m_offsets.push_back(UINT32_MAX);726const char *s;727for (s = start; s < end; ++s) {728char curr_ch = *s;729if (is_newline_char(curr_ch)) {730if (s + 1 < end) {731char next_ch = s[1];732if (is_newline_char(next_ch)) {733if (curr_ch != next_ch)734++s;735}736}737m_offsets.push_back(s + 1 - start);738}739}740if (!m_offsets.empty()) {741if (m_offsets.back() < size_t(end - start))742m_offsets.push_back(end - start);743}744return true;745}746} else {747// Some lines have been populated, start where we last left off748assert("Not implemented yet" && false);749}750751} else {752// Calculate all line offsets up to "line"753assert("Not implemented yet" && false);754}755return false;756}757758bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {759if (!LineIsValid(line_no))760return false;761762size_t start_offset = GetLineOffset(line_no);763size_t end_offset = GetLineOffset(line_no + 1);764if (end_offset == UINT32_MAX) {765end_offset = m_data_sp->GetByteSize();766}767buffer.assign((const char *)m_data_sp->GetBytes() + start_offset,768end_offset - start_offset);769770return true;771}772773void SourceManager::SourceFileCache::AddSourceFile(const FileSpec &file_spec,774FileSP file_sp) {775llvm::sys::ScopedWriter guard(m_mutex);776777assert(file_sp && "invalid FileSP");778779AddSourceFileImpl(file_spec, file_sp);780const FileSpec &resolved_file_spec = file_sp->GetFileSpec();781if (file_spec != resolved_file_spec)782AddSourceFileImpl(file_sp->GetFileSpec(), file_sp);783}784785void SourceManager::SourceFileCache::RemoveSourceFile(const FileSP &file_sp) {786llvm::sys::ScopedWriter guard(m_mutex);787788assert(file_sp && "invalid FileSP");789790// Iterate over all the elements in the cache.791// This is expensive but a relatively uncommon operation.792auto it = m_file_cache.begin();793while (it != m_file_cache.end()) {794if (it->second == file_sp)795it = m_file_cache.erase(it);796else797it++;798}799}800801void SourceManager::SourceFileCache::AddSourceFileImpl(802const FileSpec &file_spec, FileSP file_sp) {803FileCache::iterator pos = m_file_cache.find(file_spec);804if (pos == m_file_cache.end()) {805m_file_cache[file_spec] = file_sp;806} else {807if (file_sp != pos->second)808m_file_cache[file_spec] = file_sp;809}810}811812SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(813const FileSpec &file_spec) const {814llvm::sys::ScopedReader guard(m_mutex);815816FileCache::const_iterator pos = m_file_cache.find(file_spec);817if (pos != m_file_cache.end())818return pos->second;819return {};820}821822void SourceManager::SourceFileCache::Dump(Stream &stream) const {823stream << "Modification time Lines Path\n";824stream << "------------------- -------- --------------------------------\n";825for (auto &entry : m_file_cache) {826if (!entry.second)827continue;828FileSP file = entry.second;829stream.Format("{0:%Y-%m-%d %H:%M:%S} {1,8:d} {2}\n", file->GetTimestamp(),830file->GetNumLines(), entry.first.GetPath());831}832}833834835