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