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