xref: /freebsd/contrib/llvm-project/lldb/source/Core/SourceManager.cpp (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
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       sprintf(buffer, "%2.2s", (line == curr_line) ? current_line_cstr : "");
209       std::string current_line_highlight(buffer);
210 
211       auto debugger_sp = m_debugger_wp.lock();
212       if (should_show_stop_line_with_ansi(debugger_sp)) {
213         current_line_highlight = ansi::FormatAnsiTerminalCodes(
214             (debugger_sp->GetStopShowLineMarkerAnsiPrefix() +
215              current_line_highlight +
216              debugger_sp->GetStopShowLineMarkerAnsiSuffix())
217                 .str());
218       }
219 
220       s->Printf("%s%s %-4u\t", prefix.c_str(), current_line_highlight.c_str(),
221                 line);
222 
223       // So far we treated column 0 as a special 'no column value', but
224       // DisplaySourceLines starts counting columns from 0 (and no column is
225       // expressed by passing an empty optional).
226       std::optional<size_t> columnToHighlight;
227       if (line == curr_line && column)
228         columnToHighlight = column - 1;
229 
230       size_t this_line_size =
231           last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);
232       if (column != 0 && line == curr_line &&
233           should_show_stop_column_with_caret(debugger_sp)) {
234         // Display caret cursor.
235         std::string src_line;
236         last_file_sp->GetLine(line, src_line);
237         s->Printf("    \t");
238         // Insert a space for every non-tab character in the source line.
239         for (size_t i = 0; i + 1 < column && i < src_line.length(); ++i)
240           s->PutChar(src_line[i] == '\t' ? '\t' : ' ');
241         // Now add the caret.
242         s->Printf("^\n");
243       }
244       if (this_line_size == 0) {
245         m_last_line = UINT32_MAX;
246         break;
247       }
248     }
249   }
250   return *delta;
251 }
252 
253 size_t SourceManager::DisplaySourceLinesWithLineNumbers(
254     const FileSpec &file_spec, uint32_t line, uint32_t column,
255     uint32_t context_before, uint32_t context_after,
256     const char *current_line_cstr, Stream *s,
257     const SymbolContextList *bp_locs) {
258   FileSP file_sp(GetFile(file_spec));
259 
260   uint32_t start_line;
261   uint32_t count = context_before + context_after + 1;
262   if (line > context_before)
263     start_line = line - context_before;
264   else
265     start_line = 1;
266 
267   FileSP last_file_sp(GetLastFile());
268   if (last_file_sp.get() != file_sp.get()) {
269     if (line == 0)
270       m_last_line = 0;
271     m_last_file_spec = file_spec;
272   }
273   return DisplaySourceLinesWithLineNumbersUsingLastFile(
274       start_line, count, line, column, current_line_cstr, s, bp_locs);
275 }
276 
277 size_t SourceManager::DisplayMoreWithLineNumbers(
278     Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {
279   // If we get called before anybody has set a default file and line, then try
280   // to figure it out here.
281   FileSP last_file_sp(GetLastFile());
282   const bool have_default_file_line = last_file_sp && m_last_line > 0;
283   if (!m_default_set) {
284     FileSpec tmp_spec;
285     uint32_t tmp_line;
286     GetDefaultFileAndLine(tmp_spec, tmp_line);
287   }
288 
289   if (last_file_sp) {
290     if (m_last_line == UINT32_MAX)
291       return 0;
292 
293     if (reverse && m_last_line == 1)
294       return 0;
295 
296     if (count > 0)
297       m_last_count = count;
298     else if (m_last_count == 0)
299       m_last_count = 10;
300 
301     if (m_last_line > 0) {
302       if (reverse) {
303         // If this is the first time we've done a reverse, then back up one
304         // more time so we end up showing the chunk before the last one we've
305         // shown:
306         if (m_last_line > m_last_count)
307           m_last_line -= m_last_count;
308         else
309           m_last_line = 1;
310       } else if (have_default_file_line)
311         m_last_line += m_last_count;
312     } else
313       m_last_line = 1;
314 
315     const uint32_t column = 0;
316     return DisplaySourceLinesWithLineNumbersUsingLastFile(
317         m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);
318   }
319   return 0;
320 }
321 
322 bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,
323                                           uint32_t line) {
324   m_default_set = true;
325   FileSP file_sp(GetFile(file_spec));
326 
327   if (file_sp) {
328     m_last_line = line;
329     m_last_file_spec = file_spec;
330     return true;
331   } else {
332     return false;
333   }
334 }
335 
336 bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {
337   if (FileSP last_file_sp = GetLastFile()) {
338     file_spec = m_last_file_spec;
339     line = m_last_line;
340     return true;
341   } else if (!m_default_set) {
342     TargetSP target_sp(m_target_wp.lock());
343 
344     if (target_sp) {
345       // If nobody has set the default file and line then try here.  If there's
346       // no executable, then we will try again later when there is one.
347       // Otherwise, if we can't find it we won't look again, somebody will have
348       // to set it (for instance when we stop somewhere...)
349       Module *executable_ptr = target_sp->GetExecutableModulePointer();
350       if (executable_ptr) {
351         SymbolContextList sc_list;
352         ConstString main_name("main");
353 
354         ModuleFunctionSearchOptions function_options;
355         function_options.include_symbols =
356             false; // Force it to be a debug symbol.
357         function_options.include_inlines = true;
358         executable_ptr->FindFunctions(main_name, CompilerDeclContext(),
359                                       lldb::eFunctionNameTypeBase,
360                                       function_options, sc_list);
361         size_t num_matches = sc_list.GetSize();
362         for (size_t idx = 0; idx < num_matches; idx++) {
363           SymbolContext sc;
364           sc_list.GetContextAtIndex(idx, sc);
365           if (sc.function) {
366             lldb_private::LineEntry line_entry;
367             if (sc.function->GetAddressRange()
368                     .GetBaseAddress()
369                     .CalculateSymbolContextLineEntry(line_entry)) {
370               SetDefaultFileAndLine(line_entry.file, line_entry.line);
371               file_spec = m_last_file_spec;
372               line = m_last_line;
373               return true;
374             }
375           }
376         }
377       }
378     }
379   }
380   return false;
381 }
382 
383 void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
384                                            RegularExpression &regex,
385                                            uint32_t start_line,
386                                            uint32_t end_line,
387                                            std::vector<uint32_t> &match_lines) {
388   match_lines.clear();
389   FileSP file_sp = GetFile(file_spec);
390   if (!file_sp)
391     return;
392   return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
393                                          match_lines);
394 }
395 
396 SourceManager::File::File(const FileSpec &file_spec,
397                           lldb::DebuggerSP debugger_sp)
398     : m_file_spec_orig(file_spec), m_file_spec(file_spec),
399       m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
400       m_debugger_wp(debugger_sp) {
401   CommonInitializer(file_spec, nullptr);
402 }
403 
404 SourceManager::File::File(const FileSpec &file_spec, Target *target)
405     : m_file_spec_orig(file_spec), m_file_spec(file_spec),
406       m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
407       m_debugger_wp(target ? target->GetDebugger().shared_from_this()
408                            : DebuggerSP()) {
409   CommonInitializer(file_spec, target);
410 }
411 
412 void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
413                                             Target *target) {
414   if (m_mod_time == llvm::sys::TimePoint<>()) {
415     if (target) {
416       m_source_map_mod_id = target->GetSourcePathMap().GetModificationID();
417 
418       if (!file_spec.GetDirectory() && file_spec.GetFilename()) {
419         // If this is just a file name, lets see if we can find it in the
420         // target:
421         bool check_inlines = false;
422         SymbolContextList sc_list;
423         size_t num_matches =
424             target->GetImages().ResolveSymbolContextForFilePath(
425                 file_spec.GetFilename().AsCString(), 0, check_inlines,
426                 SymbolContextItem(eSymbolContextModule |
427                                   eSymbolContextCompUnit),
428                 sc_list);
429         bool got_multiple = false;
430         if (num_matches != 0) {
431           if (num_matches > 1) {
432             SymbolContext sc;
433             CompileUnit *test_cu = nullptr;
434 
435             for (unsigned i = 0; i < num_matches; i++) {
436               sc_list.GetContextAtIndex(i, sc);
437               if (sc.comp_unit) {
438                 if (test_cu) {
439                   if (test_cu != sc.comp_unit)
440                     got_multiple = true;
441                   break;
442                 } else
443                   test_cu = sc.comp_unit;
444               }
445             }
446           }
447           if (!got_multiple) {
448             SymbolContext sc;
449             sc_list.GetContextAtIndex(0, sc);
450             if (sc.comp_unit)
451               m_file_spec = sc.comp_unit->GetPrimaryFile();
452             m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
453           }
454         }
455       }
456       resolve_tilde(m_file_spec);
457       // Try remapping if m_file_spec does not correspond to an existing file.
458       if (!FileSystem::Instance().Exists(m_file_spec)) {
459         // Check target specific source remappings (i.e., the
460         // target.source-map setting), then fall back to the module
461         // specific remapping (i.e., the .dSYM remapping dictionary).
462         auto remapped = target->GetSourcePathMap().FindFile(m_file_spec);
463         if (!remapped) {
464           FileSpec new_spec;
465           if (target->GetImages().FindSourceFile(m_file_spec, new_spec))
466             remapped = new_spec;
467         }
468         if (remapped) {
469           m_file_spec = *remapped;
470           m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
471         }
472       }
473     }
474   }
475 
476   if (m_mod_time != llvm::sys::TimePoint<>())
477     m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
478 }
479 
480 uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
481   if (line == 0)
482     return UINT32_MAX;
483 
484   if (line == 1)
485     return 0;
486 
487   if (CalculateLineOffsets(line)) {
488     if (line < m_offsets.size())
489       return m_offsets[line - 1]; // yes we want "line - 1" in the index
490   }
491   return UINT32_MAX;
492 }
493 
494 uint32_t SourceManager::File::GetNumLines() {
495   CalculateLineOffsets();
496   return m_offsets.size();
497 }
498 
499 const char *SourceManager::File::PeekLineData(uint32_t line) {
500   if (!LineIsValid(line))
501     return nullptr;
502 
503   size_t line_offset = GetLineOffset(line);
504   if (line_offset < m_data_sp->GetByteSize())
505     return (const char *)m_data_sp->GetBytes() + line_offset;
506   return nullptr;
507 }
508 
509 uint32_t SourceManager::File::GetLineLength(uint32_t line,
510                                             bool include_newline_chars) {
511   if (!LineIsValid(line))
512     return false;
513 
514   size_t start_offset = GetLineOffset(line);
515   size_t end_offset = GetLineOffset(line + 1);
516   if (end_offset == UINT32_MAX)
517     end_offset = m_data_sp->GetByteSize();
518 
519   if (end_offset > start_offset) {
520     uint32_t length = end_offset - start_offset;
521     if (!include_newline_chars) {
522       const char *line_start =
523           (const char *)m_data_sp->GetBytes() + start_offset;
524       while (length > 0) {
525         const char last_char = line_start[length - 1];
526         if ((last_char == '\r') || (last_char == '\n'))
527           --length;
528         else
529           break;
530       }
531     }
532     return length;
533   }
534   return 0;
535 }
536 
537 bool SourceManager::File::LineIsValid(uint32_t line) {
538   if (line == 0)
539     return false;
540 
541   if (CalculateLineOffsets(line))
542     return line < m_offsets.size();
543   return false;
544 }
545 
546 void SourceManager::File::UpdateIfNeeded() {
547   // TODO: use host API to sign up for file modifications to anything in our
548   // source cache and only update when we determine a file has been updated.
549   // For now we check each time we want to display info for the file.
550   auto curr_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
551 
552   if (curr_mod_time != llvm::sys::TimePoint<>() &&
553       m_mod_time != curr_mod_time) {
554     m_mod_time = curr_mod_time;
555     m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
556     m_offsets.clear();
557   }
558 }
559 
560 size_t SourceManager::File::DisplaySourceLines(uint32_t line,
561                                                std::optional<size_t> column,
562                                                uint32_t context_before,
563                                                uint32_t context_after,
564                                                Stream *s) {
565   // Nothing to write if there's no stream.
566   if (!s)
567     return 0;
568 
569   // Sanity check m_data_sp before proceeding.
570   if (!m_data_sp)
571     return 0;
572 
573   size_t bytes_written = s->GetWrittenBytes();
574 
575   auto debugger_sp = m_debugger_wp.lock();
576 
577   HighlightStyle style;
578   // Use the default Vim style if source highlighting is enabled.
579   if (should_highlight_source(debugger_sp))
580     style = HighlightStyle::MakeVimStyle();
581 
582   // If we should mark the stop column with color codes, then copy the prefix
583   // and suffix to our color style.
584   if (should_show_stop_column_with_ansi(debugger_sp))
585     style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),
586                        debugger_sp->GetStopShowColumnAnsiSuffix());
587 
588   HighlighterManager mgr;
589   std::string path = GetFileSpec().GetPath(/*denormalize*/ false);
590   // FIXME: Find a way to get the definitive language this file was written in
591   // and pass it to the highlighter.
592   const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);
593 
594   const uint32_t start_line =
595       line <= context_before ? 1 : line - context_before;
596   const uint32_t start_line_offset = GetLineOffset(start_line);
597   if (start_line_offset != UINT32_MAX) {
598     const uint32_t end_line = line + context_after;
599     uint32_t end_line_offset = GetLineOffset(end_line + 1);
600     if (end_line_offset == UINT32_MAX)
601       end_line_offset = m_data_sp->GetByteSize();
602 
603     assert(start_line_offset <= end_line_offset);
604     if (start_line_offset < end_line_offset) {
605       size_t count = end_line_offset - start_line_offset;
606       const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
607 
608       auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);
609 
610       h.Highlight(style, ref, column, "", *s);
611 
612       // Ensure we get an end of line character one way or another.
613       if (!is_newline_char(ref.back()))
614         s->EOL();
615     }
616   }
617   return s->GetWrittenBytes() - bytes_written;
618 }
619 
620 void SourceManager::File::FindLinesMatchingRegex(
621     RegularExpression &regex, uint32_t start_line, uint32_t end_line,
622     std::vector<uint32_t> &match_lines) {
623   match_lines.clear();
624 
625   if (!LineIsValid(start_line) ||
626       (end_line != UINT32_MAX && !LineIsValid(end_line)))
627     return;
628   if (start_line > end_line)
629     return;
630 
631   for (uint32_t line_no = start_line; line_no < end_line; line_no++) {
632     std::string buffer;
633     if (!GetLine(line_no, buffer))
634       break;
635     if (regex.Execute(buffer)) {
636       match_lines.push_back(line_no);
637     }
638   }
639 }
640 
641 bool lldb_private::operator==(const SourceManager::File &lhs,
642                               const SourceManager::File &rhs) {
643   if (lhs.m_file_spec != rhs.m_file_spec)
644     return false;
645   return lhs.m_mod_time == rhs.m_mod_time;
646 }
647 
648 bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
649   line =
650       UINT32_MAX; // TODO: take this line out when we support partial indexing
651   if (line == UINT32_MAX) {
652     // Already done?
653     if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
654       return true;
655 
656     if (m_offsets.empty()) {
657       if (m_data_sp.get() == nullptr)
658         return false;
659 
660       const char *start = (const char *)m_data_sp->GetBytes();
661       if (start) {
662         const char *end = start + m_data_sp->GetByteSize();
663 
664         // Calculate all line offsets from scratch
665 
666         // Push a 1 at index zero to indicate the file has been completely
667         // indexed.
668         m_offsets.push_back(UINT32_MAX);
669         const char *s;
670         for (s = start; s < end; ++s) {
671           char curr_ch = *s;
672           if (is_newline_char(curr_ch)) {
673             if (s + 1 < end) {
674               char next_ch = s[1];
675               if (is_newline_char(next_ch)) {
676                 if (curr_ch != next_ch)
677                   ++s;
678               }
679             }
680             m_offsets.push_back(s + 1 - start);
681           }
682         }
683         if (!m_offsets.empty()) {
684           if (m_offsets.back() < size_t(end - start))
685             m_offsets.push_back(end - start);
686         }
687         return true;
688       }
689     } else {
690       // Some lines have been populated, start where we last left off
691       assert("Not implemented yet" && false);
692     }
693 
694   } else {
695     // Calculate all line offsets up to "line"
696     assert("Not implemented yet" && false);
697   }
698   return false;
699 }
700 
701 bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
702   if (!LineIsValid(line_no))
703     return false;
704 
705   size_t start_offset = GetLineOffset(line_no);
706   size_t end_offset = GetLineOffset(line_no + 1);
707   if (end_offset == UINT32_MAX) {
708     end_offset = m_data_sp->GetByteSize();
709   }
710   buffer.assign((const char *)m_data_sp->GetBytes() + start_offset,
711                 end_offset - start_offset);
712 
713   return true;
714 }
715 
716 void SourceManager::SourceFileCache::AddSourceFile(const FileSP &file_sp) {
717   FileSpec file_spec = file_sp->GetFileSpec();
718   FileCache::iterator pos = m_file_cache.find(file_spec);
719   if (pos == m_file_cache.end())
720     m_file_cache[file_spec] = file_sp;
721   else {
722     if (file_sp != pos->second)
723       m_file_cache[file_spec] = file_sp;
724   }
725 }
726 
727 SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
728     const FileSpec &file_spec) const {
729   FileSP file_sp;
730   FileCache::const_iterator pos = m_file_cache.find(file_spec);
731   if (pos != m_file_cache.end())
732     file_sp = pos->second;
733   return file_sp;
734 }
735