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