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 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Core/DataBuffer.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/Stream.h"
20 #include "lldb/Symbol/ClangNamespaceDecl.h"
21 #include "lldb/Symbol/CompileUnit.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Target/Target.h"
25 
26 using namespace lldb_private;
27 
28 static inline bool is_newline_char(char ch)
29 {
30     return ch == '\n' || ch == '\r';
31 }
32 
33 
34 //----------------------------------------------------------------------
35 // SourceManager constructor
36 //----------------------------------------------------------------------
37 SourceManager::SourceManager(Target &target) :
38     m_last_file_sp (),
39     m_last_file_line (0),
40     m_last_file_context_before (0),
41     m_last_file_context_after (10),
42     m_default_set(false),
43     m_target (&target),
44     m_debugger(NULL)
45 {
46     m_debugger = &(m_target->GetDebugger());
47 }
48 
49 SourceManager::SourceManager(Debugger &debugger) :
50     m_last_file_sp (),
51     m_last_file_line (0),
52     m_last_file_context_before (0),
53     m_last_file_context_after (10),
54     m_default_set(false),
55     m_target (NULL),
56     m_debugger (&debugger)
57 {
58 }
59 
60 //----------------------------------------------------------------------
61 // Destructor
62 //----------------------------------------------------------------------
63 SourceManager::~SourceManager()
64 {
65 }
66 
67 size_t
68 SourceManager::DisplaySourceLines
69 (
70     const FileSpec &file_spec,
71     uint32_t line,
72     uint32_t context_before,
73     uint32_t context_after,
74     Stream *s
75 )
76 {
77     m_last_file_sp = GetFile (file_spec);
78     m_last_file_line = line + context_after + 1;
79     m_last_file_context_before = context_before;
80     m_last_file_context_after = context_after;
81     if (m_last_file_sp.get())
82         return m_last_file_sp->DisplaySourceLines (line, context_before, context_after, s);
83 
84     return 0;
85 }
86 
87 SourceManager::FileSP
88 SourceManager::GetFile (const FileSpec &file_spec)
89 {
90     FileSP file_sp;
91     file_sp = m_debugger->GetSourceFileCache().FindSourceFile (file_spec);
92     // If file_sp is no good or it points to a non-existent file, reset it.
93     if (!file_sp || !file_sp->GetFileSpec().Exists())
94     {
95         file_sp.reset (new File (file_spec, m_target));
96 
97         m_debugger->GetSourceFileCache().AddSourceFile(file_sp);
98     }
99     return file_sp;
100 }
101 
102 size_t
103 SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile
104 (
105     uint32_t line,
106     uint32_t context_before,
107     uint32_t context_after,
108     const char* current_line_cstr,
109     Stream *s,
110     const SymbolContextList *bp_locs
111 )
112 {
113     size_t return_value = 0;
114     if (line == 0)
115     {
116         if (m_last_file_line != 0
117             && m_last_file_line != UINT32_MAX)
118             line = m_last_file_line + context_before;
119         else
120             line = 1;
121     }
122 
123     m_last_file_line = line + context_after + 1;
124     m_last_file_context_before = context_before;
125     m_last_file_context_after = context_after;
126 
127     if (context_before == UINT32_MAX)
128         context_before = 0;
129     if (context_after == UINT32_MAX)
130         context_after = 10;
131 
132     if (m_last_file_sp.get())
133     {
134         const uint32_t start_line = line <= context_before ? 1 : line - context_before;
135         const uint32_t end_line = line + context_after;
136         uint32_t curr_line;
137         for (curr_line = start_line; curr_line <= end_line; ++curr_line)
138         {
139             if (!m_last_file_sp->LineIsValid (curr_line))
140             {
141                 m_last_file_line = UINT32_MAX;
142                 break;
143             }
144 
145             char prefix[32] = "";
146             if (bp_locs)
147             {
148                 uint32_t bp_count = bp_locs->NumLineEntriesWithLine (curr_line);
149 
150                 if (bp_count > 0)
151                     ::snprintf (prefix, sizeof (prefix), "[%u] ", bp_count);
152                 else
153                     ::snprintf (prefix, sizeof (prefix), "    ");
154             }
155 
156             return_value += s->Printf("%s%2.2s %-4u\t",
157                       prefix,
158                       curr_line == line ? current_line_cstr : "",
159                       curr_line);
160             size_t this_line_size = m_last_file_sp->DisplaySourceLines (curr_line, 0, 0, s);
161             if (this_line_size == 0)
162             {
163                 m_last_file_line = UINT32_MAX;
164                 break;
165             }
166             else
167                 return_value += this_line_size;
168         }
169     }
170     return return_value;
171 }
172 
173 size_t
174 SourceManager::DisplaySourceLinesWithLineNumbers
175 (
176     const FileSpec &file_spec,
177     uint32_t line,
178     uint32_t context_before,
179     uint32_t context_after,
180     const char* current_line_cstr,
181     Stream *s,
182     const SymbolContextList *bp_locs
183 )
184 {
185     bool same_as_previous = m_last_file_sp && m_last_file_sp->FileSpecMatches (file_spec);
186 
187     if (!same_as_previous)
188         m_last_file_sp = GetFile (file_spec);
189 
190     if (line == 0)
191     {
192         if (!same_as_previous)
193             m_last_file_line = 0;
194     }
195 
196     return DisplaySourceLinesWithLineNumbersUsingLastFile (line, context_before, context_after, current_line_cstr, s, bp_locs);
197 }
198 
199 size_t
200 SourceManager::DisplayMoreWithLineNumbers (Stream *s, const SymbolContextList *bp_locs)
201 {
202     if (m_last_file_sp)
203     {
204         if (m_last_file_line == UINT32_MAX)
205             return 0;
206         return DisplaySourceLinesWithLineNumbersUsingLastFile (0, m_last_file_context_before, m_last_file_context_after, "", s, bp_locs);
207     }
208     return 0;
209 }
210 
211 bool
212 SourceManager::SetDefaultFileAndLine (const FileSpec &file_spec, uint32_t line)
213 {
214     FileSP old_file_sp = m_last_file_sp;
215     m_last_file_sp = GetFile (file_spec);
216 
217     m_default_set = true;
218     if (m_last_file_sp)
219     {
220         m_last_file_line = line;
221         return true;
222     }
223     else
224     {
225         m_last_file_sp = old_file_sp;
226         return false;
227     }
228 }
229 
230 bool
231 SourceManager::GetDefaultFileAndLine (FileSpec &file_spec, uint32_t &line)
232 {
233     if (m_last_file_sp)
234     {
235         file_spec = m_last_file_sp->GetFileSpec();
236         line = m_last_file_line;
237         return true;
238     }
239     else if (!m_default_set)
240     {
241         // If nobody has set the default file and line then try here.  If there's no executable, then we
242         // will try again later when there is one.  Otherwise, if we can't find it we won't look again,
243         // somebody will have to set it (for instance when we stop somewhere...)
244         Module *executable_ptr = m_target->GetExecutableModulePointer();
245         if (executable_ptr)
246         {
247             SymbolContextList sc_list;
248             uint32_t num_matches;
249             ConstString main_name("main");
250             bool symbols_okay = false;  // Force it to be a debug symbol.
251             bool inlines_okay = true;
252             bool append = false;
253             num_matches = executable_ptr->FindFunctions (main_name, NULL, lldb::eFunctionNameTypeBase, inlines_okay, symbols_okay, append, sc_list);
254             for (uint32_t idx = 0; idx < num_matches; idx++)
255             {
256                 SymbolContext sc;
257                 sc_list.GetContextAtIndex(idx, sc);
258                 if (sc.function)
259                 {
260                     lldb_private::LineEntry line_entry;
261                     if (sc.function->GetAddressRange().GetBaseAddress().CalculateSymbolContextLineEntry (line_entry))
262                     {
263                         SetDefaultFileAndLine (line_entry.file,
264                                                line_entry.line);
265                         file_spec = m_last_file_sp->GetFileSpec();
266                         line = m_last_file_line;
267                         return true;
268                     }
269                 }
270             }
271         }
272     }
273     return false;
274 }
275 
276 void
277 SourceManager::FindLinesMatchingRegex (FileSpec &file_spec,
278                                        RegularExpression& regex,
279                                        uint32_t start_line,
280                                        uint32_t end_line,
281                                        std::vector<uint32_t> &match_lines)
282 {
283     match_lines.clear();
284     FileSP file_sp = GetFile (file_spec);
285     if (!file_sp)
286         return;
287     return file_sp->FindLinesMatchingRegex (regex, start_line, end_line, match_lines);
288 }
289 
290 SourceManager::File::File(const FileSpec &file_spec, Target *target) :
291     m_file_spec_orig (file_spec),
292     m_file_spec(file_spec),
293     m_mod_time (file_spec.GetModificationTime()),
294     m_data_sp(),
295     m_offsets()
296 {
297     if (!m_mod_time.IsValid())
298     {
299         if (target)
300         {
301             if (!file_spec.GetDirectory() && file_spec.GetFilename())
302             {
303                 // If this is just a file name, lets see if we can find it in the target:
304                 bool check_inlines = false;
305                 SymbolContextList sc_list;
306                 size_t num_matches = target->GetImages().ResolveSymbolContextForFilePath (file_spec.GetFilename().AsCString(),
307                                                                                           0,
308                                                                                           check_inlines,
309                                                                                           lldb::eSymbolContextModule | lldb::eSymbolContextCompUnit,
310                                                                                           sc_list);
311                 bool got_multiple = false;
312                 if (num_matches != 0)
313                 {
314                     if (num_matches > 1)
315                     {
316                         SymbolContext sc;
317                         FileSpec *test_cu_spec = NULL;
318 
319                         for (unsigned i = 0; i < num_matches; i++)
320                         {
321                             sc_list.GetContextAtIndex(i, sc);
322                             if (sc.comp_unit)
323                             {
324                                 if (test_cu_spec)
325                                 {
326                                     if (test_cu_spec != static_cast<FileSpec *> (sc.comp_unit))
327                                         got_multiple = true;
328                                         break;
329                                 }
330                                 else
331                                     test_cu_spec = sc.comp_unit;
332                             }
333                         }
334                     }
335                     if (!got_multiple)
336                     {
337                         SymbolContext sc;
338                         sc_list.GetContextAtIndex (0, sc);
339                         m_file_spec = sc.comp_unit;
340                         m_mod_time = m_file_spec.GetModificationTime();
341                     }
342                 }
343             }
344             // Try remapping if m_file_spec does not correspond to an existing file.
345             if (!m_file_spec.Exists())
346             {
347                 FileSpec new_file_spec;
348                 // Check target specific source remappings first, then fall back to
349                 // modules objects can have individual path remappings that were detected
350                 // when the debug info for a module was found.
351                 // then
352                 if (target->GetSourcePathMap().FindFile (m_file_spec, new_file_spec) ||
353                     target->GetImages().FindSourceFile (m_file_spec, new_file_spec))
354                 {
355                     m_file_spec = new_file_spec;
356                     m_mod_time = m_file_spec.GetModificationTime();
357                 }
358             }
359         }
360     }
361 
362     if (m_mod_time.IsValid())
363         m_data_sp = m_file_spec.ReadFileContents ();
364 }
365 
366 SourceManager::File::~File()
367 {
368 }
369 
370 uint32_t
371 SourceManager::File::GetLineOffset (uint32_t line)
372 {
373     if (line == 0)
374         return UINT32_MAX;
375 
376     if (line == 1)
377         return 0;
378 
379     if (CalculateLineOffsets (line))
380     {
381         if (line < m_offsets.size())
382             return m_offsets[line - 1]; // yes we want "line - 1" in the index
383     }
384     return UINT32_MAX;
385 }
386 
387 bool
388 SourceManager::File::LineIsValid (uint32_t line)
389 {
390     if (line == 0)
391         return false;
392 
393     if (CalculateLineOffsets (line))
394         return line < m_offsets.size();
395     return false;
396 }
397 
398 size_t
399 SourceManager::File::DisplaySourceLines (uint32_t line, uint32_t context_before, uint32_t context_after, Stream *s)
400 {
401     // TODO: use host API to sign up for file modifications to anything in our
402     // source cache and only update when we determine a file has been updated.
403     // For now we check each time we want to display info for the file.
404     TimeValue curr_mod_time (m_file_spec.GetModificationTime());
405 
406     if (curr_mod_time.IsValid() && m_mod_time != curr_mod_time)
407     {
408         m_mod_time = curr_mod_time;
409         m_data_sp = m_file_spec.ReadFileContents ();
410         m_offsets.clear();
411     }
412 
413     // Sanity check m_data_sp before proceeding.
414     if (!m_data_sp)
415         return 0;
416 
417     const uint32_t start_line = line <= context_before ? 1 : line - context_before;
418     const uint32_t start_line_offset = GetLineOffset (start_line);
419     if (start_line_offset != UINT32_MAX)
420     {
421         const uint32_t end_line = line + context_after;
422         uint32_t end_line_offset = GetLineOffset (end_line + 1);
423         if (end_line_offset == UINT32_MAX)
424             end_line_offset = m_data_sp->GetByteSize();
425 
426         assert (start_line_offset <= end_line_offset);
427         size_t bytes_written = 0;
428         if (start_line_offset < end_line_offset)
429         {
430             size_t count = end_line_offset - start_line_offset;
431             const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
432             bytes_written = s->Write(cstr, count);
433             if (!is_newline_char(cstr[count-1]))
434                 bytes_written += s->EOL();
435         }
436         return bytes_written;
437     }
438     return 0;
439 }
440 
441 void
442 SourceManager::File::FindLinesMatchingRegex (RegularExpression& regex, uint32_t start_line, uint32_t end_line, std::vector<uint32_t> &match_lines)
443 {
444     TimeValue curr_mod_time (m_file_spec.GetModificationTime());
445     if (m_mod_time != curr_mod_time)
446     {
447         m_mod_time = curr_mod_time;
448         m_data_sp = m_file_spec.ReadFileContents ();
449         m_offsets.clear();
450     }
451 
452     match_lines.clear();
453 
454     if (!LineIsValid(start_line) || (end_line != UINT32_MAX && !LineIsValid(end_line)))
455         return;
456     if (start_line > end_line)
457         return;
458 
459     for (uint32_t line_no = start_line; line_no < end_line; line_no++)
460     {
461         std::string buffer;
462         if (!GetLine (line_no, buffer))
463             break;
464         if (regex.Execute(buffer.c_str()))
465         {
466             match_lines.push_back(line_no);
467         }
468     }
469 }
470 
471 bool
472 SourceManager::File::FileSpecMatches (const FileSpec &file_spec)
473 {
474     return FileSpec::Equal (m_file_spec, file_spec, false);
475 }
476 
477 bool
478 lldb_private::operator== (const SourceManager::File &lhs, const SourceManager::File &rhs)
479 {
480     if (lhs.m_file_spec == rhs.m_file_spec)
481     {
482         if (lhs.m_mod_time.IsValid())
483         {
484             if (rhs.m_mod_time.IsValid())
485                 return lhs.m_mod_time == rhs.m_mod_time;
486             else
487                 return false;
488         }
489         else if (rhs.m_mod_time.IsValid())
490             return false;
491         else
492             return true;
493     }
494     else
495         return false;
496 }
497 
498 bool
499 SourceManager::File::CalculateLineOffsets (uint32_t line)
500 {
501     line = UINT32_MAX;  // TODO: take this line out when we support partial indexing
502     if (line == UINT32_MAX)
503     {
504         // Already done?
505         if (!m_offsets.empty() && m_offsets[0] == UINT32_MAX)
506             return true;
507 
508         if (m_offsets.empty())
509         {
510             if (m_data_sp.get() == NULL)
511                 return false;
512 
513             const char *start = (char *)m_data_sp->GetBytes();
514             if (start)
515             {
516                 const char *end = start + m_data_sp->GetByteSize();
517 
518                 // Calculate all line offsets from scratch
519 
520                 // Push a 1 at index zero to indicate the file has been completely indexed.
521                 m_offsets.push_back(UINT32_MAX);
522                 register const char *s;
523                 for (s = start; s < end; ++s)
524                 {
525                     register char curr_ch = *s;
526                     if (is_newline_char (curr_ch))
527                     {
528                         register char next_ch = s[1];
529                         if (is_newline_char (next_ch))
530                         {
531                             if (curr_ch != next_ch)
532                                 ++s;
533                         }
534                         m_offsets.push_back(s + 1 - start);
535                     }
536                 }
537                 if (!m_offsets.empty())
538                 {
539                     if (m_offsets.back() < end - start)
540                         m_offsets.push_back(end - start);
541                 }
542                 return true;
543             }
544         }
545         else
546         {
547             // Some lines have been populated, start where we last left off
548             assert(!"Not implemented yet");
549         }
550 
551     }
552     else
553     {
554         // Calculate all line offsets up to "line"
555         assert(!"Not implemented yet");
556     }
557     return false;
558 }
559 
560 bool
561 SourceManager::File::GetLine (uint32_t line_no, std::string &buffer)
562 {
563     if (!LineIsValid(line_no))
564         return false;
565 
566     uint32_t start_offset = GetLineOffset (line_no);
567     uint32_t end_offset = GetLineOffset (line_no + 1);
568     if (end_offset == UINT32_MAX)
569     {
570         end_offset = m_data_sp->GetByteSize();
571     }
572     buffer.assign((char *) m_data_sp->GetBytes() + start_offset, end_offset - start_offset);
573 
574     return true;
575 }
576 
577 void
578 SourceManager::SourceFileCache::AddSourceFile (const FileSP &file_sp)
579 {
580     FileSpec file_spec;
581     FileCache::iterator pos = m_file_cache.find(file_spec);
582     if (pos == m_file_cache.end())
583         m_file_cache[file_spec] = file_sp;
584     else
585     {
586         if (file_sp != pos->second)
587             m_file_cache[file_spec] = file_sp;
588     }
589 }
590 
591 SourceManager::FileSP
592 SourceManager::SourceFileCache::FindSourceFile (const FileSpec &file_spec) const
593 {
594     FileSP file_sp;
595     FileCache::const_iterator pos = m_file_cache.find(file_spec);
596     if (pos != m_file_cache.end())
597         file_sp = pos->second;
598     return file_sp;
599 }
600 
601