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/TargetList.h"
31 #include "lldb/Interpreter/CommandCompletions.h"
32 #include "lldb/Interpreter/Options.h"
35 using namespace lldb_private;
37 //-------------------------------------------------------------------------
38 // CommandObjectSourceInfo
39 //-------------------------------------------------------------------------
41 class CommandObjectSourceInfo : public CommandObjectParsed
44 class CommandOptions : public Options
47 CommandOptions (CommandInterpreter &interpreter) :
57 SetOptionValue (uint32_t option_idx, const char *option_arg)
60 const int short_option = g_option_table[option_idx].short_option;
64 start_line = StringConvert::ToUInt32 (option_arg, 0);
66 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
70 file_name = option_arg;
74 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
82 OptionParsingStarting ()
89 const OptionDefinition*
92 return g_option_table;
94 static OptionDefinition g_option_table[];
96 // Instance variables to hold the values for command options.
98 std::string file_name;
104 CommandObjectSourceInfo(CommandInterpreter &interpreter) :
105 CommandObjectParsed (interpreter,
107 "Display information about the source lines from the current executable's debug info.",
108 "source info [<cmd-options>]"),
109 m_options (interpreter)
113 ~CommandObjectSourceInfo ()
126 DoExecute (Args& command, CommandReturnObject &result)
128 result.AppendError ("Not yet implemented");
129 result.SetStatus (eReturnStatusFailed);
133 CommandOptions m_options;
137 CommandObjectSourceInfo::CommandOptions::g_option_table[] =
139 { LLDB_OPT_SET_1, false, "line", 'l', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeLineNum, "The line number at which to start the display source."},
140 { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
141 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
144 #pragma mark CommandObjectSourceList
145 //-------------------------------------------------------------------------
146 // CommandObjectSourceList
147 //-------------------------------------------------------------------------
149 class CommandObjectSourceList : public CommandObjectParsed
152 class CommandOptions : public Options
155 CommandOptions (CommandInterpreter &interpreter) :
165 SetOptionValue (uint32_t option_idx, const char *option_arg)
168 const int short_option = g_option_table[option_idx].short_option;
169 switch (short_option)
172 start_line = StringConvert::ToUInt32 (option_arg, 0);
174 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
178 num_lines = StringConvert::ToUInt32 (option_arg, 0);
180 error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg);
184 file_name = option_arg;
188 symbol_name = option_arg;
193 ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
194 address = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
198 modules.push_back (std::string (option_arg));
208 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
216 OptionParsingStarting ()
221 address = LLDB_INVALID_ADDRESS;
224 show_bp_locs = false;
229 const OptionDefinition*
232 return g_option_table;
234 static OptionDefinition g_option_table[];
236 // Instance variables to hold the values for command options.
238 std::string file_name;
239 std::string symbol_name;
240 lldb::addr_t address;
243 STLStringArray modules;
249 CommandObjectSourceList(CommandInterpreter &interpreter) :
250 CommandObjectParsed (interpreter,
252 "Display source code (as specified) based on the current executable's debug info.",
254 eCommandRequiresTarget),
255 m_options (interpreter)
259 ~CommandObjectSourceList ()
271 GetRepeatCommand (Args ¤t_command_args, uint32_t index)
273 // This is kind of gross, but the command hasn't been parsed yet so we can't look at the option
274 // values for this invocation... I have to scan the arguments directly.
275 size_t num_args = current_command_args.GetArgumentCount();
276 bool is_reverse = false;
277 for (size_t i = 0 ; i < num_args; i++)
279 const char *arg = current_command_args.GetArgumentAtIndex(i);
280 if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0))
287 if (m_reverse_name.empty())
289 m_reverse_name = m_cmd_name;
290 m_reverse_name.append (" -r");
292 return m_reverse_name.c_str();
295 return m_cmd_name.c_str();
302 ConstString function;
303 LineEntry line_entry;
305 SourceInfo (const ConstString &name, const LineEntry &line_entry) :
307 line_entry(line_entry)
320 return (bool)function && line_entry.IsValid();
324 operator == (const SourceInfo &rhs) const
326 return function == rhs.function &&
327 line_entry.file == rhs.line_entry.file &&
328 line_entry.line == rhs.line_entry.line;
332 operator != (const SourceInfo &rhs) const
334 return function != rhs.function ||
335 line_entry.file != rhs.line_entry.file ||
336 line_entry.line != rhs.line_entry.line;
340 operator < (const SourceInfo &rhs) const
342 if (function.GetCString() < rhs.function.GetCString())
344 if (line_entry.file.GetDirectory().GetCString() < rhs.line_entry.file.GetDirectory().GetCString())
346 if (line_entry.file.GetFilename().GetCString() < rhs.line_entry.file.GetFilename().GetCString())
348 if (line_entry.line < rhs.line_entry.line)
355 DisplayFunctionSource (const SymbolContext &sc,
356 SourceInfo &source_info,
357 CommandReturnObject &result)
359 if (!source_info.IsValid())
361 source_info.function = sc.GetFunctionName();
362 source_info.line_entry = sc.GetFunctionStartLineEntry();
367 Target *target = m_exe_ctx.GetTargetPtr();
374 if (sc.block == NULL)
376 // Not an inlined function
377 sc.function->GetStartLineSourceInfo (start_file, start_line);
380 result.AppendErrorWithFormat("Could not find line information for start of function: \"%s\".\n", source_info.function.GetCString());
381 result.SetStatus (eReturnStatusFailed);
384 sc.function->GetEndLineSourceInfo (end_file, end_line);
388 // We have an inlined function
389 start_file = source_info.line_entry.file;
390 start_line = source_info.line_entry.line;
391 end_line = start_line + m_options.num_lines;
394 // This is a little hacky, but the first line table entry for a function points to the "{" that
395 // starts the function block. It would be nice to actually get the function
396 // declaration in there too. So back up a bit, but not further than what you're going to display.
397 uint32_t extra_lines;
398 if (m_options.num_lines >= 10)
401 extra_lines = m_options.num_lines/2;
403 if (start_line <= extra_lines)
406 line_no = start_line - extra_lines;
408 // For fun, if the function is shorter than the number of lines we're supposed to display,
409 // only display the function...
412 if (m_options.num_lines > end_line - line_no)
413 m_options.num_lines = end_line - line_no + extra_lines;
416 m_breakpoint_locations.Clear();
418 if (m_options.show_bp_locs)
420 const bool show_inlines = true;
421 m_breakpoint_locations.Reset (start_file, 0, show_inlines);
422 SearchFilterForUnconstrainedSearches target_search_filter (m_exe_ctx.GetTargetSP());
423 target_search_filter.Search (m_breakpoint_locations);
426 result.AppendMessageWithFormat("File: %s\n", start_file.GetPath().c_str());
427 return target->GetSourceManager().DisplaySourceLinesWithLineNumbers (start_file,
432 &result.GetOutputStream(),
433 GetBreakpointLocations ());
437 result.AppendErrorWithFormat("Could not find function info for: \"%s\".\n", m_options.symbol_name.c_str());
442 // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions
443 // "take a possibly empty vector of strings which are names of modules, and
444 // run the two search functions on the subset of the full module list that
445 // matches the strings in the input vector". If we wanted to put these somewhere,
446 // there should probably be a module-filter-list that can be passed to the
447 // various ModuleList::Find* calls, which would either be a vector of string
448 // names or a ModuleSpecList.
449 size_t FindMatchingFunctions (Target *target, const ConstString &name, SymbolContextList& sc_list)
451 // Displaying the source for a symbol:
452 bool include_inlines = true;
454 bool include_symbols = false;
455 size_t num_matches = 0;
457 if (m_options.num_lines == 0)
458 m_options.num_lines = 10;
460 const size_t num_modules = m_options.modules.size();
463 ModuleList matching_modules;
464 for (size_t i = 0; i < num_modules; ++i)
466 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
467 if (module_file_spec)
469 ModuleSpec module_spec (module_file_spec);
470 matching_modules.Clear();
471 target->GetImages().FindModules (module_spec, matching_modules);
472 num_matches += matching_modules.FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
478 num_matches = target->GetImages().FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
483 size_t FindMatchingFunctionSymbols (Target *target, const ConstString &name, SymbolContextList& sc_list)
485 size_t num_matches = 0;
486 const size_t num_modules = m_options.modules.size();
489 ModuleList matching_modules;
490 for (size_t i = 0; i < num_modules; ++i)
492 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
493 if (module_file_spec)
495 ModuleSpec module_spec (module_file_spec);
496 matching_modules.Clear();
497 target->GetImages().FindModules (module_spec, matching_modules);
498 num_matches += matching_modules.FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
504 num_matches = target->GetImages().FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
510 DoExecute (Args& command, CommandReturnObject &result)
512 const size_t argc = command.GetArgumentCount();
516 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", GetCommandName());
517 result.SetStatus (eReturnStatusFailed);
521 Target *target = m_exe_ctx.GetTargetPtr();
523 if (!m_options.symbol_name.empty())
525 SymbolContextList sc_list;
526 ConstString name(m_options.symbol_name.c_str());
528 // Displaying the source for a symbol. Search for function named name.
529 size_t num_matches = FindMatchingFunctions (target, name, sc_list);
532 // If we didn't find any functions with that name, try searching for symbols
533 // that line up exactly with function addresses.
534 SymbolContextList sc_list_symbols;
535 size_t num_symbol_matches = FindMatchingFunctionSymbols (target, name, sc_list_symbols);
536 for (size_t i = 0; i < num_symbol_matches; i++)
539 sc_list_symbols.GetContextAtIndex (i, sc);
540 if (sc.symbol && sc.symbol->ValueIsAddress())
542 const Address &base_address = sc.symbol->GetAddressRef();
543 Function *function = base_address.CalculateSymbolContextFunction();
546 sc_list.Append (SymbolContext(function));
554 if (num_matches == 0)
556 result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", m_options.symbol_name.c_str());
557 result.SetStatus (eReturnStatusFailed);
563 std::set<SourceInfo> source_match_set;
565 bool displayed_something = false;
566 for (size_t i = 0; i < num_matches; i++)
569 sc_list.GetContextAtIndex (i, sc);
570 SourceInfo source_info (sc.GetFunctionName(),
571 sc.GetFunctionStartLineEntry());
573 if (source_info.IsValid())
575 if (source_match_set.find(source_info) == source_match_set.end())
577 source_match_set.insert(source_info);
578 if (DisplayFunctionSource (sc, source_info, result))
579 displayed_something = true;
584 if (displayed_something)
585 result.SetStatus (eReturnStatusSuccessFinishResult);
587 result.SetStatus (eReturnStatusFailed);
592 sc_list.GetContextAtIndex (0, sc);
593 SourceInfo source_info;
595 if (DisplayFunctionSource (sc, source_info, result))
597 result.SetStatus (eReturnStatusSuccessFinishResult);
601 result.SetStatus (eReturnStatusFailed);
604 return result.Succeeded();
606 else if (m_options.address != LLDB_INVALID_ADDRESS)
609 StreamString error_strm;
610 SymbolContextList sc_list;
612 if (target->GetSectionLoadList().IsEmpty())
614 // The target isn't loaded yet, we need to lookup the file address
616 const ModuleList &module_list = target->GetImages();
617 const size_t num_modules = module_list.GetSize();
618 for (size_t i=0; i<num_modules; ++i)
620 ModuleSP module_sp (module_list.GetModuleAtIndex(i));
621 if (module_sp && module_sp->ResolveFileAddress(m_options.address, so_addr))
625 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
630 if (sc_list.GetSize() == 0)
632 result.AppendErrorWithFormat("no modules have source information for file address 0x%" PRIx64 ".\n",
634 result.SetStatus (eReturnStatusFailed);
640 // The target has some things loaded, resolve this address to a
641 // compile unit + file + line and display
642 if (target->GetSectionLoadList().ResolveLoadAddress (m_options.address, so_addr))
644 ModuleSP module_sp (so_addr.GetModule());
649 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
655 so_addr.Dump(&error_strm, NULL, Address::DumpStyleModuleWithFileAddress);
656 result.AppendErrorWithFormat("address resolves to %s, but there is no line table information available for this address.\n",
657 error_strm.GetData());
658 result.SetStatus (eReturnStatusFailed);
664 if (sc_list.GetSize() == 0)
666 result.AppendErrorWithFormat("no modules contain load address 0x%" PRIx64 ".\n", m_options.address);
667 result.SetStatus (eReturnStatusFailed);
671 uint32_t num_matches = sc_list.GetSize();
672 for (uint32_t i=0; i<num_matches; ++i)
675 sc_list.GetContextAtIndex(i, sc);
678 if (m_options.show_bp_locs)
680 m_breakpoint_locations.Clear();
681 const bool show_inlines = true;
682 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
683 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
684 target_search_filter.Search (m_breakpoint_locations);
687 bool show_fullpaths = true;
688 bool show_module = true;
689 bool show_inlined_frames = true;
690 const bool show_function_arguments = true;
691 const bool show_function_name = true;
692 sc.DumpStopContext(&result.GetOutputStream(),
693 m_exe_ctx.GetBestExecutionContextScope(),
694 sc.line_entry.range.GetBaseAddress(),
698 show_function_arguments,
700 result.GetOutputStream().EOL();
702 if (m_options.num_lines == 0)
703 m_options.num_lines = 10;
705 size_t lines_to_back_up = m_options.num_lines >= 10 ? 5 : m_options.num_lines/2;
707 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
710 m_options.num_lines - lines_to_back_up,
712 &result.GetOutputStream(),
713 GetBreakpointLocations ());
714 result.SetStatus (eReturnStatusSuccessFinishResult);
718 else if (m_options.file_name.empty())
720 // Last valid source manager context, or the current frame if no
721 // valid last context in source manager.
722 // One little trick here, if you type the exact same list command twice in a row, it is
723 // more likely because you typed it once, then typed it again
724 if (m_options.start_line == 0)
726 if (target->GetSourceManager().DisplayMoreWithLineNumbers (&result.GetOutputStream(),
729 GetBreakpointLocations ()))
731 result.SetStatus (eReturnStatusSuccessFinishResult);
736 if (m_options.num_lines == 0)
737 m_options.num_lines = 10;
739 if (m_options.show_bp_locs)
741 SourceManager::FileSP last_file_sp (target->GetSourceManager().GetLastFile ());
744 const bool show_inlines = true;
745 m_breakpoint_locations.Reset (last_file_sp->GetFileSpec(), 0, show_inlines);
746 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
747 target_search_filter.Search (m_breakpoint_locations);
751 m_breakpoint_locations.Clear();
753 if (target->GetSourceManager().DisplaySourceLinesWithLineNumbersUsingLastFile(
754 m_options.start_line, // Line to display
755 m_options.num_lines, // Lines after line to
756 UINT32_MAX, // Don't mark "line"
757 "", // Don't mark "line"
758 &result.GetOutputStream(),
759 GetBreakpointLocations ()))
761 result.SetStatus (eReturnStatusSuccessFinishResult);
768 const char *filename = m_options.file_name.c_str();
770 bool check_inlines = false;
771 SymbolContextList sc_list;
772 size_t num_matches = 0;
774 if (m_options.modules.size() > 0)
776 ModuleList matching_modules;
777 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i)
779 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
780 if (module_file_spec)
782 ModuleSpec module_spec (module_file_spec);
783 matching_modules.Clear();
784 target->GetImages().FindModules (module_spec, matching_modules);
785 num_matches += matching_modules.ResolveSymbolContextForFilePath (filename,
788 eSymbolContextModule | eSymbolContextCompUnit,
795 num_matches = target->GetImages().ResolveSymbolContextForFilePath (filename,
798 eSymbolContextModule | eSymbolContextCompUnit,
802 if (num_matches == 0)
804 result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
805 m_options.file_name.c_str());
806 result.SetStatus (eReturnStatusFailed);
812 bool got_multiple = false;
813 FileSpec *test_cu_spec = NULL;
815 for (unsigned i = 0; i < num_matches; i++)
818 sc_list.GetContextAtIndex(i, sc);
823 if (test_cu_spec != static_cast<FileSpec *> (sc.comp_unit))
828 test_cu_spec = sc.comp_unit;
833 result.AppendErrorWithFormat("Multiple source files found matching: \"%s.\"\n",
834 m_options.file_name.c_str());
835 result.SetStatus (eReturnStatusFailed);
841 if (sc_list.GetContextAtIndex(0, sc))
845 if (m_options.show_bp_locs)
847 const bool show_inlines = true;
848 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
849 SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this());
850 target_search_filter.Search (m_breakpoint_locations);
853 m_breakpoint_locations.Clear();
855 if (m_options.num_lines == 0)
856 m_options.num_lines = 10;
858 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
859 m_options.start_line,
863 &result.GetOutputStream(),
864 GetBreakpointLocations ());
866 result.SetStatus (eReturnStatusSuccessFinishResult);
870 result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
871 m_options.file_name.c_str());
872 result.SetStatus (eReturnStatusFailed);
877 return result.Succeeded();
880 const SymbolContextList *
881 GetBreakpointLocations ()
883 if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
884 return &m_breakpoint_locations.GetFileLineMatches();
887 CommandOptions m_options;
888 FileLineResolver m_breakpoint_locations;
889 std::string m_reverse_name;
894 CommandObjectSourceList::CommandOptions::g_option_table[] =
896 { LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeCount, "The number of source lines to display."},
898 LLDB_OPT_SET_2 , false, "shlib", 's', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source file in the given shared library."},
899 { 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."},
900 { LLDB_OPT_SET_1 , false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
901 { LLDB_OPT_SET_1 , false, "line", 'l', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeLineNum, "The line number at which to start the display source."},
902 { LLDB_OPT_SET_2 , false, "name", 'n', OptionParser::eRequiredArgument, NULL, NULL, CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."},
903 { 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."},
904 { 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."},
905 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
908 #pragma mark CommandObjectMultiwordSource
910 //-------------------------------------------------------------------------
911 // CommandObjectMultiwordSource
912 //-------------------------------------------------------------------------
914 CommandObjectMultiwordSource::CommandObjectMultiwordSource (CommandInterpreter &interpreter) :
915 CommandObjectMultiword (interpreter,
917 "A set of commands for accessing source file information",
918 "source <subcommand> [<subcommand-options>]")
920 // "source info" isn't implemented yet...
921 //LoadSubCommand ("info", CommandObjectSP (new CommandObjectSourceInfo (interpreter)));
922 LoadSubCommand ("list", CommandObjectSP (new CommandObjectSourceList (interpreter)));
925 CommandObjectMultiwordSource::~CommandObjectMultiwordSource ()