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