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