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     {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount,
705      "The number of line entries to display."},
706     {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr,
707      CommandCompletions::eModuleCompletion, eArgTypeShlibName,
708      "Look up the source in the given module or shared library (can be "
709      "specified more than once)."},
710     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr,
711      CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
712     {LLDB_OPT_SET_1, false, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum,
713      "The line number at which to start the displaying lines."},
714     {LLDB_OPT_SET_1, false, "end-line", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum,
715      "The line number at which to stop displaying lines."},
716     {LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr,
717      CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."},
718     {LLDB_OPT_SET_3, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression,
719      "Lookup the address and display the source information for the "
720      "corresponding file and line."},
721     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
722 };
723 
724 #pragma mark CommandObjectSourceList
725 //-------------------------------------------------------------------------
726 // CommandObjectSourceList
727 //-------------------------------------------------------------------------
728 
729 class CommandObjectSourceList : public CommandObjectParsed
730 {
731     class CommandOptions : public Options
732     {
733     public:
734         CommandOptions() :
735             Options()
736         {
737         }
738 
739         ~CommandOptions() override = default;
740 
741         Error
742         SetOptionValue(uint32_t option_idx, const char *option_arg,
743                        ExecutionContext *execution_context) override
744         {
745             Error error;
746             const int short_option = g_option_table[option_idx].short_option;
747             switch (short_option)
748             {
749             case 'l':
750                 start_line = StringConvert::ToUInt32 (option_arg, 0);
751                 if (start_line == 0)
752                     error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
753                 break;
754 
755             case 'c':
756                 num_lines = StringConvert::ToUInt32 (option_arg, 0);
757                 if (num_lines == 0)
758                     error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg);
759                 break;
760 
761             case 'f':
762                 file_name = option_arg;
763                 break;
764 
765             case 'n':
766                 symbol_name = option_arg;
767                 break;
768 
769             case 'a':
770                 {
771                     address = Args::StringToAddress(execution_context,
772                                                     option_arg,
773                                                     LLDB_INVALID_ADDRESS,
774                                                     &error);
775                 }
776                 break;
777             case 's':
778                 modules.push_back (std::string (option_arg));
779                 break;
780 
781             case 'b':
782                 show_bp_locs = true;
783                 break;
784             case 'r':
785                 reverse = true;
786                 break;
787            default:
788                 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
789                 break;
790             }
791 
792             return error;
793         }
794 
795         void
796         OptionParsingStarting(ExecutionContext *execution_context) override
797         {
798             file_spec.Clear();
799             file_name.clear();
800             symbol_name.clear();
801             address = LLDB_INVALID_ADDRESS;
802             start_line = 0;
803             num_lines = 0;
804             show_bp_locs = false;
805             reverse = false;
806             modules.clear();
807         }
808 
809         const OptionDefinition*
810         GetDefinitions () override
811         {
812             return g_option_table;
813         }
814 
815         static OptionDefinition g_option_table[];
816 
817         // Instance variables to hold the values for command options.
818         FileSpec file_spec;
819         std::string file_name;
820         std::string symbol_name;
821         lldb::addr_t address;
822         uint32_t start_line;
823         uint32_t num_lines;
824         STLStringArray modules;
825         bool show_bp_locs;
826         bool reverse;
827     };
828 
829 public:
830     CommandObjectSourceList(CommandInterpreter &interpreter)
831         : CommandObjectParsed(interpreter, "source list",
832                               "Display source code for the current target process as specified by options.", nullptr,
833                               eCommandRequiresTarget),
834           m_options()
835     {
836     }
837 
838     ~CommandObjectSourceList() override = default;
839 
840     Options *
841     GetOptions () override
842     {
843         return &m_options;
844     }
845 
846     const char *
847     GetRepeatCommand (Args &current_command_args, uint32_t index) override
848     {
849         // This is kind of gross, but the command hasn't been parsed yet so we can't look at the option
850         // values for this invocation...  I have to scan the arguments directly.
851         size_t num_args = current_command_args.GetArgumentCount();
852         bool is_reverse = false;
853         for (size_t i = 0; i < num_args; i++)
854         {
855             const char *arg = current_command_args.GetArgumentAtIndex(i);
856             if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0))
857             {
858                 is_reverse = true;
859             }
860         }
861         if (is_reverse)
862         {
863             if (m_reverse_name.empty())
864             {
865                 m_reverse_name = m_cmd_name;
866                 m_reverse_name.append (" -r");
867             }
868             return m_reverse_name.c_str();
869         }
870         else
871             return m_cmd_name.c_str();
872     }
873 
874 protected:
875     struct SourceInfo
876     {
877         ConstString function;
878         LineEntry line_entry;
879 
880         SourceInfo (const ConstString &name, const LineEntry &line_entry) :
881             function(name),
882             line_entry(line_entry)
883         {
884         }
885 
886         SourceInfo () :
887             function(),
888             line_entry()
889         {
890         }
891 
892         bool
893         IsValid () const
894         {
895             return (bool)function && line_entry.IsValid();
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             return function != rhs.function ||
910             line_entry.original_file != rhs.line_entry.original_file ||
911             line_entry.line != rhs.line_entry.line;
912         }
913 
914         bool
915         operator < (const SourceInfo &rhs) const
916         {
917             if (function.GetCString() < rhs.function.GetCString())
918                 return true;
919             if (line_entry.file.GetDirectory().GetCString() < rhs.line_entry.file.GetDirectory().GetCString())
920                 return true;
921             if (line_entry.file.GetFilename().GetCString() < rhs.line_entry.file.GetFilename().GetCString())
922                 return true;
923             if (line_entry.line < rhs.line_entry.line)
924                 return true;
925             return false;
926         }
927     };
928 
929     size_t
930     DisplayFunctionSource (const SymbolContext &sc,
931                            SourceInfo &source_info,
932                            CommandReturnObject &result)
933     {
934         if (!source_info.IsValid())
935         {
936             source_info.function = sc.GetFunctionName();
937             source_info.line_entry = sc.GetFunctionStartLineEntry();
938         }
939 
940         if (sc.function)
941         {
942             Target *target = m_exe_ctx.GetTargetPtr();
943 
944             FileSpec start_file;
945             uint32_t start_line;
946             uint32_t end_line;
947             FileSpec end_file;
948 
949             if (sc.block == nullptr)
950             {
951                 // Not an inlined function
952                 sc.function->GetStartLineSourceInfo (start_file, start_line);
953                 if (start_line == 0)
954                 {
955                     result.AppendErrorWithFormat("Could not find line information for start of function: \"%s\".\n", source_info.function.GetCString());
956                     result.SetStatus (eReturnStatusFailed);
957                     return 0;
958                 }
959                 sc.function->GetEndLineSourceInfo (end_file, end_line);
960             }
961             else
962             {
963                 // We have an inlined function
964                 start_file = source_info.line_entry.file;
965                 start_line = source_info.line_entry.line;
966                 end_line = start_line + m_options.num_lines;
967             }
968 
969             // This is a little hacky, but the first line table entry for a function points to the "{" that
970             // starts the function block.  It would be nice to actually get the function
971             // declaration in there too.  So back up a bit, but not further than what you're going to display.
972             uint32_t extra_lines;
973             if (m_options.num_lines >= 10)
974                 extra_lines = 5;
975             else
976                 extra_lines = m_options.num_lines/2;
977             uint32_t line_no;
978             if (start_line <= extra_lines)
979                 line_no = 1;
980             else
981                 line_no = start_line - extra_lines;
982 
983             // For fun, if the function is shorter than the number of lines we're supposed to display,
984             // only display the function...
985             if (end_line != 0)
986             {
987                 if (m_options.num_lines > end_line - line_no)
988                     m_options.num_lines = end_line - line_no + extra_lines;
989             }
990 
991             m_breakpoint_locations.Clear();
992 
993             if (m_options.show_bp_locs)
994             {
995                 const bool show_inlines = true;
996                 m_breakpoint_locations.Reset (start_file, 0, show_inlines);
997                 SearchFilterForUnconstrainedSearches target_search_filter (m_exe_ctx.GetTargetSP());
998                 target_search_filter.Search (m_breakpoint_locations);
999             }
1000 
1001             result.AppendMessageWithFormat("File: %s\n", start_file.GetPath().c_str());
1002             return target->GetSourceManager().DisplaySourceLinesWithLineNumbers (start_file,
1003                                                                                  line_no,
1004                                                                                  0,
1005                                                                                  m_options.num_lines,
1006                                                                                  "",
1007                                                                                  &result.GetOutputStream(),
1008                                                                                  GetBreakpointLocations ());
1009         }
1010         else
1011         {
1012             result.AppendErrorWithFormat("Could not find function info for: \"%s\".\n", m_options.symbol_name.c_str());
1013         }
1014         return 0;
1015     }
1016 
1017     // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions
1018     // "take a possibly empty vector of strings which are names of modules, and
1019     // run the two search functions on the subset of the full module list that
1020     // matches the strings in the input vector". If we wanted to put these somewhere,
1021     // there should probably be a module-filter-list that can be passed to the
1022     // various ModuleList::Find* calls, which would either be a vector of string
1023     // names or a ModuleSpecList.
1024     size_t FindMatchingFunctions (Target *target, const ConstString &name, SymbolContextList& sc_list)
1025     {
1026         // Displaying the source for a symbol:
1027         bool include_inlines = true;
1028         bool append = true;
1029         bool include_symbols = false;
1030         size_t num_matches = 0;
1031 
1032         if (m_options.num_lines == 0)
1033             m_options.num_lines = 10;
1034 
1035         const size_t num_modules = m_options.modules.size();
1036         if (num_modules > 0)
1037         {
1038             ModuleList matching_modules;
1039             for (size_t i = 0; i < num_modules; ++i)
1040             {
1041                 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1042                 if (module_file_spec)
1043                 {
1044                     ModuleSpec module_spec (module_file_spec);
1045                     matching_modules.Clear();
1046                     target->GetImages().FindModules (module_spec, matching_modules);
1047                     num_matches += matching_modules.FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
1048                 }
1049             }
1050         }
1051         else
1052         {
1053             num_matches = target->GetImages().FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
1054         }
1055         return num_matches;
1056     }
1057 
1058     size_t FindMatchingFunctionSymbols (Target *target, const ConstString &name, SymbolContextList& sc_list)
1059     {
1060         size_t num_matches = 0;
1061         const size_t num_modules = m_options.modules.size();
1062         if (num_modules > 0)
1063         {
1064             ModuleList matching_modules;
1065             for (size_t i = 0; i < num_modules; ++i)
1066             {
1067                 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1068                 if (module_file_spec)
1069                 {
1070                     ModuleSpec module_spec (module_file_spec);
1071                     matching_modules.Clear();
1072                     target->GetImages().FindModules (module_spec, matching_modules);
1073                     num_matches += matching_modules.FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
1074                 }
1075             }
1076         }
1077         else
1078         {
1079             num_matches = target->GetImages().FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
1080         }
1081         return num_matches;
1082     }
1083 
1084     bool
1085     DoExecute (Args& command, CommandReturnObject &result) override
1086     {
1087         const size_t argc = command.GetArgumentCount();
1088 
1089         if (argc != 0)
1090         {
1091             result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", GetCommandName());
1092             result.SetStatus (eReturnStatusFailed);
1093             return false;
1094         }
1095 
1096         Target *target = m_exe_ctx.GetTargetPtr();
1097 
1098         if (!m_options.symbol_name.empty())
1099         {
1100             SymbolContextList sc_list;
1101             ConstString name(m_options.symbol_name.c_str());
1102 
1103             // Displaying the source for a symbol. Search for function named name.
1104             size_t num_matches = FindMatchingFunctions (target, name, sc_list);
1105             if (!num_matches)
1106             {
1107                 // If we didn't find any functions with that name, try searching for symbols
1108                 // that line up exactly with function addresses.
1109                 SymbolContextList sc_list_symbols;
1110                 size_t num_symbol_matches = FindMatchingFunctionSymbols (target, name, sc_list_symbols);
1111                 for (size_t i = 0; i < num_symbol_matches; i++)
1112                 {
1113                     SymbolContext sc;
1114                     sc_list_symbols.GetContextAtIndex (i, sc);
1115                     if (sc.symbol && sc.symbol->ValueIsAddress())
1116                     {
1117                         const Address &base_address = sc.symbol->GetAddressRef();
1118                         Function *function = base_address.CalculateSymbolContextFunction();
1119                         if (function)
1120                         {
1121                             sc_list.Append (SymbolContext(function));
1122                             num_matches++;
1123                             break;
1124                         }
1125                     }
1126                 }
1127             }
1128 
1129             if (num_matches == 0)
1130             {
1131                 result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", m_options.symbol_name.c_str());
1132                 result.SetStatus (eReturnStatusFailed);
1133                 return false;
1134             }
1135 
1136             if (num_matches > 1)
1137             {
1138                 std::set<SourceInfo> source_match_set;
1139 
1140                 bool displayed_something = false;
1141                 for (size_t i = 0; i < num_matches; i++)
1142                 {
1143                     SymbolContext sc;
1144                     sc_list.GetContextAtIndex (i, sc);
1145                     SourceInfo source_info (sc.GetFunctionName(),
1146                                             sc.GetFunctionStartLineEntry());
1147 
1148                     if (source_info.IsValid())
1149                     {
1150                         if (source_match_set.find(source_info) == source_match_set.end())
1151                         {
1152                             source_match_set.insert(source_info);
1153                             if (DisplayFunctionSource (sc, source_info, result))
1154                                 displayed_something = true;
1155                         }
1156                     }
1157                 }
1158 
1159                 if (displayed_something)
1160                     result.SetStatus (eReturnStatusSuccessFinishResult);
1161                 else
1162                     result.SetStatus (eReturnStatusFailed);
1163             }
1164             else
1165             {
1166                 SymbolContext sc;
1167                 sc_list.GetContextAtIndex (0, sc);
1168                 SourceInfo source_info;
1169 
1170                 if (DisplayFunctionSource (sc, source_info, result))
1171                 {
1172                     result.SetStatus (eReturnStatusSuccessFinishResult);
1173                 }
1174                 else
1175                 {
1176                     result.SetStatus (eReturnStatusFailed);
1177                 }
1178             }
1179             return result.Succeeded();
1180         }
1181         else if (m_options.address != LLDB_INVALID_ADDRESS)
1182         {
1183             Address so_addr;
1184             StreamString error_strm;
1185             SymbolContextList sc_list;
1186 
1187             if (target->GetSectionLoadList().IsEmpty())
1188             {
1189                 // The target isn't loaded yet, we need to lookup the file address
1190                 // in all modules
1191                 const ModuleList &module_list = target->GetImages();
1192                 const size_t num_modules = module_list.GetSize();
1193                 for (size_t i = 0; i < num_modules; ++i)
1194                 {
1195                     ModuleSP module_sp (module_list.GetModuleAtIndex(i));
1196                     if (module_sp && module_sp->ResolveFileAddress(m_options.address, so_addr))
1197                     {
1198                         SymbolContext sc;
1199                         sc.Clear(true);
1200                         if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
1201                             sc_list.Append(sc);
1202                     }
1203                 }
1204 
1205                 if (sc_list.GetSize() == 0)
1206                 {
1207                     result.AppendErrorWithFormat("no modules have source information for file address 0x%" PRIx64 ".\n",
1208                                                  m_options.address);
1209                     result.SetStatus (eReturnStatusFailed);
1210                     return false;
1211                 }
1212             }
1213             else
1214             {
1215                 // The target has some things loaded, resolve this address to a
1216                 // compile unit + file + line and display
1217                 if (target->GetSectionLoadList().ResolveLoadAddress (m_options.address, so_addr))
1218                 {
1219                     ModuleSP module_sp (so_addr.GetModule());
1220                     if (module_sp)
1221                     {
1222                         SymbolContext sc;
1223                         sc.Clear(true);
1224                         if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
1225                         {
1226                             sc_list.Append(sc);
1227                         }
1228                         else
1229                         {
1230                             so_addr.Dump(&error_strm, nullptr, Address::DumpStyleModuleWithFileAddress);
1231                             result.AppendErrorWithFormat("address resolves to %s, but there is no line table information available for this address.\n",
1232                                                          error_strm.GetData());
1233                             result.SetStatus (eReturnStatusFailed);
1234                             return false;
1235                         }
1236                     }
1237                 }
1238 
1239                 if (sc_list.GetSize() == 0)
1240                 {
1241                     result.AppendErrorWithFormat("no modules contain load address 0x%" PRIx64 ".\n", m_options.address);
1242                     result.SetStatus (eReturnStatusFailed);
1243                     return false;
1244                 }
1245             }
1246             uint32_t num_matches = sc_list.GetSize();
1247             for (uint32_t i = 0; i < num_matches; ++i)
1248             {
1249                 SymbolContext sc;
1250                 sc_list.GetContextAtIndex(i, sc);
1251                 if (sc.comp_unit)
1252                 {
1253                     if (m_options.show_bp_locs)
1254                     {
1255                         m_breakpoint_locations.Clear();
1256                         const bool show_inlines = true;
1257                         m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
1258                         SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1259                         target_search_filter.Search (m_breakpoint_locations);
1260                     }
1261 
1262                     bool show_fullpaths = true;
1263                     bool show_module = true;
1264                     bool show_inlined_frames = true;
1265                     const bool show_function_arguments = true;
1266                     const bool show_function_name = true;
1267                     sc.DumpStopContext(&result.GetOutputStream(),
1268                                        m_exe_ctx.GetBestExecutionContextScope(),
1269                                        sc.line_entry.range.GetBaseAddress(),
1270                                        show_fullpaths,
1271                                        show_module,
1272                                        show_inlined_frames,
1273                                        show_function_arguments,
1274                                        show_function_name);
1275                     result.GetOutputStream().EOL();
1276 
1277                     if (m_options.num_lines == 0)
1278                         m_options.num_lines = 10;
1279 
1280                     size_t lines_to_back_up = m_options.num_lines >= 10 ? 5 : m_options.num_lines/2;
1281 
1282                     target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
1283                                                                                   sc.line_entry.line,
1284                                                                                   lines_to_back_up,
1285                                                                                   m_options.num_lines - lines_to_back_up,
1286                                                                                   "->",
1287                                                                                   &result.GetOutputStream(),
1288                                                                                   GetBreakpointLocations ());
1289                     result.SetStatus (eReturnStatusSuccessFinishResult);
1290                 }
1291             }
1292         }
1293         else if (m_options.file_name.empty())
1294         {
1295             // Last valid source manager context, or the current frame if no
1296             // valid last context in source manager.
1297             // One little trick here, if you type the exact same list command twice in a row, it is
1298             // more likely because you typed it once, then typed it again
1299             if (m_options.start_line == 0)
1300             {
1301                 if (target->GetSourceManager().DisplayMoreWithLineNumbers (&result.GetOutputStream(),
1302                                                                            m_options.num_lines,
1303                                                                            m_options.reverse,
1304                                                                            GetBreakpointLocations ()))
1305                 {
1306                     result.SetStatus (eReturnStatusSuccessFinishResult);
1307                 }
1308             }
1309             else
1310             {
1311                 if (m_options.num_lines == 0)
1312                     m_options.num_lines = 10;
1313 
1314                 if (m_options.show_bp_locs)
1315                 {
1316                     SourceManager::FileSP last_file_sp (target->GetSourceManager().GetLastFile ());
1317                     if (last_file_sp)
1318                     {
1319                         const bool show_inlines = true;
1320                         m_breakpoint_locations.Reset (last_file_sp->GetFileSpec(), 0, show_inlines);
1321                         SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1322                         target_search_filter.Search (m_breakpoint_locations);
1323                     }
1324                 }
1325                 else
1326                     m_breakpoint_locations.Clear();
1327 
1328                 if (target->GetSourceManager().DisplaySourceLinesWithLineNumbersUsingLastFile(
1329                             m_options.start_line,   // Line to display
1330                             m_options.num_lines,    // Lines after line to
1331                             UINT32_MAX,             // Don't mark "line"
1332                             "",                     // Don't mark "line"
1333                             &result.GetOutputStream(),
1334                             GetBreakpointLocations ()))
1335                 {
1336                     result.SetStatus (eReturnStatusSuccessFinishResult);
1337                 }
1338             }
1339         }
1340         else
1341         {
1342             const char *filename = m_options.file_name.c_str();
1343 
1344             bool check_inlines = false;
1345             SymbolContextList sc_list;
1346             size_t num_matches = 0;
1347 
1348             if (!m_options.modules.empty())
1349             {
1350                 ModuleList matching_modules;
1351                 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i)
1352                 {
1353                     FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1354                     if (module_file_spec)
1355                     {
1356                         ModuleSpec module_spec (module_file_spec);
1357                         matching_modules.Clear();
1358                         target->GetImages().FindModules (module_spec, matching_modules);
1359                         num_matches += matching_modules.ResolveSymbolContextForFilePath (filename,
1360                                                                                          0,
1361                                                                                          check_inlines,
1362                                                                                          eSymbolContextModule | eSymbolContextCompUnit,
1363                                                                                          sc_list);
1364                     }
1365                 }
1366             }
1367             else
1368             {
1369                 num_matches = target->GetImages().ResolveSymbolContextForFilePath (filename,
1370                                                                                    0,
1371                                                                                    check_inlines,
1372                                                                                    eSymbolContextModule | eSymbolContextCompUnit,
1373                                                                                    sc_list);
1374             }
1375 
1376             if (num_matches == 0)
1377             {
1378                 result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
1379                                              m_options.file_name.c_str());
1380                 result.SetStatus (eReturnStatusFailed);
1381                 return false;
1382             }
1383 
1384             if (num_matches > 1)
1385             {
1386                 bool got_multiple = false;
1387                 FileSpec *test_cu_spec = nullptr;
1388 
1389                 for (unsigned i = 0; i < num_matches; i++)
1390                 {
1391                     SymbolContext sc;
1392                     sc_list.GetContextAtIndex(i, sc);
1393                     if (sc.comp_unit)
1394                     {
1395                         if (test_cu_spec)
1396                         {
1397                             if (test_cu_spec != static_cast<FileSpec *> (sc.comp_unit))
1398                                 got_multiple = true;
1399                             break;
1400                         }
1401                         else
1402                             test_cu_spec = sc.comp_unit;
1403                     }
1404                 }
1405                 if (got_multiple)
1406                 {
1407                     result.AppendErrorWithFormat("Multiple source files found matching: \"%s.\"\n",
1408                                                  m_options.file_name.c_str());
1409                     result.SetStatus (eReturnStatusFailed);
1410                     return false;
1411                 }
1412             }
1413 
1414             SymbolContext sc;
1415             if (sc_list.GetContextAtIndex(0, sc))
1416             {
1417                 if (sc.comp_unit)
1418                 {
1419                     if (m_options.show_bp_locs)
1420                     {
1421                         const bool show_inlines = true;
1422                         m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
1423                         SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1424                         target_search_filter.Search (m_breakpoint_locations);
1425                     }
1426                     else
1427                         m_breakpoint_locations.Clear();
1428 
1429                     if (m_options.num_lines == 0)
1430                         m_options.num_lines = 10;
1431 
1432                     target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
1433                                                                                   m_options.start_line,
1434                                                                                   0,
1435                                                                                   m_options.num_lines,
1436                                                                                   "",
1437                                                                                   &result.GetOutputStream(),
1438                                                                                   GetBreakpointLocations ());
1439 
1440                     result.SetStatus (eReturnStatusSuccessFinishResult);
1441                 }
1442                 else
1443                 {
1444                     result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
1445                                                  m_options.file_name.c_str());
1446                     result.SetStatus (eReturnStatusFailed);
1447                     return false;
1448                 }
1449             }
1450         }
1451         return result.Succeeded();
1452     }
1453 
1454     const SymbolContextList *
1455     GetBreakpointLocations ()
1456     {
1457         if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
1458             return &m_breakpoint_locations.GetFileLineMatches();
1459         return nullptr;
1460     }
1461 
1462     CommandOptions m_options;
1463     FileLineResolver m_breakpoint_locations;
1464     std::string    m_reverse_name;
1465 };
1466 
1467 OptionDefinition
1468 CommandObjectSourceList::CommandOptions::g_option_table[] =
1469 {
1470 { LLDB_OPT_SET_ALL, false, "count",  'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount,   "The number of source lines to display."},
1471 { LLDB_OPT_SET_1  |
1472   LLDB_OPT_SET_2  , false, "shlib",  's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source file in the given shared library."},
1473 { 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."},
1474 { LLDB_OPT_SET_1  , false, "file",   'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,    "The file from which to display source."},
1475 { LLDB_OPT_SET_1  , false, "line",   'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum,    "The line number at which to start the display source."},
1476 { LLDB_OPT_SET_2  , false, "name",   'n', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSymbolCompletion, eArgTypeSymbol,    "The name of a function whose source to display."},
1477 { 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."},
1478 { 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."},
1479 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1480 };
1481 
1482 #pragma mark CommandObjectMultiwordSource
1483 //-------------------------------------------------------------------------
1484 // CommandObjectMultiwordSource
1485 //-------------------------------------------------------------------------
1486 
1487 CommandObjectMultiwordSource::CommandObjectMultiwordSource(CommandInterpreter &interpreter)
1488     : CommandObjectMultiword(
1489           interpreter, "source",
1490           "Commands for examining source code described by debug information for the current target process.",
1491           "source <subcommand> [<subcommand-options>]")
1492 {
1493     LoadSubCommand ("info",   CommandObjectSP (new CommandObjectSourceInfo (interpreter)));
1494     LoadSubCommand ("list",   CommandObjectSP (new CommandObjectSourceList (interpreter)));
1495 }
1496 
1497 CommandObjectMultiwordSource::~CommandObjectMultiwordSource() = default;
1498