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/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Target/Thread.h"
27 #include "llvm/ADT/STLExtras.h"
30 using namespace lldb_private;
32 //-------------------------------------------------------------------------
33 // CommandObjectBreakpointCommandAdd
34 //-------------------------------------------------------------------------
36 // FIXME: "script-type" needs to have its contents determined dynamically, so
37 // somebody can add a new scripting
38 // language to lldb and have it pickable here without having to change this
39 // enumeration by hand and rebuild lldb proper.
41 static OptionEnumValueElement g_script_option_enumeration[4] = {
42 {eScriptLanguageNone, "command",
43 "Commands are in the lldb command interpreter language"},
44 {eScriptLanguagePython, "python", "Commands are in the Python language."},
45 {eSortOrderByName, "default-script",
46 "Commands are in the default scripting language."},
47 {0, nullptr, nullptr}};
49 static OptionDefinition g_breakpoint_add_options[] = {
51 { 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." },
52 { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Specify whether breakpoint command execution should terminate on error." },
53 { 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." },
54 { 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." },
55 { 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." },
59 class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
60 public IOHandlerDelegateMultiline {
62 CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
63 : CommandObjectParsed(interpreter, "add",
64 "Add LLDB commands to a breakpoint, to be executed "
65 "whenever the breakpoint is hit."
66 " If no breakpoint is specified, adds the "
67 "commands to the last created breakpoint.",
69 IOHandlerDelegateMultiline("DONE",
70 IOHandlerDelegate::Completion::LLDBCommand),
74 General information about entering breakpoint commands
75 ------------------------------------------------------
78 "This command will prompt for commands to be executed when the specified \
79 breakpoint is hit. Each command is typed on its own line following the '> ' \
80 prompt until 'DONE' is entered."
84 "Syntactic errors may not be detected when initially entered, and many \
85 malformed commands can silently fail when executed. If your breakpoint commands \
86 do not appear to be executing, double-check the command syntax."
90 "Note: You may enter any debugger command exactly as you would at the debugger \
91 prompt. There is no limit to the number of commands supplied, but do NOT enter \
92 more than one command per line."
95 Special information about PYTHON breakpoint commands
96 ----------------------------------------------------
99 "You may enter either one or more lines of Python, including function \
100 definitions or calls to functions that will have been imported by the time \
101 the code executes. Single line breakpoint commands will be interpreted 'as is' \
102 when the breakpoint is hit. Multiple lines of Python will be wrapped in a \
103 generated function, and a call to the function will be attached to the breakpoint."
106 This auto-generated function is passed in three arguments:
108 frame: an lldb.SBFrame object for the frame which hit breakpoint.
110 bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
112 dict: the python session dictionary hit.
115 "When specifying a python function with the --python-function option, you need \
116 to supply the function name prepended by the module name:"
119 --python-function myutils.breakpoint_callback
121 The function itself must have the following prototype:
123 def breakpoint_callback(frame, bp_loc, dict):
124 # Your code goes here
127 "The arguments are the same as the arguments passed to generated functions as \
128 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
129 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
130 can get you to the thread via frame.GetThread(), the thread can get you to the \
131 process via thread.GetProcess(), and the process can get you back to the target \
132 via process.GetTarget()."
136 "Important Note: As Python code gets collected into functions, access to global \
137 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
138 Python syntax, including indentation, when entering Python breakpoint commands."
141 Example Python one-line breakpoint command:
143 (lldb) breakpoint command add -s python 1
144 Enter your Python command(s). Type 'DONE' to end.
145 > print "Hit this breakpoint!"
148 As a convenience, this also works for a short Python one-liner:
150 (lldb) breakpoint command add -s python 1 -o 'import time; print time.asctime()'
152 Launching '.../a.out' (x86_64)
153 (lldb) Fri Sep 10 12:17:45 2010
154 Process 21778 Stopped
155 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
159 39 -> return val + 3;
162 42 int main (int argc, char const *argv[])
164 Example multiple line Python breakpoint command:
166 (lldb) breakpoint command add -s p 1
167 Enter your Python command(s). Type 'DONE' to end.
169 > bp_count = bp_count + 1
170 > print "Hit this breakpoint " + repr(bp_count) + " times!"
173 Example multiple line Python breakpoint command, using function definition:
175 (lldb) breakpoint command add -s python 1
176 Enter your Python command(s). Type 'DONE' to end.
177 > def breakpoint_output (bp_no):
178 > out_string = "Hit breakpoint number " + repr (bp_no)
181 > breakpoint_output (1)
185 "In this case, since there is a reference to a global variable, \
186 'bp_count', you will also need to make sure 'bp_count' exists and is \
195 "Your Python code, however organized, can optionally return a value. \
196 If the returned value is False, that tells LLDB not to stop at the breakpoint \
197 to which the code is associated. Returning anything other than False, or even \
198 returning None, or even omitting a return statement entirely, will cause \
203 "Final Note: A warning that no breakpoint command was generated when there \
204 are no syntax errors may indicate that a function was declared but never called.");
206 CommandArgumentEntry arg;
207 CommandArgumentData bp_id_arg;
209 // Define the first (and only) variant of this arg.
210 bp_id_arg.arg_type = eArgTypeBreakpointID;
211 bp_id_arg.arg_repetition = eArgRepeatOptional;
213 // There is only one variant this argument could be; put it into the
215 arg.push_back(bp_id_arg);
217 // Push the data for the first argument into the m_arguments vector.
218 m_arguments.push_back(arg);
221 ~CommandObjectBreakpointCommandAdd() override = default;
223 Options *GetOptions() override { return &m_options; }
225 void IOHandlerActivated(IOHandler &io_handler) override {
226 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
228 output_sp->PutCString(g_reader_instructions);
233 void IOHandlerInputComplete(IOHandler &io_handler,
234 std::string &line) override {
235 io_handler.SetIsDone(true);
237 std::vector<BreakpointOptions *> *bp_options_vec =
238 (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
239 for (BreakpointOptions *bp_options : *bp_options_vec) {
243 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
244 cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
245 bp_options->SetCommandDataCallback(cmd_data);
249 void CollectDataForBreakpointCommandCallback(
250 std::vector<BreakpointOptions *> &bp_options_vec,
251 CommandReturnObject &result) {
252 m_interpreter.GetLLDBCommandsFromIOHandler(
254 *this, // IOHandlerDelegate
255 true, // Run IOHandler in async mode
256 &bp_options_vec); // Baton for the "io_handler" that will be passed back
257 // into our IOHandlerDelegate functions
260 /// Set a one-liner as the callback for the breakpoint.
262 SetBreakpointCommandCallback(std::vector<BreakpointOptions *> &bp_options_vec,
263 const char *oneliner) {
264 for (auto bp_options : bp_options_vec) {
265 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
267 cmd_data->user_source.AppendString(oneliner);
268 cmd_data->stop_on_error = m_options.m_stop_on_error;
270 bp_options->SetCommandDataCallback(cmd_data);
274 class CommandOptions : public Options {
277 : Options(), m_use_commands(false), m_use_script_language(false),
278 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
279 m_one_liner(), m_function_name() {}
281 ~CommandOptions() override = default;
283 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
284 ExecutionContext *execution_context) override {
286 const int short_option = m_getopt_table[option_idx].val;
288 switch (short_option) {
290 m_use_one_liner = true;
291 m_one_liner = option_arg;
295 m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum(
296 option_arg, g_breakpoint_add_options[option_idx].enum_values,
297 eScriptLanguageNone, error);
299 if (m_script_language == eScriptLanguagePython ||
300 m_script_language == eScriptLanguageDefault) {
301 m_use_script_language = true;
303 m_use_script_language = false;
308 bool success = false;
309 m_stop_on_error = Args::StringToBoolean(option_arg, false, &success);
311 error.SetErrorStringWithFormat(
312 "invalid value for stop-on-error: \"%s\"",
313 option_arg.str().c_str());
317 m_use_one_liner = false;
318 m_use_script_language = true;
319 m_function_name.assign(option_arg);
332 void OptionParsingStarting(ExecutionContext *execution_context) override {
333 m_use_commands = true;
334 m_use_script_language = false;
335 m_script_language = eScriptLanguageNone;
337 m_use_one_liner = false;
338 m_stop_on_error = true;
340 m_function_name.clear();
344 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
345 return llvm::makeArrayRef(g_breakpoint_add_options);
348 // Instance variables to hold the values for command options.
351 bool m_use_script_language;
352 lldb::ScriptLanguage m_script_language;
354 // Instance variables to hold the values for one_liner options.
355 bool m_use_one_liner;
356 std::string m_one_liner;
357 bool m_stop_on_error;
358 std::string m_function_name;
363 bool DoExecute(Args &command, CommandReturnObject &result) override {
364 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
366 if (target == nullptr) {
367 result.AppendError("There is not a current executable; there are no "
368 "breakpoints to which to add commands");
369 result.SetStatus(eReturnStatusFailed);
373 const BreakpointList &breakpoints = target->GetBreakpointList();
374 size_t num_breakpoints = breakpoints.GetSize();
376 if (num_breakpoints == 0) {
377 result.AppendError("No breakpoints exist to have commands added");
378 result.SetStatus(eReturnStatusFailed);
382 if (!m_options.m_use_script_language &&
383 !m_options.m_function_name.empty()) {
384 result.AppendError("need to enable scripting to have a function run as a "
385 "breakpoint command");
386 result.SetStatus(eReturnStatusFailed);
390 BreakpointIDList valid_bp_ids;
391 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
392 command, target, result, &valid_bp_ids);
394 m_bp_options_vec.clear();
396 if (result.Succeeded()) {
397 const size_t count = valid_bp_ids.GetSize();
399 for (size_t i = 0; i < count; ++i) {
400 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
401 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
403 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
404 BreakpointOptions *bp_options = nullptr;
405 if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
406 // This breakpoint does not have an associated location.
407 bp_options = bp->GetOptions();
409 BreakpointLocationSP bp_loc_sp(
410 bp->FindLocationByID(cur_bp_id.GetLocationID()));
411 // This breakpoint does have an associated location.
412 // Get its breakpoint options.
414 bp_options = bp_loc_sp->GetLocationOptions();
417 m_bp_options_vec.push_back(bp_options);
421 // If we are using script language, get the script interpreter
422 // in order to set or collect command callback. Otherwise, call
423 // the methods associated with this object.
424 if (m_options.m_use_script_language) {
425 ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter();
426 // Special handling for one-liner specified inline.
427 if (m_options.m_use_one_liner) {
428 script_interp->SetBreakpointCommandCallback(
429 m_bp_options_vec, m_options.m_one_liner.c_str());
430 } else if (!m_options.m_function_name.empty()) {
431 script_interp->SetBreakpointCommandCallbackFunction(
432 m_bp_options_vec, m_options.m_function_name.c_str());
434 script_interp->CollectDataForBreakpointCommandCallback(
435 m_bp_options_vec, result);
438 // Special handling for one-liner specified inline.
439 if (m_options.m_use_one_liner)
440 SetBreakpointCommandCallback(m_bp_options_vec,
441 m_options.m_one_liner.c_str());
443 CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
447 return result.Succeeded();
451 CommandOptions m_options;
452 std::vector<BreakpointOptions *> m_bp_options_vec; // This stores the
453 // breakpoint options that
455 // collecting commands for. In the CollectData... calls we need
456 // to hand this off to the IOHandler, which may run asynchronously.
457 // So we have to have some way to keep it alive, and not leak it.
458 // Making it an ivar of the command object, which never goes away
459 // achieves this. Note that if we were able to run
460 // the same command concurrently in one interpreter we'd have to
461 // make this "per invocation". But there are many more reasons
462 // why it is not in general safe to do that in lldb at present,
463 // so it isn't worthwhile to come up with a more complex mechanism
464 // to address this particular weakness right now.
465 static const char *g_reader_instructions;
468 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
469 "Enter your debugger command(s). Type 'DONE' to end.\n";
471 //-------------------------------------------------------------------------
472 // CommandObjectBreakpointCommandDelete
473 //-------------------------------------------------------------------------
475 static OptionDefinition g_breakpoint_delete_options[] = {
477 { 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." },
481 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
483 CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
484 : CommandObjectParsed(interpreter, "delete",
485 "Delete the set of commands from a breakpoint.",
488 CommandArgumentEntry arg;
489 CommandArgumentData bp_id_arg;
491 // Define the first (and only) variant of this arg.
492 bp_id_arg.arg_type = eArgTypeBreakpointID;
493 bp_id_arg.arg_repetition = eArgRepeatPlain;
495 // There is only one variant this argument could be; put it into the
497 arg.push_back(bp_id_arg);
499 // Push the data for the first argument into the m_arguments vector.
500 m_arguments.push_back(arg);
503 ~CommandObjectBreakpointCommandDelete() override = default;
505 Options *GetOptions() override { return &m_options; }
507 class CommandOptions : public Options {
509 CommandOptions() : Options(), m_use_dummy(false) {}
511 ~CommandOptions() override = default;
513 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
514 ExecutionContext *execution_context) override {
516 const int short_option = m_getopt_table[option_idx].val;
518 switch (short_option) {
524 error.SetErrorStringWithFormat("unrecognized option '%c'",
532 void OptionParsingStarting(ExecutionContext *execution_context) override {
536 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
537 return llvm::makeArrayRef(g_breakpoint_delete_options);
540 // Instance variables to hold the values for command options.
545 bool DoExecute(Args &command, CommandReturnObject &result) override {
546 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
548 if (target == nullptr) {
549 result.AppendError("There is not a current executable; there are no "
550 "breakpoints from which to delete commands");
551 result.SetStatus(eReturnStatusFailed);
555 const BreakpointList &breakpoints = target->GetBreakpointList();
556 size_t num_breakpoints = breakpoints.GetSize();
558 if (num_breakpoints == 0) {
559 result.AppendError("No breakpoints exist to have commands deleted");
560 result.SetStatus(eReturnStatusFailed);
564 if (command.empty()) {
566 "No breakpoint specified from which to delete the commands");
567 result.SetStatus(eReturnStatusFailed);
571 BreakpointIDList valid_bp_ids;
572 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
573 command, target, result, &valid_bp_ids);
575 if (result.Succeeded()) {
576 const size_t count = valid_bp_ids.GetSize();
577 for (size_t i = 0; i < count; ++i) {
578 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
579 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
581 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
582 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
583 BreakpointLocationSP bp_loc_sp(
584 bp->FindLocationByID(cur_bp_id.GetLocationID()));
586 bp_loc_sp->ClearCallback();
588 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
589 cur_bp_id.GetBreakpointID(),
590 cur_bp_id.GetLocationID());
591 result.SetStatus(eReturnStatusFailed);
600 return result.Succeeded();
604 CommandOptions m_options;
607 //-------------------------------------------------------------------------
608 // CommandObjectBreakpointCommandList
609 //-------------------------------------------------------------------------
611 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
613 CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
614 : CommandObjectParsed(interpreter, "list", "List the script or set of "
615 "commands to be executed when "
616 "the breakpoint is hit.",
618 CommandArgumentEntry arg;
619 CommandArgumentData bp_id_arg;
621 // Define the first (and only) variant of this arg.
622 bp_id_arg.arg_type = eArgTypeBreakpointID;
623 bp_id_arg.arg_repetition = eArgRepeatPlain;
625 // There is only one variant this argument could be; put it into the
627 arg.push_back(bp_id_arg);
629 // Push the data for the first argument into the m_arguments vector.
630 m_arguments.push_back(arg);
633 ~CommandObjectBreakpointCommandList() override = default;
636 bool DoExecute(Args &command, CommandReturnObject &result) override {
637 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
639 if (target == nullptr) {
640 result.AppendError("There is not a current executable; there are no "
641 "breakpoints for which to list commands");
642 result.SetStatus(eReturnStatusFailed);
646 const BreakpointList &breakpoints = target->GetBreakpointList();
647 size_t num_breakpoints = breakpoints.GetSize();
649 if (num_breakpoints == 0) {
650 result.AppendError("No breakpoints exist for which to list commands");
651 result.SetStatus(eReturnStatusFailed);
655 if (command.empty()) {
657 "No breakpoint specified for which to list the commands");
658 result.SetStatus(eReturnStatusFailed);
662 BreakpointIDList valid_bp_ids;
663 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
664 command, target, result, &valid_bp_ids);
666 if (result.Succeeded()) {
667 const size_t count = valid_bp_ids.GetSize();
668 for (size_t i = 0; i < count; ++i) {
669 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
670 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
672 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
675 const BreakpointOptions *bp_options = nullptr;
676 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
677 BreakpointLocationSP bp_loc_sp(
678 bp->FindLocationByID(cur_bp_id.GetLocationID()));
680 bp_options = bp_loc_sp->GetOptionsNoCreate();
682 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
683 cur_bp_id.GetBreakpointID(),
684 cur_bp_id.GetLocationID());
685 result.SetStatus(eReturnStatusFailed);
689 bp_options = bp->GetOptions();
694 BreakpointID::GetCanonicalReference(&id_str,
695 cur_bp_id.GetBreakpointID(),
696 cur_bp_id.GetLocationID());
697 const Baton *baton = bp_options->GetBaton();
699 result.GetOutputStream().Printf("Breakpoint %s:\n",
701 result.GetOutputStream().IndentMore();
702 baton->GetDescription(&result.GetOutputStream(),
703 eDescriptionLevelFull);
704 result.GetOutputStream().IndentLess();
706 result.AppendMessageWithFormat(
707 "Breakpoint %s does not have an associated command.\n",
711 result.SetStatus(eReturnStatusSuccessFinishResult);
713 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
714 cur_bp_id.GetBreakpointID());
715 result.SetStatus(eReturnStatusFailed);
721 return result.Succeeded();
725 //-------------------------------------------------------------------------
726 // CommandObjectBreakpointCommand
727 //-------------------------------------------------------------------------
729 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
730 CommandInterpreter &interpreter)
731 : CommandObjectMultiword(
732 interpreter, "command", "Commands for adding, removing and listing "
733 "LLDB commands executed when a breakpoint is "
735 "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
736 CommandObjectSP add_command_object(
737 new CommandObjectBreakpointCommandAdd(interpreter));
738 CommandObjectSP delete_command_object(
739 new CommandObjectBreakpointCommandDelete(interpreter));
740 CommandObjectSP list_command_object(
741 new CommandObjectBreakpointCommandList(interpreter));
743 add_command_object->SetCommandName("breakpoint command add");
744 delete_command_object->SetCommandName("breakpoint command delete");
745 list_command_object->SetCommandName("breakpoint command list");
747 LoadSubCommand("add", add_command_object);
748 LoadSubCommand("delete", delete_command_object);
749 LoadSubCommand("list", list_command_object);
752 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;