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 "lldb/lldb-python.h"
12 #include "CommandObjectSource.h"
16 // Other libraries and framework includes
18 #include "lldb/Interpreter/Args.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/FileLineResolver.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/SourceManager.h"
24 #include "lldb/Interpreter/CommandInterpreter.h"
25 #include "lldb/Interpreter/CommandReturnObject.h"
26 #include "lldb/Host/FileSpec.h"
27 #include "lldb/Symbol/CompileUnit.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/TargetList.h"
32 #include "lldb/Interpreter/CommandCompletions.h"
33 #include "lldb/Interpreter/Options.h"
36 using namespace lldb_private;
38 //-------------------------------------------------------------------------
39 // CommandObjectSourceInfo
40 //-------------------------------------------------------------------------
42 class CommandObjectSourceInfo : public CommandObjectParsed
45 class CommandOptions : public Options
48 CommandOptions (CommandInterpreter &interpreter) :
58 SetOptionValue (uint32_t option_idx, const char *option_arg)
61 const int short_option = g_option_table[option_idx].short_option;
65 start_line = Args::StringToUInt32 (option_arg, 0);
67 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
71 file_name = option_arg;
75 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
83 OptionParsingStarting ()
90 const OptionDefinition*
93 return g_option_table;
95 static OptionDefinition g_option_table[];
97 // Instance variables to hold the values for command options.
99 std::string file_name;
105 CommandObjectSourceInfo(CommandInterpreter &interpreter) :
106 CommandObjectParsed (interpreter,
108 "Display information about the source lines from the current executable's debug info.",
109 "source info [<cmd-options>]"),
110 m_options (interpreter)
114 ~CommandObjectSourceInfo ()
127 DoExecute (Args& command, CommandReturnObject &result)
129 result.AppendError ("Not yet implemented");
130 result.SetStatus (eReturnStatusFailed);
134 CommandOptions m_options;
138 CommandObjectSourceInfo::CommandOptions::g_option_table[] =
140 { LLDB_OPT_SET_1, false, "line", 'l', required_argument, NULL, 0, eArgTypeLineNum, "The line number at which to start the display source."},
141 { LLDB_OPT_SET_1, false, "file", 'f', required_argument, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
142 { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
145 #pragma mark CommandObjectSourceList
146 //-------------------------------------------------------------------------
147 // CommandObjectSourceList
148 //-------------------------------------------------------------------------
150 class CommandObjectSourceList : public CommandObjectParsed
153 class CommandOptions : public Options
156 CommandOptions (CommandInterpreter &interpreter) :
166 SetOptionValue (uint32_t option_idx, const char *option_arg)
169 const int short_option = g_option_table[option_idx].short_option;
170 switch (short_option)
173 start_line = Args::StringToUInt32 (option_arg, 0);
175 error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg);
179 num_lines = Args::StringToUInt32 (option_arg, 0);
181 error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg);
185 file_name = option_arg;
189 symbol_name = option_arg;
194 ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
195 address = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
199 modules.push_back (std::string (option_arg));
209 error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option);
217 OptionParsingStarting ()
222 address = LLDB_INVALID_ADDRESS;
225 show_bp_locs = false;
230 const OptionDefinition*
233 return g_option_table;
235 static OptionDefinition g_option_table[];
237 // Instance variables to hold the values for command options.
239 std::string file_name;
240 std::string symbol_name;
241 lldb::addr_t address;
244 STLStringArray modules;
250 CommandObjectSourceList(CommandInterpreter &interpreter) :
251 CommandObjectParsed (interpreter,
253 "Display source code (as specified) based on the current executable's debug info.",
255 eFlagRequiresTarget),
256 m_options (interpreter)
260 ~CommandObjectSourceList ()
272 GetRepeatCommand (Args ¤t_command_args, uint32_t index)
274 // This is kind of gross, but the command hasn't been parsed yet so we can't look at the option
275 // values for this invocation... I have to scan the arguments directly.
276 size_t num_args = current_command_args.GetArgumentCount();
277 bool is_reverse = false;
278 for (size_t i = 0 ; i < num_args; i++)
280 const char *arg = current_command_args.GetArgumentAtIndex(i);
281 if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0))
288 if (m_reverse_name.empty())
290 m_reverse_name = m_cmd_name;
291 m_reverse_name.append (" -r");
293 return m_reverse_name.c_str();
296 return m_cmd_name.c_str();
303 ConstString function;
304 LineEntry line_entry;
306 SourceInfo (const ConstString &name, const LineEntry &line_entry) :
308 line_entry(line_entry)
321 return (bool)function && line_entry.IsValid();
325 operator == (const SourceInfo &rhs) const
327 return function == rhs.function &&
328 line_entry.file == rhs.line_entry.file &&
329 line_entry.line == rhs.line_entry.line;
333 operator != (const SourceInfo &rhs) const
335 return function != rhs.function ||
336 line_entry.file != rhs.line_entry.file ||
337 line_entry.line != rhs.line_entry.line;
341 operator < (const SourceInfo &rhs) const
343 if (function.GetCString() < rhs.function.GetCString())
345 if (line_entry.file.GetDirectory().GetCString() < rhs.line_entry.file.GetDirectory().GetCString())
347 if (line_entry.file.GetFilename().GetCString() < rhs.line_entry.file.GetFilename().GetCString())
349 if (line_entry.line < rhs.line_entry.line)
356 DisplayFunctionSource (const SymbolContext &sc,
357 SourceInfo &source_info,
358 CommandReturnObject &result)
360 if (!source_info.IsValid())
362 source_info.function = sc.GetFunctionName();
363 source_info.line_entry = sc.GetFunctionStartLineEntry();
368 Target *target = m_exe_ctx.GetTargetPtr();
375 if (sc.block == NULL)
377 // Not an inlined function
378 sc.function->GetStartLineSourceInfo (start_file, start_line);
381 result.AppendErrorWithFormat("Could not find line information for start of function: \"%s\".\n", source_info.function.GetCString());
382 result.SetStatus (eReturnStatusFailed);
385 sc.function->GetEndLineSourceInfo (end_file, end_line);
389 // We have an inlined function
390 start_file = source_info.line_entry.file;
391 start_line = source_info.line_entry.line;
392 end_line = start_line + m_options.num_lines;
395 // This is a little hacky, but the first line table entry for a function points to the "{" that
396 // starts the function block. It would be nice to actually get the function
397 // declaration in there too. So back up a bit, but not further than what you're going to display.
398 uint32_t extra_lines;
399 if (m_options.num_lines >= 10)
402 extra_lines = m_options.num_lines/2;
404 if (start_line <= extra_lines)
407 line_no = start_line - extra_lines;
409 // For fun, if the function is shorter than the number of lines we're supposed to display,
410 // only display the function...
413 if (m_options.num_lines > end_line - line_no)
414 m_options.num_lines = end_line - line_no + extra_lines;
417 m_breakpoint_locations.Clear();
419 if (m_options.show_bp_locs)
421 const bool show_inlines = true;
422 m_breakpoint_locations.Reset (start_file, 0, show_inlines);
423 SearchFilter target_search_filter (m_exe_ctx.GetTargetSP());
424 target_search_filter.Search (m_breakpoint_locations);
427 result.AppendMessageWithFormat("File: %s\n", start_file.GetPath().c_str());
428 return target->GetSourceManager().DisplaySourceLinesWithLineNumbers (start_file,
433 &result.GetOutputStream(),
434 GetBreakpointLocations ());
438 result.AppendErrorWithFormat("Could not find function info for: \"%s\".\n", m_options.symbol_name.c_str());
443 // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions
444 // "take a possibly empty vector of strings which are names of modules, and
445 // run the two search functions on the subset of the full module list that
446 // matches the strings in the input vector". If we wanted to put these somewhere,
447 // there should probably be a module-filter-list that can be passed to the
448 // various ModuleList::Find* calls, which would either be a vector of string
449 // names or a ModuleSpecList.
450 size_t FindMatchingFunctions (Target *target, const ConstString &name, SymbolContextList& sc_list)
452 // Displaying the source for a symbol:
453 bool include_inlines = true;
455 bool include_symbols = false;
456 size_t num_matches = 0;
458 if (m_options.num_lines == 0)
459 m_options.num_lines = 10;
461 const size_t num_modules = m_options.modules.size();
464 ModuleList matching_modules;
465 for (size_t i = 0; i < num_modules; ++i)
467 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
468 if (module_file_spec)
470 ModuleSpec module_spec (module_file_spec);
471 matching_modules.Clear();
472 target->GetImages().FindModules (module_spec, matching_modules);
473 num_matches += matching_modules.FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
479 num_matches = target->GetImages().FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
484 size_t FindMatchingFunctionSymbols (Target *target, const ConstString &name, SymbolContextList& sc_list)
486 size_t num_matches = 0;
487 const size_t num_modules = m_options.modules.size();
490 ModuleList matching_modules;
491 for (size_t i = 0; i < num_modules; ++i)
493 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
494 if (module_file_spec)
496 ModuleSpec module_spec (module_file_spec);
497 matching_modules.Clear();
498 target->GetImages().FindModules (module_spec, matching_modules);
499 num_matches += matching_modules.FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
505 num_matches = target->GetImages().FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list);
511 DoExecute (Args& command, CommandReturnObject &result)
513 const size_t argc = command.GetArgumentCount();
517 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", GetCommandName());
518 result.SetStatus (eReturnStatusFailed);
522 Target *target = m_exe_ctx.GetTargetPtr();
524 if (!m_options.symbol_name.empty())
526 SymbolContextList sc_list;
527 ConstString name(m_options.symbol_name.c_str());
529 // Displaying the source for a symbol. Search for function named name.
530 size_t num_matches = FindMatchingFunctions (target, name, sc_list);
533 // If we didn't find any functions with that name, try searching for symbols
534 // that line up exactly with function addresses.
535 SymbolContextList sc_list_symbols;
536 size_t num_symbol_matches = FindMatchingFunctionSymbols (target, name, sc_list_symbols);
537 for (size_t i = 0; i < num_symbol_matches; i++)
540 sc_list_symbols.GetContextAtIndex (i, sc);
543 const Address &base_address = sc.symbol->GetAddress();
544 Function *function = base_address.CalculateSymbolContextFunction();
547 sc_list.Append (SymbolContext(function));
555 if (num_matches == 0)
557 result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", m_options.symbol_name.c_str());
558 result.SetStatus (eReturnStatusFailed);
564 std::set<SourceInfo> source_match_set;
566 bool displayed_something = false;
567 for (size_t i = 0; i < num_matches; i++)
570 sc_list.GetContextAtIndex (i, sc);
571 SourceInfo source_info (sc.GetFunctionName(),
572 sc.GetFunctionStartLineEntry());
574 if (source_info.IsValid())
576 if (source_match_set.find(source_info) == source_match_set.end())
578 source_match_set.insert(source_info);
579 if (DisplayFunctionSource (sc, source_info, result))
580 displayed_something = true;
585 if (displayed_something)
586 result.SetStatus (eReturnStatusSuccessFinishResult);
588 result.SetStatus (eReturnStatusFailed);
593 sc_list.GetContextAtIndex (0, sc);
594 SourceInfo source_info;
596 if (DisplayFunctionSource (sc, source_info, result))
598 result.SetStatus (eReturnStatusSuccessFinishResult);
602 result.SetStatus (eReturnStatusFailed);
605 return result.Succeeded();
607 else if (m_options.address != LLDB_INVALID_ADDRESS)
610 StreamString error_strm;
611 SymbolContextList sc_list;
613 if (target->GetSectionLoadList().IsEmpty())
615 // The target isn't loaded yet, we need to lookup the file address
617 const ModuleList &module_list = target->GetImages();
618 const size_t num_modules = module_list.GetSize();
619 for (size_t i=0; i<num_modules; ++i)
621 ModuleSP module_sp (module_list.GetModuleAtIndex(i));
622 if (module_sp && module_sp->ResolveFileAddress(m_options.address, so_addr))
626 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
631 if (sc_list.GetSize() == 0)
633 result.AppendErrorWithFormat("no modules have source information for file address 0x%" PRIx64 ".\n",
635 result.SetStatus (eReturnStatusFailed);
641 // The target has some things loaded, resolve this address to a
642 // compile unit + file + line and display
643 if (target->GetSectionLoadList().ResolveLoadAddress (m_options.address, so_addr))
645 ModuleSP module_sp (so_addr.GetModule());
650 if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry)
656 so_addr.Dump(&error_strm, NULL, Address::DumpStyleModuleWithFileAddress);
657 result.AppendErrorWithFormat("address resolves to %s, but there is no line table information available for this address.\n",
658 error_strm.GetData());
659 result.SetStatus (eReturnStatusFailed);
665 if (sc_list.GetSize() == 0)
667 result.AppendErrorWithFormat("no modules contain load address 0x%" PRIx64 ".\n", m_options.address);
668 result.SetStatus (eReturnStatusFailed);
672 uint32_t num_matches = sc_list.GetSize();
673 for (uint32_t i=0; i<num_matches; ++i)
676 sc_list.GetContextAtIndex(i, sc);
679 if (m_options.show_bp_locs)
681 m_breakpoint_locations.Clear();
682 const bool show_inlines = true;
683 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
684 SearchFilter target_search_filter (target->shared_from_this());
685 target_search_filter.Search (m_breakpoint_locations);
688 bool show_fullpaths = true;
689 bool show_module = true;
690 bool show_inlined_frames = true;
691 sc.DumpStopContext(&result.GetOutputStream(),
692 m_exe_ctx.GetBestExecutionContextScope(),
693 sc.line_entry.range.GetBaseAddress(),
696 show_inlined_frames);
697 result.GetOutputStream().EOL();
699 if (m_options.num_lines == 0)
700 m_options.num_lines = 10;
702 size_t lines_to_back_up = m_options.num_lines >= 10 ? 5 : m_options.num_lines/2;
704 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
707 m_options.num_lines - lines_to_back_up,
709 &result.GetOutputStream(),
710 GetBreakpointLocations ());
711 result.SetStatus (eReturnStatusSuccessFinishResult);
715 else if (m_options.file_name.empty())
717 // Last valid source manager context, or the current frame if no
718 // valid last context in source manager.
719 // One little trick here, if you type the exact same list command twice in a row, it is
720 // more likely because you typed it once, then typed it again
721 if (m_options.start_line == 0)
723 if (target->GetSourceManager().DisplayMoreWithLineNumbers (&result.GetOutputStream(),
726 GetBreakpointLocations ()))
728 result.SetStatus (eReturnStatusSuccessFinishResult);
733 if (m_options.num_lines == 0)
734 m_options.num_lines = 10;
736 if (m_options.show_bp_locs)
738 SourceManager::FileSP last_file_sp (target->GetSourceManager().GetLastFile ());
741 const bool show_inlines = true;
742 m_breakpoint_locations.Reset (last_file_sp->GetFileSpec(), 0, show_inlines);
743 SearchFilter target_search_filter (target->shared_from_this());
744 target_search_filter.Search (m_breakpoint_locations);
748 m_breakpoint_locations.Clear();
750 if (target->GetSourceManager().DisplaySourceLinesWithLineNumbersUsingLastFile(
751 m_options.start_line, // Line to display
752 m_options.num_lines, // Lines after line to
753 UINT32_MAX, // Don't mark "line"
754 "", // Don't mark "line"
755 &result.GetOutputStream(),
756 GetBreakpointLocations ()))
758 result.SetStatus (eReturnStatusSuccessFinishResult);
765 const char *filename = m_options.file_name.c_str();
767 bool check_inlines = false;
768 SymbolContextList sc_list;
769 size_t num_matches = 0;
771 if (m_options.modules.size() > 0)
773 ModuleList matching_modules;
774 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i)
776 FileSpec module_file_spec(m_options.modules[i].c_str(), false);
777 if (module_file_spec)
779 ModuleSpec module_spec (module_file_spec);
780 matching_modules.Clear();
781 target->GetImages().FindModules (module_spec, matching_modules);
782 num_matches += matching_modules.ResolveSymbolContextForFilePath (filename,
785 eSymbolContextModule | eSymbolContextCompUnit,
792 num_matches = target->GetImages().ResolveSymbolContextForFilePath (filename,
795 eSymbolContextModule | eSymbolContextCompUnit,
799 if (num_matches == 0)
801 result.AppendErrorWithFormat("Could not find source file \"%s\".\n",
802 m_options.file_name.c_str());
803 result.SetStatus (eReturnStatusFailed);
809 bool got_multiple = false;
810 FileSpec *test_cu_spec = NULL;
812 for (unsigned i = 0; i < num_matches; i++)
815 sc_list.GetContextAtIndex(i, sc);
820 if (test_cu_spec != static_cast<FileSpec *> (sc.comp_unit))
825 test_cu_spec = sc.comp_unit;
830 result.AppendErrorWithFormat("Multiple source files found matching: \"%s.\"\n",
831 m_options.file_name.c_str());
832 result.SetStatus (eReturnStatusFailed);
838 if (sc_list.GetContextAtIndex(0, sc))
842 if (m_options.show_bp_locs)
844 const bool show_inlines = true;
845 m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines);
846 SearchFilter target_search_filter (target->shared_from_this());
847 target_search_filter.Search (m_breakpoint_locations);
850 m_breakpoint_locations.Clear();
852 if (m_options.num_lines == 0)
853 m_options.num_lines = 10;
855 target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit,
856 m_options.start_line,
860 &result.GetOutputStream(),
861 GetBreakpointLocations ());
863 result.SetStatus (eReturnStatusSuccessFinishResult);
867 result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n",
868 m_options.file_name.c_str());
869 result.SetStatus (eReturnStatusFailed);
874 return result.Succeeded();
877 const SymbolContextList *
878 GetBreakpointLocations ()
880 if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0)
881 return &m_breakpoint_locations.GetFileLineMatches();
884 CommandOptions m_options;
885 FileLineResolver m_breakpoint_locations;
886 std::string m_reverse_name;
891 CommandObjectSourceList::CommandOptions::g_option_table[] =
893 { LLDB_OPT_SET_ALL, false, "count", 'c', required_argument, NULL, 0, eArgTypeCount, "The number of source lines to display."},
895 LLDB_OPT_SET_2 , false, "shlib", 's', required_argument, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source file in the given shared library."},
896 { LLDB_OPT_SET_ALL, false, "show-breakpoints", 'b', no_argument, NULL, 0, eArgTypeNone, "Show the line table locations from the debug information that indicate valid places to set source level breakpoints."},
897 { LLDB_OPT_SET_1 , false, "file", 'f', required_argument, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."},
898 { LLDB_OPT_SET_1 , false, "line", 'l', required_argument, NULL, 0, eArgTypeLineNum, "The line number at which to start the display source."},
899 { LLDB_OPT_SET_2 , false, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."},
900 { LLDB_OPT_SET_3 , false, "address",'a', required_argument, NULL, 0, eArgTypeAddressOrExpression, "Lookup the address and display the source information for the corresponding file and line."},
901 { LLDB_OPT_SET_4, false, "reverse", 'r', no_argument, NULL, 0, eArgTypeNone, "Reverse the listing to look backwards from the last displayed block of source."},
902 { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
905 #pragma mark CommandObjectMultiwordSource
907 //-------------------------------------------------------------------------
908 // CommandObjectMultiwordSource
909 //-------------------------------------------------------------------------
911 CommandObjectMultiwordSource::CommandObjectMultiwordSource (CommandInterpreter &interpreter) :
912 CommandObjectMultiword (interpreter,
914 "A set of commands for accessing source file information",
915 "source <subcommand> [<subcommand-options>]")
917 // "source info" isn't implemented yet...
918 //LoadSubCommand ("info", CommandObjectSP (new CommandObjectSourceInfo (interpreter)));
919 LoadSubCommand ("list", CommandObjectSP (new CommandObjectSourceList (interpreter)));
922 CommandObjectMultiwordSource::~CommandObjectMultiwordSource ()