1 //===-- CommandObjectBreakpointCommand.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 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
14 #include "CommandObjectBreakpointCommand.h"
15 #include "CommandObjectBreakpoint.h"
16 #include "lldb/Breakpoint/Breakpoint.h"
17 #include "lldb/Breakpoint/BreakpointIDList.h"
18 #include "lldb/Breakpoint/BreakpointLocation.h"
19 #include "lldb/Breakpoint/StoppointCallbackContext.h"
20 #include "lldb/Core/IOHandler.h"
21 #include "lldb/Core/State.h"
22 #include "lldb/Host/OptionParser.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/CommandReturnObject.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
28 #include "llvm/ADT/STLExtras.h"
31 using namespace lldb_private;
33 //-------------------------------------------------------------------------
34 // CommandObjectBreakpointCommandAdd
35 //-------------------------------------------------------------------------
37 // FIXME: "script-type" needs to have its contents determined dynamically, so
38 // somebody can add a new scripting
39 // language to lldb and have it pickable here without having to change this
40 // enumeration by hand and rebuild lldb proper.
42 static OptionEnumValueElement g_script_option_enumeration[4] = {
43 {eScriptLanguageNone, "command",
44 "Commands are in the lldb command interpreter language"},
45 {eScriptLanguagePython, "python", "Commands are in the Python language."},
46 {eSortOrderByName, "default-script",
47 "Commands are in the default scripting language."},
48 {0, nullptr, nullptr}};
50 static OptionDefinition g_breakpoint_add_options[] = {
52 { LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
53 { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Specify whether breakpoint command execution should terminate on error." },
54 { LLDB_OPT_SET_ALL, false, "script-type", 's', OptionParser::eRequiredArgument, nullptr, g_script_option_enumeration, 0, eArgTypeNone, "Specify the language for the commands - if none is specified, the lldb command interpreter will be used." },
55 { LLDB_OPT_SET_2, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonFunction, "Give the name of a Python function to run as command for this breakpoint. Be sure to give a module name if appropriate." },
56 { LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Sets Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets." },
60 class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
61 public IOHandlerDelegateMultiline {
63 CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
64 : CommandObjectParsed(interpreter, "add",
65 "Add LLDB commands to a breakpoint, to be executed "
66 "whenever the breakpoint is hit."
67 " If no breakpoint is specified, adds the "
68 "commands to the last created breakpoint.",
70 IOHandlerDelegateMultiline("DONE",
71 IOHandlerDelegate::Completion::LLDBCommand),
75 General information about entering breakpoint commands
76 ------------------------------------------------------
79 "This command will prompt for commands to be executed when the specified \
80 breakpoint is hit. Each command is typed on its own line following the '> ' \
81 prompt until 'DONE' is entered."
85 "Syntactic errors may not be detected when initially entered, and many \
86 malformed commands can silently fail when executed. If your breakpoint commands \
87 do not appear to be executing, double-check the command syntax."
91 "Note: You may enter any debugger command exactly as you would at the debugger \
92 prompt. There is no limit to the number of commands supplied, but do NOT enter \
93 more than one command per line."
96 Special information about PYTHON breakpoint commands
97 ----------------------------------------------------
100 "You may enter either one or more lines of Python, including function \
101 definitions or calls to functions that will have been imported by the time \
102 the code executes. Single line breakpoint commands will be interpreted 'as is' \
103 when the breakpoint is hit. Multiple lines of Python will be wrapped in a \
104 generated function, and a call to the function will be attached to the breakpoint."
107 This auto-generated function is passed in three arguments:
109 frame: an lldb.SBFrame object for the frame which hit breakpoint.
111 bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
113 dict: the python session dictionary hit.
116 "When specifying a python function with the --python-function option, you need \
117 to supply the function name prepended by the module name:"
120 --python-function myutils.breakpoint_callback
122 The function itself must have the following prototype:
124 def breakpoint_callback(frame, bp_loc, dict):
125 # Your code goes here
128 "The arguments are the same as the arguments passed to generated functions as \
129 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
130 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
131 can get you to the thread via frame.GetThread(), the thread can get you to the \
132 process via thread.GetProcess(), and the process can get you back to the target \
133 via process.GetTarget()."
137 "Important Note: As Python code gets collected into functions, access to global \
138 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
139 Python syntax, including indentation, when entering Python breakpoint commands."
142 Example Python one-line breakpoint command:
144 (lldb) breakpoint command add -s python 1
145 Enter your Python command(s). Type 'DONE' to end.
146 > print "Hit this breakpoint!"
149 As a convenience, this also works for a short Python one-liner:
151 (lldb) breakpoint command add -s python 1 -o 'import time; print time.asctime()'
153 Launching '.../a.out' (x86_64)
154 (lldb) Fri Sep 10 12:17:45 2010
155 Process 21778 Stopped
156 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
160 39 -> return val + 3;
163 42 int main (int argc, char const *argv[])
165 Example multiple line Python breakpoint command:
167 (lldb) breakpoint command add -s p 1
168 Enter your Python command(s). Type 'DONE' to end.
170 > bp_count = bp_count + 1
171 > print "Hit this breakpoint " + repr(bp_count) + " times!"
174 Example multiple line Python breakpoint command, using function definition:
176 (lldb) breakpoint command add -s python 1
177 Enter your Python command(s). Type 'DONE' to end.
178 > def breakpoint_output (bp_no):
179 > out_string = "Hit breakpoint number " + repr (bp_no)
182 > breakpoint_output (1)
186 "In this case, since there is a reference to a global variable, \
187 'bp_count', you will also need to make sure 'bp_count' exists and is \
196 "Your Python code, however organized, can optionally return a value. \
197 If the returned value is False, that tells LLDB not to stop at the breakpoint \
198 to which the code is associated. Returning anything other than False, or even \
199 returning None, or even omitting a return statement entirely, will cause \
204 "Final Note: A warning that no breakpoint command was generated when there \
205 are no syntax errors may indicate that a function was declared but never called.");
207 CommandArgumentEntry arg;
208 CommandArgumentData bp_id_arg;
210 // Define the first (and only) variant of this arg.
211 bp_id_arg.arg_type = eArgTypeBreakpointID;
212 bp_id_arg.arg_repetition = eArgRepeatOptional;
214 // There is only one variant this argument could be; put it into the
216 arg.push_back(bp_id_arg);
218 // Push the data for the first argument into the m_arguments vector.
219 m_arguments.push_back(arg);
222 ~CommandObjectBreakpointCommandAdd() override = default;
224 Options *GetOptions() override { return &m_options; }
226 void IOHandlerActivated(IOHandler &io_handler) override {
227 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
229 output_sp->PutCString(g_reader_instructions);
234 void IOHandlerInputComplete(IOHandler &io_handler,
235 std::string &line) override {
236 io_handler.SetIsDone(true);
238 std::vector<BreakpointOptions *> *bp_options_vec =
239 (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
240 for (BreakpointOptions *bp_options : *bp_options_vec) {
244 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
245 cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
246 bp_options->SetCommandDataCallback(cmd_data);
250 void CollectDataForBreakpointCommandCallback(
251 std::vector<BreakpointOptions *> &bp_options_vec,
252 CommandReturnObject &result) {
253 m_interpreter.GetLLDBCommandsFromIOHandler(
255 *this, // IOHandlerDelegate
256 true, // Run IOHandler in async mode
257 &bp_options_vec); // Baton for the "io_handler" that will be passed back
258 // into our IOHandlerDelegate functions
261 /// Set a one-liner as the callback for the breakpoint.
263 SetBreakpointCommandCallback(std::vector<BreakpointOptions *> &bp_options_vec,
264 const char *oneliner) {
265 for (auto bp_options : bp_options_vec) {
266 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
268 cmd_data->user_source.AppendString(oneliner);
269 cmd_data->stop_on_error = m_options.m_stop_on_error;
271 bp_options->SetCommandDataCallback(cmd_data);
275 class CommandOptions : public Options {
278 : Options(), m_use_commands(false), m_use_script_language(false),
279 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
280 m_one_liner(), m_function_name() {}
282 ~CommandOptions() override = default;
284 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
285 ExecutionContext *execution_context) override {
287 const int short_option = m_getopt_table[option_idx].val;
289 switch (short_option) {
291 m_use_one_liner = true;
292 m_one_liner = option_arg;
296 m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum(
297 option_arg, g_breakpoint_add_options[option_idx].enum_values,
298 eScriptLanguageNone, error);
300 if (m_script_language == eScriptLanguagePython ||
301 m_script_language == eScriptLanguageDefault) {
302 m_use_script_language = true;
304 m_use_script_language = false;
309 bool success = false;
310 m_stop_on_error = Args::StringToBoolean(option_arg, false, &success);
312 error.SetErrorStringWithFormat(
313 "invalid value for stop-on-error: \"%s\"",
314 option_arg.str().c_str());
318 m_use_one_liner = false;
319 m_use_script_language = true;
320 m_function_name.assign(option_arg);
333 void OptionParsingStarting(ExecutionContext *execution_context) override {
334 m_use_commands = true;
335 m_use_script_language = false;
336 m_script_language = eScriptLanguageNone;
338 m_use_one_liner = false;
339 m_stop_on_error = true;
341 m_function_name.clear();
345 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
346 return llvm::makeArrayRef(g_breakpoint_add_options);
349 // Instance variables to hold the values for command options.
352 bool m_use_script_language;
353 lldb::ScriptLanguage m_script_language;
355 // Instance variables to hold the values for one_liner options.
356 bool m_use_one_liner;
357 std::string m_one_liner;
358 bool m_stop_on_error;
359 std::string m_function_name;
364 bool DoExecute(Args &command, CommandReturnObject &result) override {
365 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
367 if (target == nullptr) {
368 result.AppendError("There is not a current executable; there are no "
369 "breakpoints to which to add commands");
370 result.SetStatus(eReturnStatusFailed);
374 const BreakpointList &breakpoints = target->GetBreakpointList();
375 size_t num_breakpoints = breakpoints.GetSize();
377 if (num_breakpoints == 0) {
378 result.AppendError("No breakpoints exist to have commands added");
379 result.SetStatus(eReturnStatusFailed);
383 if (!m_options.m_use_script_language &&
384 !m_options.m_function_name.empty()) {
385 result.AppendError("need to enable scripting to have a function run as a "
386 "breakpoint command");
387 result.SetStatus(eReturnStatusFailed);
391 BreakpointIDList valid_bp_ids;
392 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
393 command, target, result, &valid_bp_ids);
395 m_bp_options_vec.clear();
397 if (result.Succeeded()) {
398 const size_t count = valid_bp_ids.GetSize();
400 for (size_t i = 0; i < count; ++i) {
401 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
402 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
404 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
405 BreakpointOptions *bp_options = nullptr;
406 if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
407 // This breakpoint does not have an associated location.
408 bp_options = bp->GetOptions();
410 BreakpointLocationSP bp_loc_sp(
411 bp->FindLocationByID(cur_bp_id.GetLocationID()));
412 // This breakpoint does have an associated location.
413 // Get its breakpoint options.
415 bp_options = bp_loc_sp->GetLocationOptions();
418 m_bp_options_vec.push_back(bp_options);
422 // If we are using script language, get the script interpreter
423 // in order to set or collect command callback. Otherwise, call
424 // the methods associated with this object.
425 if (m_options.m_use_script_language) {
426 ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter();
427 // Special handling for one-liner specified inline.
428 if (m_options.m_use_one_liner) {
429 script_interp->SetBreakpointCommandCallback(
430 m_bp_options_vec, m_options.m_one_liner.c_str());
431 } else if (!m_options.m_function_name.empty()) {
432 script_interp->SetBreakpointCommandCallbackFunction(
433 m_bp_options_vec, m_options.m_function_name.c_str());
435 script_interp->CollectDataForBreakpointCommandCallback(
436 m_bp_options_vec, result);
439 // Special handling for one-liner specified inline.
440 if (m_options.m_use_one_liner)
441 SetBreakpointCommandCallback(m_bp_options_vec,
442 m_options.m_one_liner.c_str());
444 CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
448 return result.Succeeded();
452 CommandOptions m_options;
453 std::vector<BreakpointOptions *> m_bp_options_vec; // This stores the
454 // breakpoint options that
456 // collecting commands for. In the CollectData... calls we need
457 // to hand this off to the IOHandler, which may run asynchronously.
458 // So we have to have some way to keep it alive, and not leak it.
459 // Making it an ivar of the command object, which never goes away
460 // achieves this. Note that if we were able to run
461 // the same command concurrently in one interpreter we'd have to
462 // make this "per invocation". But there are many more reasons
463 // why it is not in general safe to do that in lldb at present,
464 // so it isn't worthwhile to come up with a more complex mechanism
465 // to address this particular weakness right now.
466 static const char *g_reader_instructions;
469 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
470 "Enter your debugger command(s). Type 'DONE' to end.\n";
472 //-------------------------------------------------------------------------
473 // CommandObjectBreakpointCommandDelete
474 //-------------------------------------------------------------------------
476 static OptionDefinition g_breakpoint_delete_options[] = {
478 { LLDB_OPT_SET_1, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Delete commands from Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets." },
482 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
484 CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
485 : CommandObjectParsed(interpreter, "delete",
486 "Delete the set of commands from a breakpoint.",
489 CommandArgumentEntry arg;
490 CommandArgumentData bp_id_arg;
492 // Define the first (and only) variant of this arg.
493 bp_id_arg.arg_type = eArgTypeBreakpointID;
494 bp_id_arg.arg_repetition = eArgRepeatPlain;
496 // There is only one variant this argument could be; put it into the
498 arg.push_back(bp_id_arg);
500 // Push the data for the first argument into the m_arguments vector.
501 m_arguments.push_back(arg);
504 ~CommandObjectBreakpointCommandDelete() override = default;
506 Options *GetOptions() override { return &m_options; }
508 class CommandOptions : public Options {
510 CommandOptions() : Options(), m_use_dummy(false) {}
512 ~CommandOptions() override = default;
514 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
515 ExecutionContext *execution_context) override {
517 const int short_option = m_getopt_table[option_idx].val;
519 switch (short_option) {
525 error.SetErrorStringWithFormat("unrecognized option '%c'",
533 void OptionParsingStarting(ExecutionContext *execution_context) override {
537 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
538 return llvm::makeArrayRef(g_breakpoint_delete_options);
541 // Instance variables to hold the values for command options.
546 bool DoExecute(Args &command, CommandReturnObject &result) override {
547 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
549 if (target == nullptr) {
550 result.AppendError("There is not a current executable; there are no "
551 "breakpoints from which to delete commands");
552 result.SetStatus(eReturnStatusFailed);
556 const BreakpointList &breakpoints = target->GetBreakpointList();
557 size_t num_breakpoints = breakpoints.GetSize();
559 if (num_breakpoints == 0) {
560 result.AppendError("No breakpoints exist to have commands deleted");
561 result.SetStatus(eReturnStatusFailed);
565 if (command.empty()) {
567 "No breakpoint specified from which to delete the commands");
568 result.SetStatus(eReturnStatusFailed);
572 BreakpointIDList valid_bp_ids;
573 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
574 command, target, result, &valid_bp_ids);
576 if (result.Succeeded()) {
577 const size_t count = valid_bp_ids.GetSize();
578 for (size_t i = 0; i < count; ++i) {
579 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
580 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
582 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
583 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
584 BreakpointLocationSP bp_loc_sp(
585 bp->FindLocationByID(cur_bp_id.GetLocationID()));
587 bp_loc_sp->ClearCallback();
589 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
590 cur_bp_id.GetBreakpointID(),
591 cur_bp_id.GetLocationID());
592 result.SetStatus(eReturnStatusFailed);
601 return result.Succeeded();
605 CommandOptions m_options;
608 //-------------------------------------------------------------------------
609 // CommandObjectBreakpointCommandList
610 //-------------------------------------------------------------------------
612 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
614 CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
615 : CommandObjectParsed(interpreter, "list", "List the script or set of "
616 "commands to be executed when "
617 "the breakpoint is hit.",
619 CommandArgumentEntry arg;
620 CommandArgumentData bp_id_arg;
622 // Define the first (and only) variant of this arg.
623 bp_id_arg.arg_type = eArgTypeBreakpointID;
624 bp_id_arg.arg_repetition = eArgRepeatPlain;
626 // There is only one variant this argument could be; put it into the
628 arg.push_back(bp_id_arg);
630 // Push the data for the first argument into the m_arguments vector.
631 m_arguments.push_back(arg);
634 ~CommandObjectBreakpointCommandList() override = default;
637 bool DoExecute(Args &command, CommandReturnObject &result) override {
638 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
640 if (target == nullptr) {
641 result.AppendError("There is not a current executable; there are no "
642 "breakpoints for which to list commands");
643 result.SetStatus(eReturnStatusFailed);
647 const BreakpointList &breakpoints = target->GetBreakpointList();
648 size_t num_breakpoints = breakpoints.GetSize();
650 if (num_breakpoints == 0) {
651 result.AppendError("No breakpoints exist for which to list commands");
652 result.SetStatus(eReturnStatusFailed);
656 if (command.empty()) {
658 "No breakpoint specified for which to list the commands");
659 result.SetStatus(eReturnStatusFailed);
663 BreakpointIDList valid_bp_ids;
664 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
665 command, target, result, &valid_bp_ids);
667 if (result.Succeeded()) {
668 const size_t count = valid_bp_ids.GetSize();
669 for (size_t i = 0; i < count; ++i) {
670 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
671 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
673 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
676 const BreakpointOptions *bp_options = nullptr;
677 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
678 BreakpointLocationSP bp_loc_sp(
679 bp->FindLocationByID(cur_bp_id.GetLocationID()));
681 bp_options = bp_loc_sp->GetOptionsNoCreate();
683 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
684 cur_bp_id.GetBreakpointID(),
685 cur_bp_id.GetLocationID());
686 result.SetStatus(eReturnStatusFailed);
690 bp_options = bp->GetOptions();
695 BreakpointID::GetCanonicalReference(&id_str,
696 cur_bp_id.GetBreakpointID(),
697 cur_bp_id.GetLocationID());
698 const Baton *baton = bp_options->GetBaton();
700 result.GetOutputStream().Printf("Breakpoint %s:\n",
702 result.GetOutputStream().IndentMore();
703 baton->GetDescription(&result.GetOutputStream(),
704 eDescriptionLevelFull);
705 result.GetOutputStream().IndentLess();
707 result.AppendMessageWithFormat(
708 "Breakpoint %s does not have an associated command.\n",
712 result.SetStatus(eReturnStatusSuccessFinishResult);
714 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
715 cur_bp_id.GetBreakpointID());
716 result.SetStatus(eReturnStatusFailed);
722 return result.Succeeded();
726 //-------------------------------------------------------------------------
727 // CommandObjectBreakpointCommand
728 //-------------------------------------------------------------------------
730 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
731 CommandInterpreter &interpreter)
732 : CommandObjectMultiword(
733 interpreter, "command", "Commands for adding, removing and listing "
734 "LLDB commands executed when a breakpoint is "
736 "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
737 CommandObjectSP add_command_object(
738 new CommandObjectBreakpointCommandAdd(interpreter));
739 CommandObjectSP delete_command_object(
740 new CommandObjectBreakpointCommandDelete(interpreter));
741 CommandObjectSP list_command_object(
742 new CommandObjectBreakpointCommandList(interpreter));
744 add_command_object->SetCommandName("breakpoint command add");
745 delete_command_object->SetCommandName("breakpoint command delete");
746 list_command_object->SetCommandName("breakpoint command list");
748 LoadSubCommand("add", add_command_object);
749 LoadSubCommand("delete", delete_command_object);
750 LoadSubCommand("list", list_command_object);
753 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;