xref: /freebsd/contrib/llvm-project/lldb/source/Commands/CommandObjectSource.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===-- CommandObjectSource.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectSource.h"
10 
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/FileLineResolver.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/SourceManager.h"
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Interpreter/CommandOptionArgumentTable.h"
18 #include "lldb/Interpreter/CommandReturnObject.h"
19 #include "lldb/Interpreter/OptionArgParser.h"
20 #include "lldb/Interpreter/OptionValueFileColonLine.h"
21 #include "lldb/Interpreter/Options.h"
22 #include "lldb/Symbol/CompileUnit.h"
23 #include "lldb/Symbol/Function.h"
24 #include "lldb/Symbol/Symbol.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/SectionLoadList.h"
27 #include "lldb/Target/StackFrame.h"
28 #include "lldb/Utility/FileSpec.h"
29 #include <optional>
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 #pragma mark CommandObjectSourceInfo
35 // CommandObjectSourceInfo - debug line entries dumping command
36 #define LLDB_OPTIONS_source_info
37 #include "CommandOptions.inc"
38 
39 class CommandObjectSourceInfo : public CommandObjectParsed {
40   class CommandOptions : public Options {
41   public:
42     CommandOptions() = default;
43 
44     ~CommandOptions() override = default;
45 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)46     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
47                           ExecutionContext *execution_context) override {
48       Status error;
49       const int short_option = GetDefinitions()[option_idx].short_option;
50       switch (short_option) {
51       case 'l':
52         if (option_arg.getAsInteger(0, start_line))
53           error.SetErrorStringWithFormat("invalid line number: '%s'",
54                                          option_arg.str().c_str());
55         break;
56 
57       case 'e':
58         if (option_arg.getAsInteger(0, end_line))
59           error.SetErrorStringWithFormat("invalid line number: '%s'",
60                                          option_arg.str().c_str());
61         break;
62 
63       case 'c':
64         if (option_arg.getAsInteger(0, num_lines))
65           error.SetErrorStringWithFormat("invalid line count: '%s'",
66                                          option_arg.str().c_str());
67         break;
68 
69       case 'f':
70         file_name = std::string(option_arg);
71         break;
72 
73       case 'n':
74         symbol_name = std::string(option_arg);
75         break;
76 
77       case 'a': {
78         address = OptionArgParser::ToAddress(execution_context, option_arg,
79                                              LLDB_INVALID_ADDRESS, &error);
80       } break;
81       case 's':
82         modules.push_back(std::string(option_arg));
83         break;
84       default:
85         llvm_unreachable("Unimplemented option");
86       }
87 
88       return error;
89     }
90 
OptionParsingStarting(ExecutionContext * execution_context)91     void OptionParsingStarting(ExecutionContext *execution_context) override {
92       file_spec.Clear();
93       file_name.clear();
94       symbol_name.clear();
95       address = LLDB_INVALID_ADDRESS;
96       start_line = 0;
97       end_line = 0;
98       num_lines = 0;
99       modules.clear();
100     }
101 
GetDefinitions()102     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
103       return llvm::ArrayRef(g_source_info_options);
104     }
105 
106     // Instance variables to hold the values for command options.
107     FileSpec file_spec;
108     std::string file_name;
109     std::string symbol_name;
110     lldb::addr_t address;
111     uint32_t start_line;
112     uint32_t end_line;
113     uint32_t num_lines;
114     std::vector<std::string> modules;
115   };
116 
117 public:
CommandObjectSourceInfo(CommandInterpreter & interpreter)118   CommandObjectSourceInfo(CommandInterpreter &interpreter)
119       : CommandObjectParsed(
120             interpreter, "source info",
121             "Display source line information for the current target "
122             "process.  Defaults to instruction pointer in current stack "
123             "frame.",
124             nullptr, eCommandRequiresTarget) {}
125 
126   ~CommandObjectSourceInfo() override = default;
127 
GetOptions()128   Options *GetOptions() override { return &m_options; }
129 
130 protected:
131   // Dump the line entries in each symbol context. Return the number of entries
132   // found. If module_list is set, only dump lines contained in one of the
133   // modules. If file_spec is set, only dump lines in the file. If the
134   // start_line option was specified, don't print lines less than start_line.
135   // If the end_line option was specified, don't print lines greater than
136   // end_line. If the num_lines option was specified, dont print more than
137   // num_lines entries.
DumpLinesInSymbolContexts(Stream & strm,const SymbolContextList & sc_list,const ModuleList & module_list,const FileSpec & file_spec)138   uint32_t DumpLinesInSymbolContexts(Stream &strm,
139                                      const SymbolContextList &sc_list,
140                                      const ModuleList &module_list,
141                                      const FileSpec &file_spec) {
142     uint32_t start_line = m_options.start_line;
143     uint32_t end_line = m_options.end_line;
144     uint32_t num_lines = m_options.num_lines;
145     Target *target = m_exe_ctx.GetTargetPtr();
146 
147     uint32_t num_matches = 0;
148     // Dump all the line entries for the file in the list.
149     ConstString last_module_file_name;
150     for (const SymbolContext &sc : sc_list) {
151       if (sc.comp_unit) {
152         Module *module = sc.module_sp.get();
153         CompileUnit *cu = sc.comp_unit;
154         const LineEntry &line_entry = sc.line_entry;
155         assert(module && cu);
156 
157         // Are we looking for specific modules, files or lines?
158         if (module_list.GetSize() &&
159             module_list.GetIndexForModule(module) == LLDB_INVALID_INDEX32)
160           continue;
161         if (!FileSpec::Match(file_spec, line_entry.GetFile()))
162           continue;
163         if (start_line > 0 && line_entry.line < start_line)
164           continue;
165         if (end_line > 0 && line_entry.line > end_line)
166           continue;
167         if (num_lines > 0 && num_matches > num_lines)
168           continue;
169 
170         // Print a new header if the module changed.
171         ConstString module_file_name = module->GetFileSpec().GetFilename();
172         assert(module_file_name);
173         if (module_file_name != last_module_file_name) {
174           if (num_matches > 0)
175             strm << "\n\n";
176           strm << "Lines found in module `" << module_file_name << "\n";
177         }
178         // Dump the line entry.
179         line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu,
180                                   target, /*show_address_only=*/false);
181         strm << "\n";
182         last_module_file_name = module_file_name;
183         num_matches++;
184       }
185     }
186     return num_matches;
187   }
188 
189   // Dump the requested line entries for the file in the compilation unit.
190   // Return the number of entries found. If module_list is set, only dump lines
191   // contained in one of the modules. If the start_line option was specified,
192   // don't print lines less than start_line. If the end_line option was
193   // specified, don't print lines greater than end_line. If the num_lines
194   // option was specified, dont print more than num_lines entries.
DumpFileLinesInCompUnit(Stream & strm,Module * module,CompileUnit * cu,const FileSpec & file_spec)195   uint32_t DumpFileLinesInCompUnit(Stream &strm, Module *module,
196                                    CompileUnit *cu, const FileSpec &file_spec) {
197     uint32_t start_line = m_options.start_line;
198     uint32_t end_line = m_options.end_line;
199     uint32_t num_lines = m_options.num_lines;
200     Target *target = m_exe_ctx.GetTargetPtr();
201 
202     uint32_t num_matches = 0;
203     assert(module);
204     if (cu) {
205       assert(file_spec.GetFilename().AsCString());
206       bool has_path = (file_spec.GetDirectory().AsCString() != nullptr);
207       const SupportFileList &cu_file_list = cu->GetSupportFiles();
208       size_t file_idx = cu_file_list.FindFileIndex(0, file_spec, has_path);
209       if (file_idx != UINT32_MAX) {
210         // Update the file to how it appears in the CU.
211         const FileSpec &cu_file_spec =
212             cu_file_list.GetFileSpecAtIndex(file_idx);
213 
214         // Dump all matching lines at or above start_line for the file in the
215         // CU.
216         ConstString file_spec_name = file_spec.GetFilename();
217         ConstString module_file_name = module->GetFileSpec().GetFilename();
218         bool cu_header_printed = false;
219         uint32_t line = start_line;
220         while (true) {
221           LineEntry line_entry;
222 
223           // Find the lowest index of a line entry with a line equal to or
224           // higher than 'line'.
225           uint32_t start_idx = 0;
226           start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec,
227                                         /*exact=*/false, &line_entry);
228           if (start_idx == UINT32_MAX)
229             // No more line entries for our file in this CU.
230             break;
231 
232           if (end_line > 0 && line_entry.line > end_line)
233             break;
234 
235           // Loop through to find any other entries for this line, dumping
236           // each.
237           line = line_entry.line;
238           do {
239             num_matches++;
240             if (num_lines > 0 && num_matches > num_lines)
241               break;
242             assert(cu_file_spec == line_entry.GetFile());
243             if (!cu_header_printed) {
244               if (num_matches > 0)
245                 strm << "\n\n";
246               strm << "Lines found for file " << file_spec_name
247                    << " in compilation unit "
248                    << cu->GetPrimaryFile().GetFilename() << " in `"
249                    << module_file_name << "\n";
250               cu_header_printed = true;
251             }
252             line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu,
253                                       target, /*show_address_only=*/false);
254             strm << "\n";
255 
256             // Anymore after this one?
257             start_idx++;
258             start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec,
259                                           /*exact=*/true, &line_entry);
260           } while (start_idx != UINT32_MAX);
261 
262           // Try the next higher line, starting over at start_idx 0.
263           line++;
264         }
265       }
266     }
267     return num_matches;
268   }
269 
270   // Dump the requested line entries for the file in the module. Return the
271   // number of entries found. If module_list is set, only dump lines contained
272   // in one of the modules. If the start_line option was specified, don't print
273   // lines less than start_line. If the end_line option was specified, don't
274   // print lines greater than end_line. If the num_lines option was specified,
275   // dont print more than num_lines entries.
DumpFileLinesInModule(Stream & strm,Module * module,const FileSpec & file_spec)276   uint32_t DumpFileLinesInModule(Stream &strm, Module *module,
277                                  const FileSpec &file_spec) {
278     uint32_t num_matches = 0;
279     if (module) {
280       // Look through all the compilation units (CUs) in this module for ones
281       // that contain lines of code from this source file.
282       for (size_t i = 0; i < module->GetNumCompileUnits(); i++) {
283         // Look for a matching source file in this CU.
284         CompUnitSP cu_sp(module->GetCompileUnitAtIndex(i));
285         if (cu_sp) {
286           num_matches +=
287               DumpFileLinesInCompUnit(strm, module, cu_sp.get(), file_spec);
288         }
289       }
290     }
291     return num_matches;
292   }
293 
294   // Given an address and a list of modules, append the symbol contexts of all
295   // line entries containing the address found in the modules and return the
296   // count of matches.  If none is found, return an error in 'error_strm'.
GetSymbolContextsForAddress(const ModuleList & module_list,lldb::addr_t addr,SymbolContextList & sc_list,StreamString & error_strm)297   size_t GetSymbolContextsForAddress(const ModuleList &module_list,
298                                      lldb::addr_t addr,
299                                      SymbolContextList &sc_list,
300                                      StreamString &error_strm) {
301     Address so_addr;
302     size_t num_matches = 0;
303     assert(module_list.GetSize() > 0);
304     Target *target = m_exe_ctx.GetTargetPtr();
305     if (target->GetSectionLoadList().IsEmpty()) {
306       // The target isn't loaded yet, we need to lookup the file address in all
307       // modules.  Note: the module list option does not apply to addresses.
308       const size_t num_modules = module_list.GetSize();
309       for (size_t i = 0; i < num_modules; ++i) {
310         ModuleSP module_sp(module_list.GetModuleAtIndex(i));
311         if (!module_sp)
312           continue;
313         if (module_sp->ResolveFileAddress(addr, so_addr)) {
314           SymbolContext sc;
315           sc.Clear(true);
316           if (module_sp->ResolveSymbolContextForAddress(
317                   so_addr, eSymbolContextEverything, sc) &
318               eSymbolContextLineEntry) {
319             sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false);
320             ++num_matches;
321           }
322         }
323       }
324       if (num_matches == 0)
325         error_strm.Printf("Source information for file address 0x%" PRIx64
326                           " not found in any modules.\n",
327                           addr);
328     } else {
329       // The target has some things loaded, resolve this address to a compile
330       // unit + file + line and display
331       if (target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) {
332         ModuleSP module_sp(so_addr.GetModule());
333         // Check to make sure this module is in our list.
334         if (module_sp && module_list.GetIndexForModule(module_sp.get()) !=
335                              LLDB_INVALID_INDEX32) {
336           SymbolContext sc;
337           sc.Clear(true);
338           if (module_sp->ResolveSymbolContextForAddress(
339                   so_addr, eSymbolContextEverything, sc) &
340               eSymbolContextLineEntry) {
341             sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false);
342             ++num_matches;
343           } else {
344             StreamString addr_strm;
345             so_addr.Dump(&addr_strm, nullptr,
346                          Address::DumpStyleModuleWithFileAddress);
347             error_strm.Printf(
348                 "Address 0x%" PRIx64 " resolves to %s, but there is"
349                 " no source information available for this address.\n",
350                 addr, addr_strm.GetData());
351           }
352         } else {
353           StreamString addr_strm;
354           so_addr.Dump(&addr_strm, nullptr,
355                        Address::DumpStyleModuleWithFileAddress);
356           error_strm.Printf("Address 0x%" PRIx64
357                             " resolves to %s, but it cannot"
358                             " be found in any modules.\n",
359                             addr, addr_strm.GetData());
360         }
361       } else
362         error_strm.Printf("Unable to resolve address 0x%" PRIx64 ".\n", addr);
363     }
364     return num_matches;
365   }
366 
367   // Dump the line entries found in functions matching the name specified in
368   // the option.
DumpLinesInFunctions(CommandReturnObject & result)369   bool DumpLinesInFunctions(CommandReturnObject &result) {
370     SymbolContextList sc_list_funcs;
371     ConstString name(m_options.symbol_name.c_str());
372     SymbolContextList sc_list_lines;
373     Target *target = m_exe_ctx.GetTargetPtr();
374     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
375 
376     ModuleFunctionSearchOptions function_options;
377     function_options.include_symbols = false;
378     function_options.include_inlines = true;
379 
380     // Note: module_list can't be const& because FindFunctionSymbols isn't
381     // const.
382     ModuleList module_list =
383         (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages();
384     module_list.FindFunctions(name, eFunctionNameTypeAuto, function_options,
385                               sc_list_funcs);
386     size_t num_matches = sc_list_funcs.GetSize();
387 
388     if (!num_matches) {
389       // If we didn't find any functions with that name, try searching for
390       // symbols that line up exactly with function addresses.
391       SymbolContextList sc_list_symbols;
392       module_list.FindFunctionSymbols(name, eFunctionNameTypeAuto,
393                                       sc_list_symbols);
394       for (const SymbolContext &sc : sc_list_symbols) {
395         if (sc.symbol && sc.symbol->ValueIsAddress()) {
396           const Address &base_address = sc.symbol->GetAddressRef();
397           Function *function = base_address.CalculateSymbolContextFunction();
398           if (function) {
399             sc_list_funcs.Append(SymbolContext(function));
400             num_matches++;
401           }
402         }
403       }
404     }
405     if (num_matches == 0) {
406       result.AppendErrorWithFormat("Could not find function named \'%s\'.\n",
407                                    m_options.symbol_name.c_str());
408       return false;
409     }
410     for (const SymbolContext &sc : sc_list_funcs) {
411       bool context_found_for_symbol = false;
412       // Loop through all the ranges in the function.
413       AddressRange range;
414       for (uint32_t r = 0;
415            sc.GetAddressRange(eSymbolContextEverything, r,
416                               /*use_inline_block_range=*/true, range);
417            ++r) {
418         // Append the symbol contexts for each address in the range to
419         // sc_list_lines.
420         const Address &base_address = range.GetBaseAddress();
421         const addr_t size = range.GetByteSize();
422         lldb::addr_t start_addr = base_address.GetLoadAddress(target);
423         if (start_addr == LLDB_INVALID_ADDRESS)
424           start_addr = base_address.GetFileAddress();
425         lldb::addr_t end_addr = start_addr + size;
426         for (lldb::addr_t addr = start_addr; addr < end_addr;
427              addr += addr_byte_size) {
428           StreamString error_strm;
429           if (!GetSymbolContextsForAddress(module_list, addr, sc_list_lines,
430                                            error_strm))
431             result.AppendWarningWithFormat("in symbol '%s': %s",
432                                            sc.GetFunctionName().AsCString(),
433                                            error_strm.GetData());
434           else
435             context_found_for_symbol = true;
436         }
437       }
438       if (!context_found_for_symbol)
439         result.AppendWarningWithFormat("Unable to find line information"
440                                        " for matching symbol '%s'.\n",
441                                        sc.GetFunctionName().AsCString());
442     }
443     if (sc_list_lines.GetSize() == 0) {
444       result.AppendErrorWithFormat("No line information could be found"
445                                    " for any symbols matching '%s'.\n",
446                                    name.AsCString());
447       return false;
448     }
449     FileSpec file_spec;
450     if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list_lines,
451                                    module_list, file_spec)) {
452       result.AppendErrorWithFormat(
453           "Unable to dump line information for symbol '%s'.\n",
454           name.AsCString());
455       return false;
456     }
457     return true;
458   }
459 
460   // Dump the line entries found for the address specified in the option.
DumpLinesForAddress(CommandReturnObject & result)461   bool DumpLinesForAddress(CommandReturnObject &result) {
462     Target *target = m_exe_ctx.GetTargetPtr();
463     SymbolContextList sc_list;
464 
465     StreamString error_strm;
466     if (!GetSymbolContextsForAddress(target->GetImages(), m_options.address,
467                                      sc_list, error_strm)) {
468       result.AppendErrorWithFormat("%s.\n", error_strm.GetData());
469       return false;
470     }
471     ModuleList module_list;
472     FileSpec file_spec;
473     if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list,
474                                    module_list, file_spec)) {
475       result.AppendErrorWithFormat("No modules contain load address 0x%" PRIx64
476                                    ".\n",
477                                    m_options.address);
478       return false;
479     }
480     return true;
481   }
482 
483   // Dump the line entries found in the file specified in the option.
DumpLinesForFile(CommandReturnObject & result)484   bool DumpLinesForFile(CommandReturnObject &result) {
485     FileSpec file_spec(m_options.file_name);
486     const char *filename = m_options.file_name.c_str();
487     Target *target = m_exe_ctx.GetTargetPtr();
488     const ModuleList &module_list =
489         (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages();
490 
491     bool displayed_something = false;
492     const size_t num_modules = module_list.GetSize();
493     for (uint32_t i = 0; i < num_modules; ++i) {
494       // Dump lines for this module.
495       Module *module = module_list.GetModulePointerAtIndex(i);
496       assert(module);
497       if (DumpFileLinesInModule(result.GetOutputStream(), module, file_spec))
498         displayed_something = true;
499     }
500     if (!displayed_something) {
501       result.AppendErrorWithFormat("No source filenames matched '%s'.\n",
502                                    filename);
503       return false;
504     }
505     return true;
506   }
507 
508   // Dump the line entries for the current frame.
DumpLinesForFrame(CommandReturnObject & result)509   bool DumpLinesForFrame(CommandReturnObject &result) {
510     StackFrame *cur_frame = m_exe_ctx.GetFramePtr();
511     if (cur_frame == nullptr) {
512       result.AppendError(
513           "No selected frame to use to find the default source.");
514       return false;
515     } else if (!cur_frame->HasDebugInformation()) {
516       result.AppendError("No debug info for the selected frame.");
517       return false;
518     } else {
519       const SymbolContext &sc =
520           cur_frame->GetSymbolContext(eSymbolContextLineEntry);
521       SymbolContextList sc_list;
522       sc_list.Append(sc);
523       ModuleList module_list;
524       FileSpec file_spec;
525       if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list,
526                                      module_list, file_spec)) {
527         result.AppendError(
528             "No source line info available for the selected frame.");
529         return false;
530       }
531     }
532     return true;
533   }
534 
DoExecute(Args & command,CommandReturnObject & result)535   void DoExecute(Args &command, CommandReturnObject &result) override {
536     Target *target = m_exe_ctx.GetTargetPtr();
537     if (target == nullptr) {
538       target = GetDebugger().GetSelectedTarget().get();
539       if (target == nullptr) {
540         result.AppendError("invalid target, create a debug target using the "
541                            "'target create' command.");
542         return;
543       }
544     }
545 
546     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
547     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
548     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
549 
550     // Collect the list of modules to search.
551     m_module_list.Clear();
552     if (!m_options.modules.empty()) {
553       for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) {
554         FileSpec module_file_spec(m_options.modules[i]);
555         if (module_file_spec) {
556           ModuleSpec module_spec(module_file_spec);
557           target->GetImages().FindModules(module_spec, m_module_list);
558           if (m_module_list.IsEmpty())
559             result.AppendWarningWithFormat("No module found for '%s'.\n",
560                                            m_options.modules[i].c_str());
561         }
562       }
563       if (!m_module_list.GetSize()) {
564         result.AppendError("No modules match the input.");
565         return;
566       }
567     } else if (target->GetImages().GetSize() == 0) {
568       result.AppendError("The target has no associated executable images.");
569       return;
570     }
571 
572     // Check the arguments to see what lines we should dump.
573     if (!m_options.symbol_name.empty()) {
574       // Print lines for symbol.
575       if (DumpLinesInFunctions(result))
576         result.SetStatus(eReturnStatusSuccessFinishResult);
577       else
578         result.SetStatus(eReturnStatusFailed);
579     } else if (m_options.address != LLDB_INVALID_ADDRESS) {
580       // Print lines for an address.
581       if (DumpLinesForAddress(result))
582         result.SetStatus(eReturnStatusSuccessFinishResult);
583       else
584         result.SetStatus(eReturnStatusFailed);
585     } else if (!m_options.file_name.empty()) {
586       // Dump lines for a file.
587       if (DumpLinesForFile(result))
588         result.SetStatus(eReturnStatusSuccessFinishResult);
589       else
590         result.SetStatus(eReturnStatusFailed);
591     } else {
592       // Dump the line for the current frame.
593       if (DumpLinesForFrame(result))
594         result.SetStatus(eReturnStatusSuccessFinishResult);
595       else
596         result.SetStatus(eReturnStatusFailed);
597     }
598   }
599 
600   CommandOptions m_options;
601   ModuleList m_module_list;
602 };
603 
604 #pragma mark CommandObjectSourceList
605 // CommandObjectSourceList
606 #define LLDB_OPTIONS_source_list
607 #include "CommandOptions.inc"
608 
609 class CommandObjectSourceList : public CommandObjectParsed {
610   class CommandOptions : public Options {
611   public:
612     CommandOptions() = default;
613 
614     ~CommandOptions() override = default;
615 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)616     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
617                           ExecutionContext *execution_context) override {
618       Status error;
619       const int short_option = GetDefinitions()[option_idx].short_option;
620       switch (short_option) {
621       case 'l':
622         if (option_arg.getAsInteger(0, start_line))
623           error.SetErrorStringWithFormat("invalid line number: '%s'",
624                                          option_arg.str().c_str());
625         break;
626 
627       case 'c':
628         if (option_arg.getAsInteger(0, num_lines))
629           error.SetErrorStringWithFormat("invalid line count: '%s'",
630                                          option_arg.str().c_str());
631         break;
632 
633       case 'f':
634         file_name = std::string(option_arg);
635         break;
636 
637       case 'n':
638         symbol_name = std::string(option_arg);
639         break;
640 
641       case 'a': {
642         address = OptionArgParser::ToAddress(execution_context, option_arg,
643                                              LLDB_INVALID_ADDRESS, &error);
644       } break;
645       case 's':
646         modules.push_back(std::string(option_arg));
647         break;
648 
649       case 'b':
650         show_bp_locs = true;
651         break;
652       case 'r':
653         reverse = true;
654         break;
655       case 'y':
656       {
657         OptionValueFileColonLine value;
658         Status fcl_err = value.SetValueFromString(option_arg);
659         if (!fcl_err.Success()) {
660           error.SetErrorStringWithFormat(
661               "Invalid value for file:line specifier: %s",
662               fcl_err.AsCString());
663         } else {
664           file_name = value.GetFileSpec().GetPath();
665           start_line = value.GetLineNumber();
666           // I don't see anything useful to do with a column number, but I don't
667           // want to complain since someone may well have cut and pasted a
668           // listing from somewhere that included a column.
669         }
670       } break;
671       default:
672         llvm_unreachable("Unimplemented option");
673       }
674 
675       return error;
676     }
677 
OptionParsingStarting(ExecutionContext * execution_context)678     void OptionParsingStarting(ExecutionContext *execution_context) override {
679       file_spec.Clear();
680       file_name.clear();
681       symbol_name.clear();
682       address = LLDB_INVALID_ADDRESS;
683       start_line = 0;
684       num_lines = 0;
685       show_bp_locs = false;
686       reverse = false;
687       modules.clear();
688     }
689 
GetDefinitions()690     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
691       return llvm::ArrayRef(g_source_list_options);
692     }
693 
694     // Instance variables to hold the values for command options.
695     FileSpec file_spec;
696     std::string file_name;
697     std::string symbol_name;
698     lldb::addr_t address;
699     uint32_t start_line;
700     uint32_t num_lines;
701     std::vector<std::string> modules;
702     bool show_bp_locs;
703     bool reverse;
704   };
705 
706 public:
CommandObjectSourceList(CommandInterpreter & interpreter)707   CommandObjectSourceList(CommandInterpreter &interpreter)
708       : CommandObjectParsed(interpreter, "source list",
709                             "Display source code for the current target "
710                             "process as specified by options.",
711                             nullptr, eCommandRequiresTarget) {}
712 
713   ~CommandObjectSourceList() override = default;
714 
GetOptions()715   Options *GetOptions() override { return &m_options; }
716 
GetRepeatCommand(Args & current_command_args,uint32_t index)717   std::optional<std::string> GetRepeatCommand(Args &current_command_args,
718                                               uint32_t index) override {
719     // This is kind of gross, but the command hasn't been parsed yet so we
720     // can't look at the option values for this invocation...  I have to scan
721     // the arguments directly.
722     auto iter =
723         llvm::find_if(current_command_args, [](const Args::ArgEntry &e) {
724           return e.ref() == "-r" || e.ref() == "--reverse";
725         });
726     if (iter == current_command_args.end())
727       return m_cmd_name;
728 
729     if (m_reverse_name.empty()) {
730       m_reverse_name = m_cmd_name;
731       m_reverse_name.append(" -r");
732     }
733     return m_reverse_name;
734   }
735 
736 protected:
737   struct SourceInfo {
738     ConstString function;
739     LineEntry line_entry;
740 
SourceInfoCommandObjectSourceList::SourceInfo741     SourceInfo(ConstString name, const LineEntry &line_entry)
742         : function(name), line_entry(line_entry) {}
743 
744     SourceInfo() = default;
745 
IsValidCommandObjectSourceList::SourceInfo746     bool IsValid() const { return (bool)function && line_entry.IsValid(); }
747 
operator ==CommandObjectSourceList::SourceInfo748     bool operator==(const SourceInfo &rhs) const {
749       return function == rhs.function &&
750              line_entry.original_file_sp->Equal(
751                  *rhs.line_entry.original_file_sp,
752                  SupportFile::eEqualFileSpecAndChecksumIfSet) &&
753              line_entry.line == rhs.line_entry.line;
754     }
755 
operator !=CommandObjectSourceList::SourceInfo756     bool operator!=(const SourceInfo &rhs) const {
757       return function != rhs.function ||
758              !line_entry.original_file_sp->Equal(
759                  *rhs.line_entry.original_file_sp,
760                  SupportFile::eEqualFileSpecAndChecksumIfSet) ||
761              line_entry.line != rhs.line_entry.line;
762     }
763 
operator <CommandObjectSourceList::SourceInfo764     bool operator<(const SourceInfo &rhs) const {
765       if (function.GetCString() < rhs.function.GetCString())
766         return true;
767       if (line_entry.GetFile().GetDirectory().GetCString() <
768           rhs.line_entry.GetFile().GetDirectory().GetCString())
769         return true;
770       if (line_entry.GetFile().GetFilename().GetCString() <
771           rhs.line_entry.GetFile().GetFilename().GetCString())
772         return true;
773       if (line_entry.line < rhs.line_entry.line)
774         return true;
775       return false;
776     }
777   };
778 
DisplayFunctionSource(const SymbolContext & sc,SourceInfo & source_info,CommandReturnObject & result)779   size_t DisplayFunctionSource(const SymbolContext &sc, SourceInfo &source_info,
780                                CommandReturnObject &result) {
781     if (!source_info.IsValid()) {
782       source_info.function = sc.GetFunctionName();
783       source_info.line_entry = sc.GetFunctionStartLineEntry();
784     }
785 
786     if (sc.function) {
787       Target *target = m_exe_ctx.GetTargetPtr();
788 
789       FileSpec start_file;
790       uint32_t start_line;
791       uint32_t end_line;
792       FileSpec end_file;
793 
794       if (sc.block == nullptr) {
795         // Not an inlined function
796         sc.function->GetStartLineSourceInfo(start_file, start_line);
797         if (start_line == 0) {
798           result.AppendErrorWithFormat("Could not find line information for "
799                                        "start of function: \"%s\".\n",
800                                        source_info.function.GetCString());
801           return 0;
802         }
803         sc.function->GetEndLineSourceInfo(end_file, end_line);
804       } else {
805         // We have an inlined function
806         start_file = source_info.line_entry.GetFile();
807         start_line = source_info.line_entry.line;
808         end_line = start_line + m_options.num_lines;
809       }
810 
811       // This is a little hacky, but the first line table entry for a function
812       // points to the "{" that starts the function block.  It would be nice to
813       // actually get the function declaration in there too.  So back up a bit,
814       // but not further than what you're going to display.
815       uint32_t extra_lines;
816       if (m_options.num_lines >= 10)
817         extra_lines = 5;
818       else
819         extra_lines = m_options.num_lines / 2;
820       uint32_t line_no;
821       if (start_line <= extra_lines)
822         line_no = 1;
823       else
824         line_no = start_line - extra_lines;
825 
826       // For fun, if the function is shorter than the number of lines we're
827       // supposed to display, only display the function...
828       if (end_line != 0) {
829         if (m_options.num_lines > end_line - line_no)
830           m_options.num_lines = end_line - line_no + extra_lines;
831       }
832 
833       m_breakpoint_locations.Clear();
834 
835       if (m_options.show_bp_locs) {
836         const bool show_inlines = true;
837         m_breakpoint_locations.Reset(start_file, 0, show_inlines);
838         SearchFilterForUnconstrainedSearches target_search_filter(
839             m_exe_ctx.GetTargetSP());
840         target_search_filter.Search(m_breakpoint_locations);
841       }
842 
843       result.AppendMessageWithFormat("File: %s\n",
844                                      start_file.GetPath().c_str());
845       // We don't care about the column here.
846       const uint32_t column = 0;
847       return target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
848           start_file, line_no, column, 0, m_options.num_lines, "",
849           &result.GetOutputStream(), GetBreakpointLocations());
850     } else {
851       result.AppendErrorWithFormat(
852           "Could not find function info for: \"%s\".\n",
853           m_options.symbol_name.c_str());
854     }
855     return 0;
856   }
857 
858   // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols
859   // functions "take a possibly empty vector of strings which are names of
860   // modules, and run the two search functions on the subset of the full module
861   // list that matches the strings in the input vector". If we wanted to put
862   // these somewhere, there should probably be a module-filter-list that can be
863   // passed to the various ModuleList::Find* calls, which would either be a
864   // vector of string names or a ModuleSpecList.
FindMatchingFunctions(Target * target,ConstString name,SymbolContextList & sc_list)865   void FindMatchingFunctions(Target *target, ConstString name,
866                              SymbolContextList &sc_list) {
867     // Displaying the source for a symbol:
868     if (m_options.num_lines == 0)
869       m_options.num_lines = 10;
870 
871     ModuleFunctionSearchOptions function_options;
872     function_options.include_symbols = true;
873     function_options.include_inlines = false;
874 
875     const size_t num_modules = m_options.modules.size();
876     if (num_modules > 0) {
877       ModuleList matching_modules;
878       for (size_t i = 0; i < num_modules; ++i) {
879         FileSpec module_file_spec(m_options.modules[i]);
880         if (module_file_spec) {
881           ModuleSpec module_spec(module_file_spec);
882           matching_modules.Clear();
883           target->GetImages().FindModules(module_spec, matching_modules);
884 
885           matching_modules.FindFunctions(name, eFunctionNameTypeAuto,
886                                          function_options, sc_list);
887         }
888       }
889     } else {
890       target->GetImages().FindFunctions(name, eFunctionNameTypeAuto,
891                                         function_options, sc_list);
892     }
893   }
894 
FindMatchingFunctionSymbols(Target * target,ConstString name,SymbolContextList & sc_list)895   void FindMatchingFunctionSymbols(Target *target, ConstString name,
896                                    SymbolContextList &sc_list) {
897     const size_t num_modules = m_options.modules.size();
898     if (num_modules > 0) {
899       ModuleList matching_modules;
900       for (size_t i = 0; i < num_modules; ++i) {
901         FileSpec module_file_spec(m_options.modules[i]);
902         if (module_file_spec) {
903           ModuleSpec module_spec(module_file_spec);
904           matching_modules.Clear();
905           target->GetImages().FindModules(module_spec, matching_modules);
906           matching_modules.FindFunctionSymbols(name, eFunctionNameTypeAuto,
907                                                sc_list);
908         }
909       }
910     } else {
911       target->GetImages().FindFunctionSymbols(name, eFunctionNameTypeAuto,
912                                               sc_list);
913     }
914   }
915 
DoExecute(Args & command,CommandReturnObject & result)916   void DoExecute(Args &command, CommandReturnObject &result) override {
917     Target *target = m_exe_ctx.GetTargetPtr();
918 
919     if (!m_options.symbol_name.empty()) {
920       SymbolContextList sc_list;
921       ConstString name(m_options.symbol_name.c_str());
922 
923       // Displaying the source for a symbol. Search for function named name.
924       FindMatchingFunctions(target, name, sc_list);
925       if (sc_list.GetSize() == 0) {
926         // If we didn't find any functions with that name, try searching for
927         // symbols that line up exactly with function addresses.
928         SymbolContextList sc_list_symbols;
929         FindMatchingFunctionSymbols(target, name, sc_list_symbols);
930         for (const SymbolContext &sc : sc_list_symbols) {
931           if (sc.symbol && sc.symbol->ValueIsAddress()) {
932             const Address &base_address = sc.symbol->GetAddressRef();
933             Function *function = base_address.CalculateSymbolContextFunction();
934             if (function) {
935               sc_list.Append(SymbolContext(function));
936               break;
937             }
938           }
939         }
940       }
941 
942       if (sc_list.GetSize() == 0) {
943         result.AppendErrorWithFormat("Could not find function named: \"%s\".\n",
944                                      m_options.symbol_name.c_str());
945         return;
946       }
947 
948       std::set<SourceInfo> source_match_set;
949       bool displayed_something = false;
950       for (const SymbolContext &sc : sc_list) {
951         SourceInfo source_info(sc.GetFunctionName(),
952                                sc.GetFunctionStartLineEntry());
953         if (source_info.IsValid() &&
954             source_match_set.find(source_info) == source_match_set.end()) {
955           source_match_set.insert(source_info);
956           if (DisplayFunctionSource(sc, source_info, result))
957             displayed_something = true;
958         }
959       }
960       if (displayed_something)
961         result.SetStatus(eReturnStatusSuccessFinishResult);
962       else
963         result.SetStatus(eReturnStatusFailed);
964       return;
965     } else if (m_options.address != LLDB_INVALID_ADDRESS) {
966       Address so_addr;
967       StreamString error_strm;
968       SymbolContextList sc_list;
969 
970       if (target->GetSectionLoadList().IsEmpty()) {
971         // The target isn't loaded yet, we need to lookup the file address in
972         // all modules
973         const ModuleList &module_list = target->GetImages();
974         const size_t num_modules = module_list.GetSize();
975         for (size_t i = 0; i < num_modules; ++i) {
976           ModuleSP module_sp(module_list.GetModuleAtIndex(i));
977           if (module_sp &&
978               module_sp->ResolveFileAddress(m_options.address, so_addr)) {
979             SymbolContext sc;
980             sc.Clear(true);
981             if (module_sp->ResolveSymbolContextForAddress(
982                     so_addr, eSymbolContextEverything, sc) &
983                 eSymbolContextLineEntry)
984               sc_list.Append(sc);
985           }
986         }
987 
988         if (sc_list.GetSize() == 0) {
989           result.AppendErrorWithFormat(
990               "no modules have source information for file address 0x%" PRIx64
991               ".\n",
992               m_options.address);
993           return;
994         }
995       } else {
996         // The target has some things loaded, resolve this address to a compile
997         // unit + file + line and display
998         if (target->GetSectionLoadList().ResolveLoadAddress(m_options.address,
999                                                             so_addr)) {
1000           ModuleSP module_sp(so_addr.GetModule());
1001           if (module_sp) {
1002             SymbolContext sc;
1003             sc.Clear(true);
1004             if (module_sp->ResolveSymbolContextForAddress(
1005                     so_addr, eSymbolContextEverything, sc) &
1006                 eSymbolContextLineEntry) {
1007               sc_list.Append(sc);
1008             } else {
1009               so_addr.Dump(&error_strm, nullptr,
1010                            Address::DumpStyleModuleWithFileAddress);
1011               result.AppendErrorWithFormat("address resolves to %s, but there "
1012                                            "is no line table information "
1013                                            "available for this address.\n",
1014                                            error_strm.GetData());
1015               return;
1016             }
1017           }
1018         }
1019 
1020         if (sc_list.GetSize() == 0) {
1021           result.AppendErrorWithFormat(
1022               "no modules contain load address 0x%" PRIx64 ".\n",
1023               m_options.address);
1024           return;
1025         }
1026       }
1027       for (const SymbolContext &sc : sc_list) {
1028         if (sc.comp_unit) {
1029           if (m_options.show_bp_locs) {
1030             m_breakpoint_locations.Clear();
1031             const bool show_inlines = true;
1032             m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0,
1033                                          show_inlines);
1034             SearchFilterForUnconstrainedSearches target_search_filter(
1035                 target->shared_from_this());
1036             target_search_filter.Search(m_breakpoint_locations);
1037           }
1038 
1039           bool show_fullpaths = true;
1040           bool show_module = true;
1041           bool show_inlined_frames = true;
1042           const bool show_function_arguments = true;
1043           const bool show_function_name = true;
1044           sc.DumpStopContext(&result.GetOutputStream(),
1045                              m_exe_ctx.GetBestExecutionContextScope(),
1046                              sc.line_entry.range.GetBaseAddress(),
1047                              show_fullpaths, show_module, show_inlined_frames,
1048                              show_function_arguments, show_function_name);
1049           result.GetOutputStream().EOL();
1050 
1051           if (m_options.num_lines == 0)
1052             m_options.num_lines = 10;
1053 
1054           size_t lines_to_back_up =
1055               m_options.num_lines >= 10 ? 5 : m_options.num_lines / 2;
1056 
1057           const uint32_t column =
1058               (GetDebugger().GetStopShowColumn() != eStopShowColumnNone)
1059                   ? sc.line_entry.column
1060                   : 0;
1061           target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
1062               sc.comp_unit->GetPrimaryFile(), sc.line_entry.line, column,
1063               lines_to_back_up, m_options.num_lines - lines_to_back_up, "->",
1064               &result.GetOutputStream(), GetBreakpointLocations());
1065           result.SetStatus(eReturnStatusSuccessFinishResult);
1066         }
1067       }
1068     } else if (m_options.file_name.empty()) {
1069       // Last valid source manager context, or the current frame if no valid
1070       // last context in source manager. One little trick here, if you type the
1071       // exact same list command twice in a row, it is more likely because you
1072       // typed it once, then typed it again
1073       if (m_options.start_line == 0) {
1074         if (target->GetSourceManager().DisplayMoreWithLineNumbers(
1075                 &result.GetOutputStream(), m_options.num_lines,
1076                 m_options.reverse, GetBreakpointLocations())) {
1077           result.SetStatus(eReturnStatusSuccessFinishResult);
1078         }
1079       } else {
1080         if (m_options.num_lines == 0)
1081           m_options.num_lines = 10;
1082 
1083         if (m_options.show_bp_locs) {
1084           SourceManager::FileSP last_file_sp(
1085               target->GetSourceManager().GetLastFile());
1086           if (last_file_sp) {
1087             const bool show_inlines = true;
1088             m_breakpoint_locations.Reset(last_file_sp->GetFileSpec(), 0,
1089                                          show_inlines);
1090             SearchFilterForUnconstrainedSearches target_search_filter(
1091                 target->shared_from_this());
1092             target_search_filter.Search(m_breakpoint_locations);
1093           }
1094         } else
1095           m_breakpoint_locations.Clear();
1096 
1097         const uint32_t column = 0;
1098         if (target->GetSourceManager()
1099                 .DisplaySourceLinesWithLineNumbersUsingLastFile(
1100                     m_options.start_line, // Line to display
1101                     m_options.num_lines,  // Lines after line to
1102                     UINT32_MAX,           // Don't mark "line"
1103                     column,
1104                     "", // Don't mark "line"
1105                     &result.GetOutputStream(), GetBreakpointLocations())) {
1106           result.SetStatus(eReturnStatusSuccessFinishResult);
1107         }
1108       }
1109     } else {
1110       const char *filename = m_options.file_name.c_str();
1111 
1112       bool check_inlines = false;
1113       SymbolContextList sc_list;
1114       size_t num_matches = 0;
1115 
1116       if (!m_options.modules.empty()) {
1117         ModuleList matching_modules;
1118         for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) {
1119           FileSpec module_file_spec(m_options.modules[i]);
1120           if (module_file_spec) {
1121             ModuleSpec module_spec(module_file_spec);
1122             matching_modules.Clear();
1123             target->GetImages().FindModules(module_spec, matching_modules);
1124             num_matches += matching_modules.ResolveSymbolContextForFilePath(
1125                 filename, 0, check_inlines,
1126                 SymbolContextItem(eSymbolContextModule |
1127                                   eSymbolContextCompUnit),
1128                 sc_list);
1129           }
1130         }
1131       } else {
1132         num_matches = target->GetImages().ResolveSymbolContextForFilePath(
1133             filename, 0, check_inlines,
1134             eSymbolContextModule | eSymbolContextCompUnit, sc_list);
1135       }
1136 
1137       if (num_matches == 0) {
1138         result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
1139                                      m_options.file_name.c_str());
1140         return;
1141       }
1142 
1143       if (num_matches > 1) {
1144         bool got_multiple = false;
1145         CompileUnit *test_cu = nullptr;
1146 
1147         for (const SymbolContext &sc : sc_list) {
1148           if (sc.comp_unit) {
1149             if (test_cu) {
1150               if (test_cu != sc.comp_unit)
1151                 got_multiple = true;
1152               break;
1153             } else
1154               test_cu = sc.comp_unit;
1155           }
1156         }
1157         if (got_multiple) {
1158           result.AppendErrorWithFormat(
1159               "Multiple source files found matching: \"%s.\"\n",
1160               m_options.file_name.c_str());
1161           return;
1162         }
1163       }
1164 
1165       SymbolContext sc;
1166       if (sc_list.GetContextAtIndex(0, sc)) {
1167         if (sc.comp_unit) {
1168           if (m_options.show_bp_locs) {
1169             const bool show_inlines = true;
1170             m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0,
1171                                          show_inlines);
1172             SearchFilterForUnconstrainedSearches target_search_filter(
1173                 target->shared_from_this());
1174             target_search_filter.Search(m_breakpoint_locations);
1175           } else
1176             m_breakpoint_locations.Clear();
1177 
1178           if (m_options.num_lines == 0)
1179             m_options.num_lines = 10;
1180           const uint32_t column = 0;
1181           target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
1182               sc.comp_unit->GetPrimaryFile(), m_options.start_line, column, 0,
1183               m_options.num_lines, "", &result.GetOutputStream(),
1184               GetBreakpointLocations());
1185 
1186           result.SetStatus(eReturnStatusSuccessFinishResult);
1187         } else {
1188           result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
1189                                        m_options.file_name.c_str());
1190         }
1191       }
1192     }
1193   }
1194 
GetBreakpointLocations()1195   const SymbolContextList *GetBreakpointLocations() {
1196     if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
1197       return &m_breakpoint_locations.GetFileLineMatches();
1198     return nullptr;
1199   }
1200 
1201   CommandOptions m_options;
1202   FileLineResolver m_breakpoint_locations;
1203   std::string m_reverse_name;
1204 };
1205 
1206 class CommandObjectSourceCacheDump : public CommandObjectParsed {
1207 public:
CommandObjectSourceCacheDump(CommandInterpreter & interpreter)1208   CommandObjectSourceCacheDump(CommandInterpreter &interpreter)
1209       : CommandObjectParsed(interpreter, "source cache dump",
1210                             "Dump the state of the source code cache. Intended "
1211                             "to be used for debugging LLDB itself.",
1212                             nullptr) {}
1213 
1214   ~CommandObjectSourceCacheDump() override = default;
1215 
1216 protected:
DoExecute(Args & command,CommandReturnObject & result)1217   void DoExecute(Args &command, CommandReturnObject &result) override {
1218     // Dump the debugger source cache.
1219     result.GetOutputStream() << "Debugger Source File Cache\n";
1220     SourceManager::SourceFileCache &cache = GetDebugger().GetSourceFileCache();
1221     cache.Dump(result.GetOutputStream());
1222 
1223     // Dump the process source cache.
1224     if (ProcessSP process_sp = m_exe_ctx.GetProcessSP()) {
1225       result.GetOutputStream() << "\nProcess Source File Cache\n";
1226       SourceManager::SourceFileCache &cache = process_sp->GetSourceFileCache();
1227       cache.Dump(result.GetOutputStream());
1228     }
1229 
1230     result.SetStatus(eReturnStatusSuccessFinishResult);
1231   }
1232 };
1233 
1234 class CommandObjectSourceCacheClear : public CommandObjectParsed {
1235 public:
CommandObjectSourceCacheClear(CommandInterpreter & interpreter)1236   CommandObjectSourceCacheClear(CommandInterpreter &interpreter)
1237       : CommandObjectParsed(interpreter, "source cache clear",
1238                             "Clear the source code cache.\n", nullptr) {}
1239 
1240   ~CommandObjectSourceCacheClear() override = default;
1241 
1242 protected:
DoExecute(Args & command,CommandReturnObject & result)1243   void DoExecute(Args &command, CommandReturnObject &result) override {
1244     // Clear the debugger cache.
1245     SourceManager::SourceFileCache &cache = GetDebugger().GetSourceFileCache();
1246     cache.Clear();
1247 
1248     // Clear the process cache.
1249     if (ProcessSP process_sp = m_exe_ctx.GetProcessSP())
1250       process_sp->GetSourceFileCache().Clear();
1251 
1252     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1253   }
1254 };
1255 
1256 class CommandObjectSourceCache : public CommandObjectMultiword {
1257 public:
CommandObjectSourceCache(CommandInterpreter & interpreter)1258   CommandObjectSourceCache(CommandInterpreter &interpreter)
1259       : CommandObjectMultiword(interpreter, "source cache",
1260                                "Commands for managing the source code cache.",
1261                                "source cache <sub-command>") {
1262     LoadSubCommand(
1263         "dump", CommandObjectSP(new CommandObjectSourceCacheDump(interpreter)));
1264     LoadSubCommand("clear", CommandObjectSP(new CommandObjectSourceCacheClear(
1265                                 interpreter)));
1266   }
1267 
1268   ~CommandObjectSourceCache() override = default;
1269 
1270 private:
1271   CommandObjectSourceCache(const CommandObjectSourceCache &) = delete;
1272   const CommandObjectSourceCache &
1273   operator=(const CommandObjectSourceCache &) = delete;
1274 };
1275 
1276 #pragma mark CommandObjectMultiwordSource
1277 // CommandObjectMultiwordSource
1278 
CommandObjectMultiwordSource(CommandInterpreter & interpreter)1279 CommandObjectMultiwordSource::CommandObjectMultiwordSource(
1280     CommandInterpreter &interpreter)
1281     : CommandObjectMultiword(interpreter, "source",
1282                              "Commands for examining "
1283                              "source code described by "
1284                              "debug information for the "
1285                              "current target process.",
1286                              "source <subcommand> [<subcommand-options>]") {
1287   LoadSubCommand("info",
1288                  CommandObjectSP(new CommandObjectSourceInfo(interpreter)));
1289   LoadSubCommand("list",
1290                  CommandObjectSP(new CommandObjectSourceList(interpreter)));
1291   LoadSubCommand("cache",
1292                  CommandObjectSP(new CommandObjectSourceCache(interpreter)));
1293 }
1294 
1295 CommandObjectMultiwordSource::~CommandObjectMultiwordSource() = default;
1296