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