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       result.SetStatus(eReturnStatusFailed);
545       return false;
546     }
547 
548     Target *target = m_exe_ctx.GetTargetPtr();
549     if (target == nullptr) {
550       target = GetDebugger().GetSelectedTarget().get();
551       if (target == nullptr) {
552         result.AppendError("invalid target, create a debug target using the "
553                            "'target create' command.");
554         result.SetStatus(eReturnStatusFailed);
555         return false;
556       }
557     }
558 
559     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
560     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
561     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
562 
563     // Collect the list of modules to search.
564     m_module_list.Clear();
565     if (!m_options.modules.empty()) {
566       for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) {
567         FileSpec module_file_spec(m_options.modules[i]);
568         if (module_file_spec) {
569           ModuleSpec module_spec(module_file_spec);
570           target->GetImages().FindModules(module_spec, m_module_list);
571           if (m_module_list.IsEmpty())
572             result.AppendWarningWithFormat("No module found for '%s'.\n",
573                                            m_options.modules[i].c_str());
574         }
575       }
576       if (!m_module_list.GetSize()) {
577         result.AppendError("No modules match the input.");
578         result.SetStatus(eReturnStatusFailed);
579         return false;
580       }
581     } else if (target->GetImages().GetSize() == 0) {
582       result.AppendError("The target has no associated executable images.");
583       result.SetStatus(eReturnStatusFailed);
584       return false;
585     }
586 
587     // Check the arguments to see what lines we should dump.
588     if (!m_options.symbol_name.empty()) {
589       // Print lines for symbol.
590       if (DumpLinesInFunctions(result))
591         result.SetStatus(eReturnStatusSuccessFinishResult);
592       else
593         result.SetStatus(eReturnStatusFailed);
594     } else if (m_options.address != LLDB_INVALID_ADDRESS) {
595       // Print lines for an address.
596       if (DumpLinesForAddress(result))
597         result.SetStatus(eReturnStatusSuccessFinishResult);
598       else
599         result.SetStatus(eReturnStatusFailed);
600     } else if (!m_options.file_name.empty()) {
601       // Dump lines for a file.
602       if (DumpLinesForFile(result))
603         result.SetStatus(eReturnStatusSuccessFinishResult);
604       else
605         result.SetStatus(eReturnStatusFailed);
606     } else {
607       // Dump the line for the current frame.
608       if (DumpLinesForFrame(result))
609         result.SetStatus(eReturnStatusSuccessFinishResult);
610       else
611         result.SetStatus(eReturnStatusFailed);
612     }
613     return result.Succeeded();
614   }
615 
616   CommandOptions m_options;
617   ModuleList m_module_list;
618 };
619 
620 #pragma mark CommandObjectSourceList
621 // CommandObjectSourceList
622 #define LLDB_OPTIONS_source_list
623 #include "CommandOptions.inc"
624 
625 class CommandObjectSourceList : public CommandObjectParsed {
626   class CommandOptions : public Options {
627   public:
628     CommandOptions() : Options() {}
629 
630     ~CommandOptions() override = default;
631 
632     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
633                           ExecutionContext *execution_context) override {
634       Status error;
635       const int short_option = GetDefinitions()[option_idx].short_option;
636       switch (short_option) {
637       case 'l':
638         if (option_arg.getAsInteger(0, start_line))
639           error.SetErrorStringWithFormat("invalid line number: '%s'",
640                                          option_arg.str().c_str());
641         break;
642 
643       case 'c':
644         if (option_arg.getAsInteger(0, num_lines))
645           error.SetErrorStringWithFormat("invalid line count: '%s'",
646                                          option_arg.str().c_str());
647         break;
648 
649       case 'f':
650         file_name = std::string(option_arg);
651         break;
652 
653       case 'n':
654         symbol_name = std::string(option_arg);
655         break;
656 
657       case 'a': {
658         address = OptionArgParser::ToAddress(execution_context, option_arg,
659                                              LLDB_INVALID_ADDRESS, &error);
660       } break;
661       case 's':
662         modules.push_back(std::string(option_arg));
663         break;
664 
665       case 'b':
666         show_bp_locs = true;
667         break;
668       case 'r':
669         reverse = true;
670         break;
671       case 'y':
672       {
673         OptionValueFileColonLine value;
674         Status fcl_err = value.SetValueFromString(option_arg);
675         if (!fcl_err.Success()) {
676           error.SetErrorStringWithFormat(
677               "Invalid value for file:line specifier: %s",
678               fcl_err.AsCString());
679         } else {
680           file_name = value.GetFileSpec().GetPath();
681           start_line = value.GetLineNumber();
682           // I don't see anything useful to do with a column number, but I don't
683           // want to complain since someone may well have cut and pasted a
684           // listing from somewhere that included a column.
685         }
686       } break;
687       default:
688         llvm_unreachable("Unimplemented option");
689       }
690 
691       return error;
692     }
693 
694     void OptionParsingStarting(ExecutionContext *execution_context) override {
695       file_spec.Clear();
696       file_name.clear();
697       symbol_name.clear();
698       address = LLDB_INVALID_ADDRESS;
699       start_line = 0;
700       num_lines = 0;
701       show_bp_locs = false;
702       reverse = false;
703       modules.clear();
704     }
705 
706     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
707       return llvm::makeArrayRef(g_source_list_options);
708     }
709 
710     // Instance variables to hold the values for command options.
711     FileSpec file_spec;
712     std::string file_name;
713     std::string symbol_name;
714     lldb::addr_t address;
715     uint32_t start_line;
716     uint32_t num_lines;
717     std::vector<std::string> modules;
718     bool show_bp_locs;
719     bool reverse;
720   };
721 
722 public:
723   CommandObjectSourceList(CommandInterpreter &interpreter)
724       : CommandObjectParsed(interpreter, "source list",
725                             "Display source code for the current target "
726                             "process as specified by options.",
727                             nullptr, eCommandRequiresTarget),
728         m_options() {}
729 
730   ~CommandObjectSourceList() override = default;
731 
732   Options *GetOptions() override { return &m_options; }
733 
734   const char *GetRepeatCommand(Args &current_command_args,
735                                uint32_t index) override {
736     // This is kind of gross, but the command hasn't been parsed yet so we
737     // can't look at the option values for this invocation...  I have to scan
738     // the arguments directly.
739     auto iter =
740         llvm::find_if(current_command_args, [](const Args::ArgEntry &e) {
741           return e.ref() == "-r" || e.ref() == "--reverse";
742         });
743     if (iter == current_command_args.end())
744       return m_cmd_name.c_str();
745 
746     if (m_reverse_name.empty()) {
747       m_reverse_name = m_cmd_name;
748       m_reverse_name.append(" -r");
749     }
750     return m_reverse_name.c_str();
751   }
752 
753 protected:
754   struct SourceInfo {
755     ConstString function;
756     LineEntry line_entry;
757 
758     SourceInfo(ConstString name, const LineEntry &line_entry)
759         : function(name), line_entry(line_entry) {}
760 
761     SourceInfo() : function(), line_entry() {}
762 
763     bool IsValid() const { return (bool)function && line_entry.IsValid(); }
764 
765     bool operator==(const SourceInfo &rhs) const {
766       return function == rhs.function &&
767              line_entry.original_file == rhs.line_entry.original_file &&
768              line_entry.line == rhs.line_entry.line;
769     }
770 
771     bool operator!=(const SourceInfo &rhs) const {
772       return function != rhs.function ||
773              line_entry.original_file != rhs.line_entry.original_file ||
774              line_entry.line != rhs.line_entry.line;
775     }
776 
777     bool operator<(const SourceInfo &rhs) const {
778       if (function.GetCString() < rhs.function.GetCString())
779         return true;
780       if (line_entry.file.GetDirectory().GetCString() <
781           rhs.line_entry.file.GetDirectory().GetCString())
782         return true;
783       if (line_entry.file.GetFilename().GetCString() <
784           rhs.line_entry.file.GetFilename().GetCString())
785         return true;
786       if (line_entry.line < rhs.line_entry.line)
787         return true;
788       return false;
789     }
790   };
791 
792   size_t DisplayFunctionSource(const SymbolContext &sc, SourceInfo &source_info,
793                                CommandReturnObject &result) {
794     if (!source_info.IsValid()) {
795       source_info.function = sc.GetFunctionName();
796       source_info.line_entry = sc.GetFunctionStartLineEntry();
797     }
798 
799     if (sc.function) {
800       Target *target = m_exe_ctx.GetTargetPtr();
801 
802       FileSpec start_file;
803       uint32_t start_line;
804       uint32_t end_line;
805       FileSpec end_file;
806 
807       if (sc.block == nullptr) {
808         // Not an inlined function
809         sc.function->GetStartLineSourceInfo(start_file, start_line);
810         if (start_line == 0) {
811           result.AppendErrorWithFormat("Could not find line information for "
812                                        "start of function: \"%s\".\n",
813                                        source_info.function.GetCString());
814           result.SetStatus(eReturnStatusFailed);
815           return 0;
816         }
817         sc.function->GetEndLineSourceInfo(end_file, end_line);
818       } else {
819         // We have an inlined function
820         start_file = source_info.line_entry.file;
821         start_line = source_info.line_entry.line;
822         end_line = start_line + m_options.num_lines;
823       }
824 
825       // This is a little hacky, but the first line table entry for a function
826       // points to the "{" that starts the function block.  It would be nice to
827       // actually get the function declaration in there too.  So back up a bit,
828       // but not further than what you're going to display.
829       uint32_t extra_lines;
830       if (m_options.num_lines >= 10)
831         extra_lines = 5;
832       else
833         extra_lines = m_options.num_lines / 2;
834       uint32_t line_no;
835       if (start_line <= extra_lines)
836         line_no = 1;
837       else
838         line_no = start_line - extra_lines;
839 
840       // For fun, if the function is shorter than the number of lines we're
841       // supposed to display, only display the function...
842       if (end_line != 0) {
843         if (m_options.num_lines > end_line - line_no)
844           m_options.num_lines = end_line - line_no + extra_lines;
845       }
846 
847       m_breakpoint_locations.Clear();
848 
849       if (m_options.show_bp_locs) {
850         const bool show_inlines = true;
851         m_breakpoint_locations.Reset(start_file, 0, show_inlines);
852         SearchFilterForUnconstrainedSearches target_search_filter(
853             m_exe_ctx.GetTargetSP());
854         target_search_filter.Search(m_breakpoint_locations);
855       }
856 
857       result.AppendMessageWithFormat("File: %s\n",
858                                      start_file.GetPath().c_str());
859       // We don't care about the column here.
860       const uint32_t column = 0;
861       return target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
862           start_file, line_no, column, 0, m_options.num_lines, "",
863           &result.GetOutputStream(), GetBreakpointLocations());
864     } else {
865       result.AppendErrorWithFormat(
866           "Could not find function info for: \"%s\".\n",
867           m_options.symbol_name.c_str());
868     }
869     return 0;
870   }
871 
872   // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols
873   // functions "take a possibly empty vector of strings which are names of
874   // modules, and run the two search functions on the subset of the full module
875   // list that matches the strings in the input vector". If we wanted to put
876   // these somewhere, there should probably be a module-filter-list that can be
877   // passed to the various ModuleList::Find* calls, which would either be a
878   // vector of string names or a ModuleSpecList.
879   void FindMatchingFunctions(Target *target, ConstString name,
880                              SymbolContextList &sc_list) {
881     // Displaying the source for a symbol:
882     bool include_inlines = true;
883     bool include_symbols = false;
884 
885     if (m_options.num_lines == 0)
886       m_options.num_lines = 10;
887 
888     const size_t num_modules = m_options.modules.size();
889     if (num_modules > 0) {
890       ModuleList matching_modules;
891       for (size_t i = 0; i < num_modules; ++i) {
892         FileSpec module_file_spec(m_options.modules[i]);
893         if (module_file_spec) {
894           ModuleSpec module_spec(module_file_spec);
895           matching_modules.Clear();
896           target->GetImages().FindModules(module_spec, matching_modules);
897           matching_modules.FindFunctions(name, eFunctionNameTypeAuto,
898                                          include_symbols, include_inlines,
899                                          sc_list);
900         }
901       }
902     } else {
903       target->GetImages().FindFunctions(name, eFunctionNameTypeAuto,
904                                         include_symbols, include_inlines,
905                                         sc_list);
906     }
907   }
908 
909   void FindMatchingFunctionSymbols(Target *target, ConstString name,
910                                    SymbolContextList &sc_list) {
911     const size_t num_modules = m_options.modules.size();
912     if (num_modules > 0) {
913       ModuleList matching_modules;
914       for (size_t i = 0; i < num_modules; ++i) {
915         FileSpec module_file_spec(m_options.modules[i]);
916         if (module_file_spec) {
917           ModuleSpec module_spec(module_file_spec);
918           matching_modules.Clear();
919           target->GetImages().FindModules(module_spec, matching_modules);
920           matching_modules.FindFunctionSymbols(name, eFunctionNameTypeAuto,
921                                                sc_list);
922         }
923       }
924     } else {
925       target->GetImages().FindFunctionSymbols(name, eFunctionNameTypeAuto,
926                                               sc_list);
927     }
928   }
929 
930   bool DoExecute(Args &command, CommandReturnObject &result) override {
931     const size_t argc = command.GetArgumentCount();
932 
933     if (argc != 0) {
934       result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n",
935                                    GetCommandName().str().c_str());
936       result.SetStatus(eReturnStatusFailed);
937       return false;
938     }
939 
940     Target *target = m_exe_ctx.GetTargetPtr();
941 
942     if (!m_options.symbol_name.empty()) {
943       SymbolContextList sc_list;
944       ConstString name(m_options.symbol_name.c_str());
945 
946       // Displaying the source for a symbol. Search for function named name.
947       FindMatchingFunctions(target, name, sc_list);
948       size_t num_matches = sc_list.GetSize();
949       if (!num_matches) {
950         // If we didn't find any functions with that name, try searching for
951         // symbols that line up exactly with function addresses.
952         SymbolContextList sc_list_symbols;
953         FindMatchingFunctionSymbols(target, name, sc_list_symbols);
954         size_t num_symbol_matches = sc_list_symbols.GetSize();
955 
956         for (size_t i = 0; i < num_symbol_matches; i++) {
957           SymbolContext sc;
958           sc_list_symbols.GetContextAtIndex(i, sc);
959           if (sc.symbol && sc.symbol->ValueIsAddress()) {
960             const Address &base_address = sc.symbol->GetAddressRef();
961             Function *function = base_address.CalculateSymbolContextFunction();
962             if (function) {
963               sc_list.Append(SymbolContext(function));
964               num_matches++;
965               break;
966             }
967           }
968         }
969       }
970 
971       if (num_matches == 0) {
972         result.AppendErrorWithFormat("Could not find function named: \"%s\".\n",
973                                      m_options.symbol_name.c_str());
974         result.SetStatus(eReturnStatusFailed);
975         return false;
976       }
977 
978       if (num_matches > 1) {
979         std::set<SourceInfo> source_match_set;
980 
981         bool displayed_something = false;
982         for (size_t i = 0; i < num_matches; i++) {
983           SymbolContext sc;
984           sc_list.GetContextAtIndex(i, sc);
985           SourceInfo source_info(sc.GetFunctionName(),
986                                  sc.GetFunctionStartLineEntry());
987 
988           if (source_info.IsValid()) {
989             if (source_match_set.find(source_info) == source_match_set.end()) {
990               source_match_set.insert(source_info);
991               if (DisplayFunctionSource(sc, source_info, result))
992                 displayed_something = true;
993             }
994           }
995         }
996 
997         if (displayed_something)
998           result.SetStatus(eReturnStatusSuccessFinishResult);
999         else
1000           result.SetStatus(eReturnStatusFailed);
1001       } else {
1002         SymbolContext sc;
1003         sc_list.GetContextAtIndex(0, sc);
1004         SourceInfo source_info;
1005 
1006         if (DisplayFunctionSource(sc, source_info, result)) {
1007           result.SetStatus(eReturnStatusSuccessFinishResult);
1008         } else {
1009           result.SetStatus(eReturnStatusFailed);
1010         }
1011       }
1012       return result.Succeeded();
1013     } else if (m_options.address != LLDB_INVALID_ADDRESS) {
1014       Address so_addr;
1015       StreamString error_strm;
1016       SymbolContextList sc_list;
1017 
1018       if (target->GetSectionLoadList().IsEmpty()) {
1019         // The target isn't loaded yet, we need to lookup the file address in
1020         // all modules
1021         const ModuleList &module_list = target->GetImages();
1022         const size_t num_modules = module_list.GetSize();
1023         for (size_t i = 0; i < num_modules; ++i) {
1024           ModuleSP module_sp(module_list.GetModuleAtIndex(i));
1025           if (module_sp &&
1026               module_sp->ResolveFileAddress(m_options.address, so_addr)) {
1027             SymbolContext sc;
1028             sc.Clear(true);
1029             if (module_sp->ResolveSymbolContextForAddress(
1030                     so_addr, eSymbolContextEverything, sc) &
1031                 eSymbolContextLineEntry)
1032               sc_list.Append(sc);
1033           }
1034         }
1035 
1036         if (sc_list.GetSize() == 0) {
1037           result.AppendErrorWithFormat(
1038               "no modules have source information for file address 0x%" PRIx64
1039               ".\n",
1040               m_options.address);
1041           result.SetStatus(eReturnStatusFailed);
1042           return false;
1043         }
1044       } else {
1045         // The target has some things loaded, resolve this address to a compile
1046         // unit + file + line and display
1047         if (target->GetSectionLoadList().ResolveLoadAddress(m_options.address,
1048                                                             so_addr)) {
1049           ModuleSP module_sp(so_addr.GetModule());
1050           if (module_sp) {
1051             SymbolContext sc;
1052             sc.Clear(true);
1053             if (module_sp->ResolveSymbolContextForAddress(
1054                     so_addr, eSymbolContextEverything, sc) &
1055                 eSymbolContextLineEntry) {
1056               sc_list.Append(sc);
1057             } else {
1058               so_addr.Dump(&error_strm, nullptr,
1059                            Address::DumpStyleModuleWithFileAddress);
1060               result.AppendErrorWithFormat("address resolves to %s, but there "
1061                                            "is no line table information "
1062                                            "available for this address.\n",
1063                                            error_strm.GetData());
1064               result.SetStatus(eReturnStatusFailed);
1065               return false;
1066             }
1067           }
1068         }
1069 
1070         if (sc_list.GetSize() == 0) {
1071           result.AppendErrorWithFormat(
1072               "no modules contain load address 0x%" PRIx64 ".\n",
1073               m_options.address);
1074           result.SetStatus(eReturnStatusFailed);
1075           return false;
1076         }
1077       }
1078       uint32_t num_matches = sc_list.GetSize();
1079       for (uint32_t i = 0; i < num_matches; ++i) {
1080         SymbolContext sc;
1081         sc_list.GetContextAtIndex(i, sc);
1082         if (sc.comp_unit) {
1083           if (m_options.show_bp_locs) {
1084             m_breakpoint_locations.Clear();
1085             const bool show_inlines = true;
1086             m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0,
1087                                          show_inlines);
1088             SearchFilterForUnconstrainedSearches target_search_filter(
1089                 target->shared_from_this());
1090             target_search_filter.Search(m_breakpoint_locations);
1091           }
1092 
1093           bool show_fullpaths = true;
1094           bool show_module = true;
1095           bool show_inlined_frames = true;
1096           const bool show_function_arguments = true;
1097           const bool show_function_name = true;
1098           sc.DumpStopContext(&result.GetOutputStream(),
1099                              m_exe_ctx.GetBestExecutionContextScope(),
1100                              sc.line_entry.range.GetBaseAddress(),
1101                              show_fullpaths, show_module, show_inlined_frames,
1102                              show_function_arguments, show_function_name);
1103           result.GetOutputStream().EOL();
1104 
1105           if (m_options.num_lines == 0)
1106             m_options.num_lines = 10;
1107 
1108           size_t lines_to_back_up =
1109               m_options.num_lines >= 10 ? 5 : m_options.num_lines / 2;
1110 
1111           const uint32_t column =
1112               (GetDebugger().GetStopShowColumn() != eStopShowColumnNone)
1113                   ? sc.line_entry.column
1114                   : 0;
1115           target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
1116               sc.comp_unit->GetPrimaryFile(), sc.line_entry.line, column,
1117               lines_to_back_up, m_options.num_lines - lines_to_back_up, "->",
1118               &result.GetOutputStream(), GetBreakpointLocations());
1119           result.SetStatus(eReturnStatusSuccessFinishResult);
1120         }
1121       }
1122     } else if (m_options.file_name.empty()) {
1123       // Last valid source manager context, or the current frame if no valid
1124       // last context in source manager. One little trick here, if you type the
1125       // exact same list command twice in a row, it is more likely because you
1126       // typed it once, then typed it again
1127       if (m_options.start_line == 0) {
1128         if (target->GetSourceManager().DisplayMoreWithLineNumbers(
1129                 &result.GetOutputStream(), m_options.num_lines,
1130                 m_options.reverse, GetBreakpointLocations())) {
1131           result.SetStatus(eReturnStatusSuccessFinishResult);
1132         }
1133       } else {
1134         if (m_options.num_lines == 0)
1135           m_options.num_lines = 10;
1136 
1137         if (m_options.show_bp_locs) {
1138           SourceManager::FileSP last_file_sp(
1139               target->GetSourceManager().GetLastFile());
1140           if (last_file_sp) {
1141             const bool show_inlines = true;
1142             m_breakpoint_locations.Reset(last_file_sp->GetFileSpec(), 0,
1143                                          show_inlines);
1144             SearchFilterForUnconstrainedSearches target_search_filter(
1145                 target->shared_from_this());
1146             target_search_filter.Search(m_breakpoint_locations);
1147           }
1148         } else
1149           m_breakpoint_locations.Clear();
1150 
1151         const uint32_t column = 0;
1152         if (target->GetSourceManager()
1153                 .DisplaySourceLinesWithLineNumbersUsingLastFile(
1154                     m_options.start_line, // Line to display
1155                     m_options.num_lines,  // Lines after line to
1156                     UINT32_MAX,           // Don't mark "line"
1157                     column,
1158                     "", // Don't mark "line"
1159                     &result.GetOutputStream(), GetBreakpointLocations())) {
1160           result.SetStatus(eReturnStatusSuccessFinishResult);
1161         }
1162       }
1163     } else {
1164       const char *filename = m_options.file_name.c_str();
1165 
1166       bool check_inlines = false;
1167       SymbolContextList sc_list;
1168       size_t num_matches = 0;
1169 
1170       if (!m_options.modules.empty()) {
1171         ModuleList matching_modules;
1172         for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) {
1173           FileSpec module_file_spec(m_options.modules[i]);
1174           if (module_file_spec) {
1175             ModuleSpec module_spec(module_file_spec);
1176             matching_modules.Clear();
1177             target->GetImages().FindModules(module_spec, matching_modules);
1178             num_matches += matching_modules.ResolveSymbolContextForFilePath(
1179                 filename, 0, check_inlines,
1180                 SymbolContextItem(eSymbolContextModule |
1181                                   eSymbolContextCompUnit),
1182                 sc_list);
1183           }
1184         }
1185       } else {
1186         num_matches = target->GetImages().ResolveSymbolContextForFilePath(
1187             filename, 0, check_inlines,
1188             eSymbolContextModule | eSymbolContextCompUnit, sc_list);
1189       }
1190 
1191       if (num_matches == 0) {
1192         result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
1193                                      m_options.file_name.c_str());
1194         result.SetStatus(eReturnStatusFailed);
1195         return false;
1196       }
1197 
1198       if (num_matches > 1) {
1199         bool got_multiple = false;
1200         CompileUnit *test_cu = nullptr;
1201 
1202         for (unsigned i = 0; i < num_matches; i++) {
1203           SymbolContext sc;
1204           sc_list.GetContextAtIndex(i, sc);
1205           if (sc.comp_unit) {
1206             if (test_cu) {
1207               if (test_cu != sc.comp_unit)
1208                 got_multiple = true;
1209               break;
1210             } else
1211               test_cu = sc.comp_unit;
1212           }
1213         }
1214         if (got_multiple) {
1215           result.AppendErrorWithFormat(
1216               "Multiple source files found matching: \"%s.\"\n",
1217               m_options.file_name.c_str());
1218           result.SetStatus(eReturnStatusFailed);
1219           return false;
1220         }
1221       }
1222 
1223       SymbolContext sc;
1224       if (sc_list.GetContextAtIndex(0, sc)) {
1225         if (sc.comp_unit) {
1226           if (m_options.show_bp_locs) {
1227             const bool show_inlines = true;
1228             m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0,
1229                                          show_inlines);
1230             SearchFilterForUnconstrainedSearches target_search_filter(
1231                 target->shared_from_this());
1232             target_search_filter.Search(m_breakpoint_locations);
1233           } else
1234             m_breakpoint_locations.Clear();
1235 
1236           if (m_options.num_lines == 0)
1237             m_options.num_lines = 10;
1238           const uint32_t column = 0;
1239           target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
1240               sc.comp_unit->GetPrimaryFile(), m_options.start_line, column, 0,
1241               m_options.num_lines, "", &result.GetOutputStream(),
1242               GetBreakpointLocations());
1243 
1244           result.SetStatus(eReturnStatusSuccessFinishResult);
1245         } else {
1246           result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
1247                                        m_options.file_name.c_str());
1248           result.SetStatus(eReturnStatusFailed);
1249           return false;
1250         }
1251       }
1252     }
1253     return result.Succeeded();
1254   }
1255 
1256   const SymbolContextList *GetBreakpointLocations() {
1257     if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
1258       return &m_breakpoint_locations.GetFileLineMatches();
1259     return nullptr;
1260   }
1261 
1262   CommandOptions m_options;
1263   FileLineResolver m_breakpoint_locations;
1264   std::string m_reverse_name;
1265 };
1266 
1267 #pragma mark CommandObjectMultiwordSource
1268 // CommandObjectMultiwordSource
1269 
1270 CommandObjectMultiwordSource::CommandObjectMultiwordSource(
1271     CommandInterpreter &interpreter)
1272     : CommandObjectMultiword(interpreter, "source",
1273                              "Commands for examining "
1274                              "source code described by "
1275                              "debug information for the "
1276                              "current target process.",
1277                              "source <subcommand> [<subcommand-options>]") {
1278   LoadSubCommand("info",
1279                  CommandObjectSP(new CommandObjectSourceInfo(interpreter)));
1280   LoadSubCommand("list",
1281                  CommandObjectSP(new CommandObjectSourceList(interpreter)));
1282 }
1283 
1284 CommandObjectMultiwordSource::~CommandObjectMultiwordSource() = default;
1285