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