1 //===-- CommandObjectSource.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommandObjectSource.h"
14 // Other libraries and framework 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"
36 using namespace lldb_private;
39 #pragma mark CommandObjectSourceInfo
40 //----------------------------------------------------------------------
41 // CommandObjectSourceInfo - debug line entries dumping command
42 //----------------------------------------------------------------------
44 class CommandObjectSourceInfo : public CommandObjectParsed
47 class CommandOptions : public Options
50 CommandOptions (CommandInterpreter &interpreter) : Options(interpreter) {}
52 ~CommandOptions () override {}
55 SetOptionValue (uint32_t option_idx, const char *option_arg) override
58 const int short_option = g_option_table[option_idx].short_option;
62 start_line = StringConvert::ToUInt32(option_arg, 0);
64 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
68 end_line = StringConvert::ToUInt32(option_arg, 0);
70 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
74 num_lines = StringConvert::ToUInt32(option_arg, 0);
76 error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg);
80 file_name = option_arg;
84 symbol_name = option_arg;
89 ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
90 address = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
94 modules.push_back(std::string(option_arg));
97 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
105 OptionParsingStarting () override
110 address = LLDB_INVALID_ADDRESS;
117 const OptionDefinition *
118 GetDefinitions () override
120 return g_option_table;
122 static OptionDefinition g_option_table[];
124 // Instance variables to hold the values for command options.
126 std::string file_name;
127 std::string symbol_name;
128 lldb::addr_t address;
132 STLStringArray modules;
136 CommandObjectSourceInfo (CommandInterpreter &interpreter)
137 : CommandObjectParsed(interpreter, "source info", "Display source line information (as specified) based "
138 "on the current executable's debug info.",
139 NULL, eCommandRequiresTarget),
140 m_options(interpreter)
144 ~CommandObjectSourceInfo () override {}
147 GetOptions () override
154 // Dump the line entries in each symbol context.
155 // Return the number of entries found.
156 // If module_list is set, only dump lines contained in one of the modules.
157 // If file_spec is set, only dump lines in the file.
158 // If the start_line option was specified, don't print lines less than start_line.
159 // If the end_line option was specified, don't print lines greater than end_line.
160 // If the num_lines option was specified, dont print more than num_lines entries.
162 DumpLinesInSymbolContexts (Stream &strm, const SymbolContextList &sc_list,
163 const ModuleList &module_list, const FileSpec &file_spec)
165 uint32_t start_line = m_options.start_line;
166 uint32_t end_line = m_options.end_line;
167 uint32_t num_lines = m_options.num_lines;
168 Target *target = m_exe_ctx.GetTargetPtr();
170 uint32_t num_matches = 0;
171 bool has_path = false;
174 assert(file_spec.GetFilename().AsCString());
175 has_path = (file_spec.GetDirectory().AsCString() != 0);
178 // Dump all the line entries for the file in the list.
179 ConstString last_module_file_name;
180 uint32_t num_scs = sc_list.GetSize();
181 for (uint32_t i = 0; i < num_scs; ++i)
184 sc_list.GetContextAtIndex(i, sc);
187 Module *module = sc.module_sp.get();
188 CompileUnit *cu = sc.comp_unit;
189 const LineEntry &line_entry = sc.line_entry;
190 assert(module && cu);
192 // Are we looking for specific modules, files or lines?
193 if (module_list.GetSize() && module_list.GetIndexForModule(module) == LLDB_INVALID_INDEX32)
195 if (file_spec && !lldb_private::FileSpec::Equal(file_spec, line_entry.file, has_path))
197 if (start_line > 0 && line_entry.line < start_line)
199 if (end_line > 0 && line_entry.line > end_line)
201 if (num_lines > 0 && num_matches > num_lines)
204 // Print a new header if the module changed.
205 const ConstString &module_file_name = module->GetFileSpec().GetFilename();
206 assert(module_file_name);
207 if (module_file_name != last_module_file_name)
211 strm << "Lines found in module `" << module_file_name << "\n";
213 // Dump the line entry.
214 line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu,
215 target, /*show_address_only=*/false);
217 last_module_file_name = module_file_name;
224 // Dump the requested line entries for the file in the compilation unit.
225 // Return the number of entries found.
226 // If module_list is set, only dump lines contained in one of the modules.
227 // If the start_line option was specified, don't print lines less than start_line.
228 // If the end_line option was specified, don't print lines greater than end_line.
229 // If the num_lines option was specified, dont print more than num_lines entries.
231 DumpFileLinesInCompUnit (Stream &strm, Module *module, CompileUnit *cu, const FileSpec &file_spec)
233 uint32_t start_line = m_options.start_line;
234 uint32_t end_line = m_options.end_line;
235 uint32_t num_lines = m_options.num_lines;
236 Target *target = m_exe_ctx.GetTargetPtr();
238 uint32_t num_matches = 0;
242 assert(file_spec.GetFilename().AsCString());
243 bool has_path = (file_spec.GetDirectory().AsCString() != 0);
244 const FileSpecList &cu_file_list = cu->GetSupportFiles();
245 size_t file_idx = cu_file_list.FindFileIndex(0, file_spec, has_path);
246 if (file_idx != UINT32_MAX)
248 // Update the file to how it appears in the CU.
249 const FileSpec &cu_file_spec = cu_file_list.GetFileSpecAtIndex(file_idx);
251 // Dump all matching lines at or above start_line for the file in the CU.
252 const ConstString &file_spec_name = file_spec.GetFilename();
253 const ConstString &module_file_name = module->GetFileSpec().GetFilename();
254 bool cu_header_printed = false;
255 uint32_t line = start_line;
258 LineEntry line_entry;
260 // Find the lowest index of a line entry with a line equal to
261 // or higher than 'line'.
262 uint32_t start_idx = 0;
263 start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec,
264 /*exact=*/false, &line_entry);
265 if (start_idx == UINT32_MAX)
266 // No more line entries for our file in this CU.
269 if (end_line > 0 && line_entry.line > end_line)
272 // Loop through to find any other entries for this line, dumping each.
273 line = line_entry.line;
277 if (num_lines > 0 && num_matches > num_lines)
279 assert(lldb_private::FileSpec::Equal(cu_file_spec, line_entry.file, has_path));
280 if (!cu_header_printed)
284 strm << "Lines found for file " << file_spec_name
285 << " in compilation unit " << cu->GetFilename()
286 << " in `" << module_file_name << "\n";
287 cu_header_printed = true;
289 line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu,
290 target, /*show_address_only=*/false);
293 // Anymore after this one?
295 start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec,
296 /*exact=*/true, &line_entry);
297 } while (start_idx != UINT32_MAX);
299 // Try the next higher line, starting over at start_idx 0.
307 // Dump the requested line entries for the file in the module.
308 // Return the number of entries found.
309 // If module_list is set, only dump lines contained in one of the modules.
310 // If the start_line option was specified, don't print lines less than start_line.
311 // If the end_line option was specified, don't print lines greater than end_line.
312 // If the num_lines option was specified, dont print more than num_lines entries.
314 DumpFileLinesInModule (Stream &strm, Module *module, const FileSpec &file_spec)
316 uint32_t num_matches = 0;
319 // Look through all the compilation units (CUs) in this module for ones that
320 // contain lines of code from this source file.
321 for (size_t i = 0; i < module->GetNumCompileUnits(); i++)
323 // Look for a matching source file in this CU.
324 CompUnitSP cu_sp(module->GetCompileUnitAtIndex(i));
327 num_matches += DumpFileLinesInCompUnit(strm, module, cu_sp.get(), file_spec);
334 // Given an address and a list of modules, append the symbol contexts of all line entries
335 // containing the address found in the modules and return the count of matches. If none
336 // is found, return an error in 'error_strm'.
338 GetSymbolContextsForAddress (const ModuleList &module_list, lldb::addr_t addr,
339 SymbolContextList &sc_list, StreamString &error_strm)
342 size_t num_matches = 0;
343 assert(module_list.GetSize() > 0);
344 Target *target = m_exe_ctx.GetTargetPtr();
345 if (target->GetSectionLoadList().IsEmpty())
347 // The target isn't loaded yet, we need to lookup the file address in
348 // all modules. Note: the module list option does not apply to addresses.
349 const size_t num_modules = module_list.GetSize();
350 for (size_t i = 0; i < num_modules; ++i)
352 ModuleSP module_sp(module_list.GetModuleAtIndex(i));
355 if (module_sp->ResolveFileAddress(addr, so_addr))
359 if (module_sp->ResolveSymbolContextForAddress(so_addr, eSymbolContextEverything, sc) &
360 eSymbolContextLineEntry)
362 sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false);
367 if (num_matches == 0)
368 error_strm.Printf("Source information for file address 0x%" PRIx64
369 " not found in any modules.\n", addr);
373 // The target has some things loaded, resolve this address to a
374 // compile unit + file + line and display
375 if (target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
377 ModuleSP module_sp(so_addr.GetModule());
378 // Check to make sure this module is in our list.
380 module_list.GetIndexForModule(module_sp.get()) != LLDB_INVALID_INDEX32)
384 if (module_sp->ResolveSymbolContextForAddress(so_addr, eSymbolContextEverything, sc) &
385 eSymbolContextLineEntry)
387 sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false);
392 StreamString addr_strm;
393 so_addr.Dump(&addr_strm, NULL, Address::DumpStyleModuleWithFileAddress);
394 error_strm.Printf("Address 0x%" PRIx64 " resolves to %s, but there is"
395 " no source information available for this address.\n",
396 addr, addr_strm.GetData());
401 StreamString addr_strm;
402 so_addr.Dump(&addr_strm, NULL, Address::DumpStyleModuleWithFileAddress);
403 error_strm.Printf("Address 0x%" PRIx64 " resolves to %s, but it cannot"
404 " be found in any modules.\n",
405 addr, addr_strm.GetData());
409 error_strm.Printf("Unable to resolve address 0x%" PRIx64 ".\n", addr);
414 // Dump the line entries found in functions matching the name specified in the option.
416 DumpLinesInFunctions (CommandReturnObject &result)
418 SymbolContextList sc_list_funcs;
419 ConstString name(m_options.symbol_name.c_str());
420 SymbolContextList sc_list_lines;
421 Target *target = m_exe_ctx.GetTargetPtr();
422 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
424 // Note: module_list can't be const& because FindFunctionSymbols isn't const.
425 ModuleList module_list = (m_module_list.GetSize() > 0) ?
426 m_module_list : target->GetImages();
427 size_t num_matches = module_list.FindFunctions(name,
428 eFunctionNameTypeAuto,
429 /*include_symbols=*/false,
430 /*include_inlines=*/true,
435 // If we didn't find any functions with that name, try searching for
436 // symbols that line up exactly with function addresses.
437 SymbolContextList sc_list_symbols;
438 size_t num_symbol_matches = module_list.FindFunctionSymbols(name,
439 eFunctionNameTypeAuto,
441 for (size_t i = 0; i < num_symbol_matches; i++)
444 sc_list_symbols.GetContextAtIndex(i, sc);
445 if (sc.symbol && sc.symbol->ValueIsAddress())
447 const Address &base_address = sc.symbol->GetAddressRef();
448 Function *function = base_address.CalculateSymbolContextFunction();
451 sc_list_funcs.Append(SymbolContext(function));
457 if (num_matches == 0)
459 result.AppendErrorWithFormat("Could not find function named \'%s\'.\n",
460 m_options.symbol_name.c_str());
463 for (size_t i = 0; i < num_matches; i++)
466 sc_list_funcs.GetContextAtIndex(i, sc);
467 bool context_found_for_symbol = false;
468 // Loop through all the ranges in the function.
471 sc.GetAddressRange(eSymbolContextEverything,
473 /*use_inline_block_range=*/true,
477 // Append the symbol contexts for each address in the range to sc_list_lines.
478 const Address &base_address = range.GetBaseAddress();
479 const addr_t size = range.GetByteSize();
480 lldb::addr_t start_addr = base_address.GetLoadAddress(target);
481 if (start_addr == LLDB_INVALID_ADDRESS)
482 start_addr = base_address.GetFileAddress();
483 lldb::addr_t end_addr = start_addr + size;
484 for (lldb::addr_t addr = start_addr; addr < end_addr; addr += addr_byte_size)
486 StreamString error_strm;
487 if (!GetSymbolContextsForAddress(module_list, addr, sc_list_lines, error_strm))
488 result.AppendWarningWithFormat("in symbol '%s': %s",
489 sc.GetFunctionName().AsCString(),
490 error_strm.GetData());
492 context_found_for_symbol = true;
495 if (!context_found_for_symbol)
496 result.AppendWarningWithFormat("Unable to find line information"
497 " for matching symbol '%s'.\n",
498 sc.GetFunctionName().AsCString());
500 if (sc_list_lines.GetSize() == 0)
502 result.AppendErrorWithFormat("No line information could be found"
503 " for any symbols matching '%s'.\n",
508 if (!DumpLinesInSymbolContexts(result.GetOutputStream(),
509 sc_list_lines, module_list, file_spec))
511 result.AppendErrorWithFormat("Unable to dump line information for symbol '%s'.\n",
518 // Dump the line entries found for the address specified in the option.
520 DumpLinesForAddress (CommandReturnObject &result)
522 Target *target = m_exe_ctx.GetTargetPtr();
523 SymbolContextList sc_list;
525 StreamString error_strm;
526 if (!GetSymbolContextsForAddress(target->GetImages(), m_options.address, sc_list, error_strm))
528 result.AppendErrorWithFormat("%s.\n", error_strm.GetData());
531 ModuleList module_list;
533 if (!DumpLinesInSymbolContexts(result.GetOutputStream(),
534 sc_list, module_list, file_spec))
536 result.AppendErrorWithFormat("No modules contain load address 0x%" PRIx64 ".\n",
543 // Dump the line entries found in the file specified in the option.
545 DumpLinesForFile (CommandReturnObject &result)
547 FileSpec file_spec(m_options.file_name, false);
548 const char *filename = m_options.file_name.c_str();
549 Target *target = m_exe_ctx.GetTargetPtr();
550 const ModuleList &module_list = (m_module_list.GetSize() > 0) ?
551 m_module_list : target->GetImages();
553 bool displayed_something = false;
554 const size_t num_modules = module_list.GetSize();
555 for (uint32_t i = 0; i < num_modules; ++i)
557 // Dump lines for this module.
558 Module *module = module_list.GetModulePointerAtIndex(i);
560 if (DumpFileLinesInModule(result.GetOutputStream(), module, file_spec))
561 displayed_something = true;
563 if (!displayed_something)
565 result.AppendErrorWithFormat("No source filenames matched '%s'.\n", filename);
571 // Dump the line entries for the current frame.
573 DumpLinesForFrame (CommandReturnObject &result)
575 StackFrame *cur_frame = m_exe_ctx.GetFramePtr();
576 if (cur_frame == NULL)
578 result.AppendError("No selected frame to use to find the default source.");
581 else if (!cur_frame->HasDebugInformation())
583 result.AppendError("No debug info for the selected frame.");
588 const SymbolContext &sc = cur_frame->GetSymbolContext(eSymbolContextLineEntry);
589 SymbolContextList sc_list;
591 ModuleList module_list;
593 if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, module_list, file_spec))
595 result.AppendError("No source line info available for the selected frame.");
603 DoExecute (Args &command, CommandReturnObject &result) override
605 const size_t argc = command.GetArgumentCount();
609 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n",
611 result.SetStatus(eReturnStatusFailed);
615 Target *target = m_exe_ctx.GetTargetPtr();
618 target = m_interpreter.GetDebugger().GetSelectedTarget().get();
621 result.AppendError("invalid target, create a debug target using the "
622 "'target create' command.");
623 result.SetStatus(eReturnStatusFailed);
628 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
629 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
630 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
632 // Collect the list of modules to search.
633 m_module_list.Clear();
634 if (m_options.modules.size() > 0)
636 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i)
638 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
639 if (module_file_spec)
641 ModuleSpec module_spec(module_file_spec);
642 if (target->GetImages().FindModules(module_spec, m_module_list) == 0)
643 result.AppendWarningWithFormat("No module found for '%s'.\n",
644 m_options.modules[i].c_str());
647 if (!m_module_list.GetSize())
649 result.AppendError("No modules match the input.");
650 result.SetStatus(eReturnStatusFailed);
654 else if (target->GetImages().GetSize() == 0)
656 result.AppendError("The target has no associated executable images.");
657 result.SetStatus(eReturnStatusFailed);
661 // Check the arguments to see what lines we should dump.
662 if (!m_options.symbol_name.empty())
664 // Print lines for symbol.
665 if (DumpLinesInFunctions(result))
666 result.SetStatus(eReturnStatusSuccessFinishResult);
668 result.SetStatus(eReturnStatusFailed);
670 else if (m_options.address != LLDB_INVALID_ADDRESS)
672 // Print lines for an address.
673 if (DumpLinesForAddress(result))
674 result.SetStatus(eReturnStatusSuccessFinishResult);
676 result.SetStatus(eReturnStatusFailed);
678 else if (!m_options.file_name.empty())
680 // Dump lines for a file.
681 if (DumpLinesForFile(result))
682 result.SetStatus(eReturnStatusSuccessFinishResult);
684 result.SetStatus(eReturnStatusFailed);
688 // Dump the line for the current frame.
689 if (DumpLinesForFrame(result))
690 result.SetStatus(eReturnStatusSuccessFinishResult);
692 result.SetStatus(eReturnStatusFailed);
694 return result.Succeeded();
697 CommandOptions m_options;
698 ModuleList m_module_list;
701 OptionDefinition CommandObjectSourceInfo::CommandOptions::g_option_table[] = {
702 {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeCount,
703 "The number of line entries to display."},
704 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "shlib", 's', OptionParser::eRequiredArgument, NULL, NULL,
705 CommandCompletions::eModuleCompletion, eArgTypeShlibName,
706 "Look up the source in the given module or shared library (can be "
707 "specified more than once)."},
708 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL,
709 CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
710 {LLDB_OPT_SET_1, false, "line", 'l', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeLineNum,
711 "The line number at which to start the displaying lines."},
712 {LLDB_OPT_SET_1, false, "end-line", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeLineNum,
713 "The line number at which to stop displaying lines."},
714 {LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, NULL, NULL,
715 CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."},
716 {LLDB_OPT_SET_3, false, "address", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeAddressOrExpression,
717 "Lookup the address and display the source information for the "
718 "corresponding file and line."},
719 {0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL}
723 #pragma mark CommandObjectSourceList
724 //-------------------------------------------------------------------------
725 // CommandObjectSourceList
726 //-------------------------------------------------------------------------
728 class CommandObjectSourceList : public CommandObjectParsed
731 class CommandOptions : public Options
734 CommandOptions (CommandInterpreter &interpreter) :
739 ~CommandOptions () override
744 SetOptionValue (uint32_t option_idx, const char *option_arg) override
747 const int short_option = g_option_table[option_idx].short_option;
748 switch (short_option)
751 start_line = StringConvert::ToUInt32 (option_arg, 0);
753 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
757 num_lines = StringConvert::ToUInt32 (option_arg, 0);
759 error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg);
763 file_name = option_arg;
767 symbol_name = option_arg;
772 ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
773 address = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
777 modules.push_back (std::string (option_arg));
787 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
795 OptionParsingStarting () override
800 address = LLDB_INVALID_ADDRESS;
803 show_bp_locs = false;
808 const OptionDefinition*
809 GetDefinitions () override
811 return g_option_table;
813 static OptionDefinition g_option_table[];
815 // Instance variables to hold the values for command options.
817 std::string file_name;
818 std::string symbol_name;
819 lldb::addr_t address;
822 STLStringArray modules;
828 CommandObjectSourceList(CommandInterpreter &interpreter) :
829 CommandObjectParsed (interpreter,
831 "Display source code (as specified) based on the current executable's debug info.",
833 eCommandRequiresTarget),
834 m_options (interpreter)
838 ~CommandObjectSourceList () override
844 GetOptions () override
850 GetRepeatCommand (Args ¤t_command_args, uint32_t index) override
852 // This is kind of gross, but the command hasn't been parsed yet so we can't look at the option
853 // values for this invocation... I have to scan the arguments directly.
854 size_t num_args = current_command_args.GetArgumentCount();
855 bool is_reverse = false;
856 for (size_t i = 0 ; i < num_args; i++)
858 const char *arg = current_command_args.GetArgumentAtIndex(i);
859 if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0))
866 if (m_reverse_name.empty())
868 m_reverse_name = m_cmd_name;
869 m_reverse_name.append (" -r");
871 return m_reverse_name.c_str();
874 return m_cmd_name.c_str();
881 ConstString function;
882 LineEntry line_entry;
884 SourceInfo (const ConstString &name, const LineEntry &line_entry) :
886 line_entry(line_entry)
899 return (bool)function && line_entry.IsValid();
903 operator == (const SourceInfo &rhs) const
905 return function == rhs.function &&
906 line_entry.file == rhs.line_entry.file &&
907 line_entry.line == rhs.line_entry.line;
911 operator != (const SourceInfo &rhs) const
913 return function != rhs.function ||
914 line_entry.file != rhs.line_entry.file ||
915 line_entry.line != rhs.line_entry.line;
919 operator < (const SourceInfo &rhs) const
921 if (function.GetCString() < rhs.function.GetCString())
923 if (line_entry.file.GetDirectory().GetCString() < rhs.line_entry.file.GetDirectory().GetCString())
925 if (line_entry.file.GetFilename().GetCString() < rhs.line_entry.file.GetFilename().GetCString())
927 if (line_entry.line < rhs.line_entry.line)
934 DisplayFunctionSource (const SymbolContext &sc,
935 SourceInfo &source_info,
936 CommandReturnObject &result)
938 if (!source_info.IsValid())
940 source_info.function = sc.GetFunctionName();
941 source_info.line_entry = sc.GetFunctionStartLineEntry();
946 Target *target = m_exe_ctx.GetTargetPtr();
953 if (sc.block == NULL)
955 // Not an inlined function
956 sc.function->GetStartLineSourceInfo (start_file, start_line);
959 result.AppendErrorWithFormat("Could not find line information for start of function: \"%s\".\n", source_info.function.GetCString());
960 result.SetStatus (eReturnStatusFailed);
963 sc.function->GetEndLineSourceInfo (end_file, end_line);
967 // We have an inlined function
968 start_file = source_info.line_entry.file;
969 start_line = source_info.line_entry.line;
970 end_line = start_line + m_options.num_lines;
973 // This is a little hacky, but the first line table entry for a function points to the "{" that
974 // starts the function block. It would be nice to actually get the function
975 // declaration in there too. So back up a bit, but not further than what you're going to display.
976 uint32_t extra_lines;
977 if (m_options.num_lines >= 10)
980 extra_lines = m_options.num_lines/2;
982 if (start_line <= extra_lines)
985 line_no = start_line - extra_lines;
987 // For fun, if the function is shorter than the number of lines we're supposed to display,
988 // only display the function...
991 if (m_options.num_lines > end_line - line_no)
992 m_options.num_lines = end_line - line_no + extra_lines;
995 m_breakpoint_locations.Clear();
997 if (m_options.show_bp_locs)
999 const bool show_inlines = true;
1000 m_breakpoint_locations.Reset (start_file, 0, show_inlines);
1001 SearchFilterForUnconstrainedSearches target_search_filter (m_exe_ctx.GetTargetSP());
1002 target_search_filter.Search (m_breakpoint_locations);
1005 result.AppendMessageWithFormat("File: %s\n", start_file.GetPath().c_str());
1006 return target->GetSourceManager().DisplaySourceLinesWithLineNumbers (start_file,
1009 m_options.num_lines,
1011 &result.GetOutputStream(),
1012 GetBreakpointLocations ());
1016 result.AppendErrorWithFormat("Could not find function info for: \"%s\".\n", m_options.symbol_name.c_str());
1021 // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions
1022 // "take a possibly empty vector of strings which are names of modules, and
1023 // run the two search functions on the subset of the full module list that
1024 // matches the strings in the input vector". If we wanted to put these somewhere,
1025 // there should probably be a module-filter-list that can be passed to the
1026 // various ModuleList::Find* calls, which would either be a vector of string
1027 // names or a ModuleSpecList.
1028 size_t FindMatchingFunctions (Target *target, const ConstString &name, SymbolContextList& sc_list)
1030 // Displaying the source for a symbol:
1031 bool include_inlines = true;
1033 bool include_symbols = false;
1034 size_t num_matches = 0;
1036 if (m_options.num_lines == 0)
1037 m_options.num_lines = 10;
1039 const size_t num_modules = m_options.modules.size();
1040 if (num_modules > 0)
1042 ModuleList matching_modules;
1043 for (size_t i = 0; i < num_modules; ++i)
1045 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1046 if (module_file_spec)
1048 ModuleSpec module_spec (module_file_spec);
1049 matching_modules.Clear();
1050 target->GetImages().FindModules (module_spec, matching_modules);
1051 num_matches += matching_modules.FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
1057 num_matches = target->GetImages().FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
1062 size_t FindMatchingFunctionSymbols (Target *target, const ConstString &name, SymbolContextList& sc_list)
1064 size_t num_matches = 0;
1065 const size_t num_modules = m_options.modules.size();
1066 if (num_modules > 0)
1068 ModuleList matching_modules;
1069 for (size_t i = 0; i < num_modules; ++i)
1071 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1072 if (module_file_spec)
1074 ModuleSpec module_spec (module_file_spec);
1075 matching_modules.Clear();
1076 target->GetImages().FindModules (module_spec, matching_modules);
1077 num_matches += matching_modules.FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
1083 num_matches = target->GetImages().FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
1089 DoExecute (Args& command, CommandReturnObject &result) override
1091 const size_t argc = command.GetArgumentCount();
1095 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", GetCommandName());
1096 result.SetStatus (eReturnStatusFailed);
1100 Target *target = m_exe_ctx.GetTargetPtr();
1102 if (!m_options.symbol_name.empty())
1104 SymbolContextList sc_list;
1105 ConstString name(m_options.symbol_name.c_str());
1107 // Displaying the source for a symbol. Search for function named name.
1108 size_t num_matches = FindMatchingFunctions (target, name, sc_list);
1111 // If we didn't find any functions with that name, try searching for symbols
1112 // that line up exactly with function addresses.
1113 SymbolContextList sc_list_symbols;
1114 size_t num_symbol_matches = FindMatchingFunctionSymbols (target, name, sc_list_symbols);
1115 for (size_t i = 0; i < num_symbol_matches; i++)
1118 sc_list_symbols.GetContextAtIndex (i, sc);
1119 if (sc.symbol && sc.symbol->ValueIsAddress())
1121 const Address &base_address = sc.symbol->GetAddressRef();
1122 Function *function = base_address.CalculateSymbolContextFunction();
1125 sc_list.Append (SymbolContext(function));
1133 if (num_matches == 0)
1135 result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", m_options.symbol_name.c_str());
1136 result.SetStatus (eReturnStatusFailed);
1140 if (num_matches > 1)
1142 std::set<SourceInfo> source_match_set;
1144 bool displayed_something = false;
1145 for (size_t i = 0; i < num_matches; i++)
1148 sc_list.GetContextAtIndex (i, sc);
1149 SourceInfo source_info (sc.GetFunctionName(),
1150 sc.GetFunctionStartLineEntry());
1152 if (source_info.IsValid())
1154 if (source_match_set.find(source_info) == source_match_set.end())
1156 source_match_set.insert(source_info);
1157 if (DisplayFunctionSource (sc, source_info, result))
1158 displayed_something = true;
1163 if (displayed_something)
1164 result.SetStatus (eReturnStatusSuccessFinishResult);
1166 result.SetStatus (eReturnStatusFailed);
1171 sc_list.GetContextAtIndex (0, sc);
1172 SourceInfo source_info;
1174 if (DisplayFunctionSource (sc, source_info, result))
1176 result.SetStatus (eReturnStatusSuccessFinishResult);
1180 result.SetStatus (eReturnStatusFailed);
1183 return result.Succeeded();
1185 else if (m_options.address != LLDB_INVALID_ADDRESS)
1188 StreamString error_strm;
1189 SymbolContextList sc_list;
1191 if (target->GetSectionLoadList().IsEmpty())
1193 // The target isn't loaded yet, we need to lookup the file address
1195 const ModuleList &module_list = target->GetImages();
1196 const size_t num_modules = module_list.GetSize();
1197 for (size_t i=0; i<num_modules; ++i)
1199 ModuleSP module_sp (module_list.GetModuleAtIndex(i));
1200 if (module_sp && module_sp->ResolveFileAddress(m_options.address, so_addr))
1204 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
1209 if (sc_list.GetSize() == 0)
1211 result.AppendErrorWithFormat("no modules have source information for file address 0x%" PRIx64 ".\n",
1213 result.SetStatus (eReturnStatusFailed);
1219 // The target has some things loaded, resolve this address to a
1220 // compile unit + file + line and display
1221 if (target->GetSectionLoadList().ResolveLoadAddress (m_options.address, so_addr))
1223 ModuleSP module_sp (so_addr.GetModule());
1228 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
1234 so_addr.Dump(&error_strm, NULL, Address::DumpStyleModuleWithFileAddress);
1235 result.AppendErrorWithFormat("address resolves to %s, but there is no line table information available for this address.\n",
1236 error_strm.GetData());
1237 result.SetStatus (eReturnStatusFailed);
1243 if (sc_list.GetSize() == 0)
1245 result.AppendErrorWithFormat("no modules contain load address 0x%" PRIx64 ".\n", m_options.address);
1246 result.SetStatus (eReturnStatusFailed);
1250 uint32_t num_matches = sc_list.GetSize();
1251 for (uint32_t i=0; i<num_matches; ++i)
1254 sc_list.GetContextAtIndex(i, sc);
1257 if (m_options.show_bp_locs)
1259 m_breakpoint_locations.Clear();
1260 const bool show_inlines = true;
1261 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
1262 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1263 target_search_filter.Search (m_breakpoint_locations);
1266 bool show_fullpaths = true;
1267 bool show_module = true;
1268 bool show_inlined_frames = true;
1269 const bool show_function_arguments = true;
1270 const bool show_function_name = true;
1271 sc.DumpStopContext(&result.GetOutputStream(),
1272 m_exe_ctx.GetBestExecutionContextScope(),
1273 sc.line_entry.range.GetBaseAddress(),
1276 show_inlined_frames,
1277 show_function_arguments,
1278 show_function_name);
1279 result.GetOutputStream().EOL();
1281 if (m_options.num_lines == 0)
1282 m_options.num_lines = 10;
1284 size_t lines_to_back_up = m_options.num_lines >= 10 ? 5 : m_options.num_lines/2;
1286 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
1289 m_options.num_lines - lines_to_back_up,
1291 &result.GetOutputStream(),
1292 GetBreakpointLocations ());
1293 result.SetStatus (eReturnStatusSuccessFinishResult);
1297 else if (m_options.file_name.empty())
1299 // Last valid source manager context, or the current frame if no
1300 // valid last context in source manager.
1301 // One little trick here, if you type the exact same list command twice in a row, it is
1302 // more likely because you typed it once, then typed it again
1303 if (m_options.start_line == 0)
1305 if (target->GetSourceManager().DisplayMoreWithLineNumbers (&result.GetOutputStream(),
1306 m_options.num_lines,
1308 GetBreakpointLocations ()))
1310 result.SetStatus (eReturnStatusSuccessFinishResult);
1315 if (m_options.num_lines == 0)
1316 m_options.num_lines = 10;
1318 if (m_options.show_bp_locs)
1320 SourceManager::FileSP last_file_sp (target->GetSourceManager().GetLastFile ());
1323 const bool show_inlines = true;
1324 m_breakpoint_locations.Reset (last_file_sp->GetFileSpec(), 0, show_inlines);
1325 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1326 target_search_filter.Search (m_breakpoint_locations);
1330 m_breakpoint_locations.Clear();
1332 if (target->GetSourceManager().DisplaySourceLinesWithLineNumbersUsingLastFile(
1333 m_options.start_line, // Line to display
1334 m_options.num_lines, // Lines after line to
1335 UINT32_MAX, // Don't mark "line"
1336 "", // Don't mark "line"
1337 &result.GetOutputStream(),
1338 GetBreakpointLocations ()))
1340 result.SetStatus (eReturnStatusSuccessFinishResult);
1347 const char *filename = m_options.file_name.c_str();
1349 bool check_inlines = false;
1350 SymbolContextList sc_list;
1351 size_t num_matches = 0;
1353 if (m_options.modules.size() > 0)
1355 ModuleList matching_modules;
1356 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i)
1358 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
1359 if (module_file_spec)
1361 ModuleSpec module_spec (module_file_spec);
1362 matching_modules.Clear();
1363 target->GetImages().FindModules (module_spec, matching_modules);
1364 num_matches += matching_modules.ResolveSymbolContextForFilePath (filename,
1367 eSymbolContextModule | eSymbolContextCompUnit,
1374 num_matches = target->GetImages().ResolveSymbolContextForFilePath (filename,
1377 eSymbolContextModule | eSymbolContextCompUnit,
1381 if (num_matches == 0)
1383 result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
1384 m_options.file_name.c_str());
1385 result.SetStatus (eReturnStatusFailed);
1389 if (num_matches > 1)
1391 bool got_multiple = false;
1392 FileSpec *test_cu_spec = NULL;
1394 for (unsigned i = 0; i < num_matches; i++)
1397 sc_list.GetContextAtIndex(i, sc);
1402 if (test_cu_spec != static_cast<FileSpec *> (sc.comp_unit))
1403 got_multiple = true;
1407 test_cu_spec = sc.comp_unit;
1412 result.AppendErrorWithFormat("Multiple source files found matching: \"%s.\"\n",
1413 m_options.file_name.c_str());
1414 result.SetStatus (eReturnStatusFailed);
1420 if (sc_list.GetContextAtIndex(0, sc))
1424 if (m_options.show_bp_locs)
1426 const bool show_inlines = true;
1427 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
1428 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
1429 target_search_filter.Search (m_breakpoint_locations);
1432 m_breakpoint_locations.Clear();
1434 if (m_options.num_lines == 0)
1435 m_options.num_lines = 10;
1437 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
1438 m_options.start_line,
1440 m_options.num_lines,
1442 &result.GetOutputStream(),
1443 GetBreakpointLocations ());
1445 result.SetStatus (eReturnStatusSuccessFinishResult);
1449 result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
1450 m_options.file_name.c_str());
1451 result.SetStatus (eReturnStatusFailed);
1456 return result.Succeeded();
1459 const SymbolContextList *
1460 GetBreakpointLocations ()
1462 if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
1463 return &m_breakpoint_locations.GetFileLineMatches();
1466 CommandOptions m_options;
1467 FileLineResolver m_breakpoint_locations;
1468 std::string m_reverse_name;
1473 CommandObjectSourceList::CommandOptions::g_option_table[] =
1475 { LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeCount, "The number of source lines to display."},
1477 LLDB_OPT_SET_2 , false, "shlib", 's', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source file in the given shared library."},
1478 { LLDB_OPT_SET_ALL, false, "show-breakpoints", 'b', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Show the line table locations from the debug information that indicate valid places to set source level breakpoints."},
1479 { LLDB_OPT_SET_1 , false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
1480 { LLDB_OPT_SET_1 , false, "line", 'l', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeLineNum, "The line number at which to start the display source."},
1481 { LLDB_OPT_SET_2 , false, "name", 'n', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."},
1482 { LLDB_OPT_SET_3 , false, "address",'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeAddressOrExpression, "Lookup the address and display the source information for the corresponding file and line."},
1483 { LLDB_OPT_SET_4, false, "reverse", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Reverse the listing to look backwards from the last displayed block of source."},
1484 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
1487 #pragma mark CommandObjectMultiwordSource
1488 //-------------------------------------------------------------------------
1489 // CommandObjectMultiwordSource
1490 //-------------------------------------------------------------------------
1492 CommandObjectMultiwordSource::CommandObjectMultiwordSource (CommandInterpreter &interpreter) :
1493 CommandObjectMultiword (interpreter,
1495 "A set of commands for accessing source file information",
1496 "source <subcommand> [<subcommand-options>]")
1498 LoadSubCommand ("info", CommandObjectSP (new CommandObjectSourceInfo (interpreter)));
1499 LoadSubCommand ("list", CommandObjectSP (new CommandObjectSourceList (interpreter)));
1502 CommandObjectMultiwordSource::~CommandObjectMultiwordSource ()