1 //===-- CommandObjectBreakpointCommand.cpp ----------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "CommandObjectBreakpointCommand.h"
10 #include "CommandObjectBreakpoint.h"
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Breakpoint/BreakpointIDList.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Breakpoint/StoppointCallbackContext.h"
15 #include "lldb/Core/IOHandler.h"
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Interpreter/CommandInterpreter.h"
18 #include "lldb/Interpreter/CommandReturnObject.h"
19 #include "lldb/Interpreter/OptionArgParser.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Utility/State.h"
24 #include "llvm/ADT/STLExtras.h"
27 using namespace lldb_private;
29 // FIXME: "script-type" needs to have its contents determined dynamically, so
30 // somebody can add a new scripting language to lldb and have it pickable here
31 // without having to change this enumeration by hand and rebuild lldb proper.
32 static constexpr OptionEnumValueElement g_script_option_enumeration[] = {
36 "Commands are in the lldb command interpreter language",
39 eScriptLanguagePython,
41 "Commands are in the Python language.",
46 "Commands are in the default scripting language.",
50 static constexpr OptionEnumValues ScriptOptionEnum() {
51 return OptionEnumValues(g_script_option_enumeration);
54 #define LLDB_OPTIONS_breakpoint_command_add
55 #include "CommandOptions.inc"
57 class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
58 public IOHandlerDelegateMultiline {
60 CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
61 : CommandObjectParsed(interpreter, "add",
62 "Add LLDB commands to a breakpoint, to be executed "
63 "whenever the breakpoint is hit."
64 " If no breakpoint is specified, adds the "
65 "commands to the last created breakpoint.",
67 IOHandlerDelegateMultiline("DONE",
68 IOHandlerDelegate::Completion::LLDBCommand),
72 General information about entering breakpoint commands
73 ------------------------------------------------------
76 "This command will prompt for commands to be executed when the specified \
77 breakpoint is hit. Each command is typed on its own line following the '> ' \
78 prompt until 'DONE' is entered."
82 "Syntactic errors may not be detected when initially entered, and many \
83 malformed commands can silently fail when executed. If your breakpoint commands \
84 do not appear to be executing, double-check the command syntax."
88 "Note: You may enter any debugger command exactly as you would at the debugger \
89 prompt. There is no limit to the number of commands supplied, but do NOT enter \
90 more than one command per line."
93 Special information about PYTHON breakpoint commands
94 ----------------------------------------------------
97 "You may enter either one or more lines of Python, including function \
98 definitions or calls to functions that will have been imported by the time \
99 the code executes. Single line breakpoint commands will be interpreted 'as is' \
100 when the breakpoint is hit. Multiple lines of Python will be wrapped in a \
101 generated function, and a call to the function will be attached to the breakpoint."
104 This auto-generated function is passed in three arguments:
106 frame: an lldb.SBFrame object for the frame which hit breakpoint.
108 bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
110 dict: the python session dictionary hit.
113 "When specifying a python function with the --python-function option, you need \
114 to supply the function name prepended by the module name:"
117 --python-function myutils.breakpoint_callback
119 The function itself must have the following prototype:
121 def breakpoint_callback(frame, bp_loc, dict):
122 # Your code goes here
125 "The arguments are the same as the arguments passed to generated functions as \
126 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
127 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
128 can get you to the thread via frame.GetThread(), the thread can get you to the \
129 process via thread.GetProcess(), and the process can get you back to the target \
130 via process.GetTarget()."
134 "Important Note: As Python code gets collected into functions, access to global \
135 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
136 Python syntax, including indentation, when entering Python breakpoint commands."
139 Example Python one-line breakpoint command:
141 (lldb) breakpoint command add -s python 1
142 Enter your Python command(s). Type 'DONE' to end.
143 > print "Hit this breakpoint!"
146 As a convenience, this also works for a short Python one-liner:
148 (lldb) breakpoint command add -s python 1 -o 'import time; print time.asctime()'
150 Launching '.../a.out' (x86_64)
151 (lldb) Fri Sep 10 12:17:45 2010
152 Process 21778 Stopped
153 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
157 39 -> return val + 3;
160 42 int main (int argc, char const *argv[])
162 Example multiple line Python breakpoint command:
164 (lldb) breakpoint command add -s p 1
165 Enter your Python command(s). Type 'DONE' to end.
167 > bp_count = bp_count + 1
168 > print "Hit this breakpoint " + repr(bp_count) + " times!"
171 Example multiple line Python breakpoint command, using function definition:
173 (lldb) breakpoint command add -s python 1
174 Enter your Python command(s). Type 'DONE' to end.
175 > def breakpoint_output (bp_no):
176 > out_string = "Hit breakpoint number " + repr (bp_no)
179 > breakpoint_output (1)
183 "In this case, since there is a reference to a global variable, \
184 'bp_count', you will also need to make sure 'bp_count' exists and is \
193 "Your Python code, however organized, can optionally return a value. \
194 If the returned value is False, that tells LLDB not to stop at the breakpoint \
195 to which the code is associated. Returning anything other than False, or even \
196 returning None, or even omitting a return statement entirely, will cause \
201 "Final Note: A warning that no breakpoint command was generated when there \
202 are no syntax errors may indicate that a function was declared but never called.");
204 CommandArgumentEntry arg;
205 CommandArgumentData bp_id_arg;
207 // Define the first (and only) variant of this arg.
208 bp_id_arg.arg_type = eArgTypeBreakpointID;
209 bp_id_arg.arg_repetition = eArgRepeatOptional;
211 // There is only one variant this argument could be; put it into the
213 arg.push_back(bp_id_arg);
215 // Push the data for the first argument into the m_arguments vector.
216 m_arguments.push_back(arg);
219 ~CommandObjectBreakpointCommandAdd() override = default;
221 Options *GetOptions() override { return &m_options; }
223 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
224 StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
225 if (output_sp && interactive) {
226 output_sp->PutCString(g_reader_instructions);
231 void IOHandlerInputComplete(IOHandler &io_handler,
232 std::string &line) override {
233 io_handler.SetIsDone(true);
235 std::vector<BreakpointOptions *> *bp_options_vec =
236 (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
237 for (BreakpointOptions *bp_options : *bp_options_vec) {
241 auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
242 cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
243 bp_options->SetCommandDataCallback(cmd_data);
247 void CollectDataForBreakpointCommandCallback(
248 std::vector<BreakpointOptions *> &bp_options_vec,
249 CommandReturnObject &result) {
250 m_interpreter.GetLLDBCommandsFromIOHandler(
252 *this, // IOHandlerDelegate
253 true, // Run IOHandler in async mode
254 &bp_options_vec); // Baton for the "io_handler" that will be passed back
255 // into our IOHandlerDelegate functions
258 /// Set a one-liner as the callback for the breakpoint.
260 SetBreakpointCommandCallback(std::vector<BreakpointOptions *> &bp_options_vec,
261 const char *oneliner) {
262 for (auto bp_options : bp_options_vec) {
263 auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
265 cmd_data->user_source.AppendString(oneliner);
266 cmd_data->stop_on_error = m_options.m_stop_on_error;
268 bp_options->SetCommandDataCallback(cmd_data);
272 class CommandOptions : public Options {
275 : Options(), m_use_commands(false), m_use_script_language(false),
276 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
277 m_one_liner(), m_function_name() {}
279 ~CommandOptions() override = default;
281 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
282 ExecutionContext *execution_context) override {
284 const int short_option = m_getopt_table[option_idx].val;
286 switch (short_option) {
288 m_use_one_liner = true;
289 m_one_liner = option_arg;
293 m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
295 g_breakpoint_command_add_options[option_idx].enum_values,
296 eScriptLanguageNone, error);
298 if (m_script_language == eScriptLanguagePython ||
299 m_script_language == eScriptLanguageDefault) {
300 m_use_script_language = true;
302 m_use_script_language = false;
307 bool success = false;
309 OptionArgParser::ToBoolean(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);
327 llvm_unreachable("Unimplemented option");
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_command_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 const BreakpointList &breakpoints = target.GetBreakpointList();
367 size_t num_breakpoints = breakpoints.GetSize();
369 if (num_breakpoints == 0) {
370 result.AppendError("No breakpoints exist to have commands added");
371 result.SetStatus(eReturnStatusFailed);
375 if (!m_options.m_use_script_language &&
376 !m_options.m_function_name.empty()) {
377 result.AppendError("need to enable scripting to have a function run as a "
378 "breakpoint command");
379 result.SetStatus(eReturnStatusFailed);
383 BreakpointIDList valid_bp_ids;
384 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
385 command, &target, result, &valid_bp_ids,
386 BreakpointName::Permissions::PermissionKinds::listPerm);
388 m_bp_options_vec.clear();
390 if (result.Succeeded()) {
391 const size_t count = valid_bp_ids.GetSize();
393 for (size_t i = 0; i < count; ++i) {
394 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
395 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
397 target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
398 BreakpointOptions *bp_options = nullptr;
399 if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
400 // This breakpoint does not have an associated location.
401 bp_options = bp->GetOptions();
403 BreakpointLocationSP bp_loc_sp(
404 bp->FindLocationByID(cur_bp_id.GetLocationID()));
405 // This breakpoint does have an associated location. Get its
406 // breakpoint options.
408 bp_options = bp_loc_sp->GetLocationOptions();
411 m_bp_options_vec.push_back(bp_options);
415 // If we are using script language, get the script interpreter in order
416 // to set or collect command callback. Otherwise, call the methods
417 // associated with this object.
418 if (m_options.m_use_script_language) {
419 ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter();
420 // Special handling for one-liner specified inline.
421 if (m_options.m_use_one_liner) {
422 script_interp->SetBreakpointCommandCallback(
423 m_bp_options_vec, m_options.m_one_liner.c_str());
424 } else if (!m_options.m_function_name.empty()) {
425 script_interp->SetBreakpointCommandCallbackFunction(
426 m_bp_options_vec, m_options.m_function_name.c_str());
428 script_interp->CollectDataForBreakpointCommandCallback(
429 m_bp_options_vec, result);
432 // Special handling for one-liner specified inline.
433 if (m_options.m_use_one_liner)
434 SetBreakpointCommandCallback(m_bp_options_vec,
435 m_options.m_one_liner.c_str());
437 CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
441 return result.Succeeded();
445 CommandOptions m_options;
446 std::vector<BreakpointOptions *> m_bp_options_vec; // This stores the
447 // breakpoint options that
449 // collecting commands for. In the CollectData... calls we need to hand this
450 // off to the IOHandler, which may run asynchronously. So we have to have
451 // some way to keep it alive, and not leak it. Making it an ivar of the
452 // command object, which never goes away achieves this. Note that if we were
453 // able to run the same command concurrently in one interpreter we'd have to
454 // make this "per invocation". But there are many more reasons why it is not
455 // in general safe to do that in lldb at present, so it isn't worthwhile to
456 // come up with a more complex mechanism to address this particular weakness
458 static const char *g_reader_instructions;
461 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
462 "Enter your debugger command(s). Type 'DONE' to end.\n";
464 // CommandObjectBreakpointCommandDelete
466 #define LLDB_OPTIONS_breakpoint_command_delete
467 #include "CommandOptions.inc"
469 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
471 CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
472 : CommandObjectParsed(interpreter, "delete",
473 "Delete the set of commands from a breakpoint.",
476 CommandArgumentEntry arg;
477 CommandArgumentData bp_id_arg;
479 // Define the first (and only) variant of this arg.
480 bp_id_arg.arg_type = eArgTypeBreakpointID;
481 bp_id_arg.arg_repetition = eArgRepeatPlain;
483 // There is only one variant this argument could be; put it into the
485 arg.push_back(bp_id_arg);
487 // Push the data for the first argument into the m_arguments vector.
488 m_arguments.push_back(arg);
491 ~CommandObjectBreakpointCommandDelete() override = default;
493 Options *GetOptions() override { return &m_options; }
495 class CommandOptions : public Options {
497 CommandOptions() : Options(), m_use_dummy(false) {}
499 ~CommandOptions() override = default;
501 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
502 ExecutionContext *execution_context) override {
504 const int short_option = m_getopt_table[option_idx].val;
506 switch (short_option) {
512 llvm_unreachable("Unimplemented option");
518 void OptionParsingStarting(ExecutionContext *execution_context) override {
522 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
523 return llvm::makeArrayRef(g_breakpoint_command_delete_options);
526 // Instance variables to hold the values for command options.
531 bool DoExecute(Args &command, CommandReturnObject &result) override {
532 Target &target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
534 const BreakpointList &breakpoints = target.GetBreakpointList();
535 size_t num_breakpoints = breakpoints.GetSize();
537 if (num_breakpoints == 0) {
538 result.AppendError("No breakpoints exist to have commands deleted");
539 result.SetStatus(eReturnStatusFailed);
543 if (command.empty()) {
545 "No breakpoint specified from which to delete the commands");
546 result.SetStatus(eReturnStatusFailed);
550 BreakpointIDList valid_bp_ids;
551 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
552 command, &target, result, &valid_bp_ids,
553 BreakpointName::Permissions::PermissionKinds::listPerm);
555 if (result.Succeeded()) {
556 const size_t count = valid_bp_ids.GetSize();
557 for (size_t i = 0; i < count; ++i) {
558 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
559 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
561 target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
562 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
563 BreakpointLocationSP bp_loc_sp(
564 bp->FindLocationByID(cur_bp_id.GetLocationID()));
566 bp_loc_sp->ClearCallback();
568 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
569 cur_bp_id.GetBreakpointID(),
570 cur_bp_id.GetLocationID());
571 result.SetStatus(eReturnStatusFailed);
580 return result.Succeeded();
584 CommandOptions m_options;
587 // CommandObjectBreakpointCommandList
589 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
591 CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
592 : CommandObjectParsed(interpreter, "list",
593 "List the script or set of commands to be "
594 "executed when the breakpoint is hit.",
595 nullptr, eCommandRequiresTarget) {
596 CommandArgumentEntry arg;
597 CommandArgumentData bp_id_arg;
599 // Define the first (and only) variant of this arg.
600 bp_id_arg.arg_type = eArgTypeBreakpointID;
601 bp_id_arg.arg_repetition = eArgRepeatPlain;
603 // There is only one variant this argument could be; put it into the
605 arg.push_back(bp_id_arg);
607 // Push the data for the first argument into the m_arguments vector.
608 m_arguments.push_back(arg);
611 ~CommandObjectBreakpointCommandList() override = default;
614 bool DoExecute(Args &command, CommandReturnObject &result) override {
615 Target *target = &GetSelectedTarget();
617 const BreakpointList &breakpoints = target->GetBreakpointList();
618 size_t num_breakpoints = breakpoints.GetSize();
620 if (num_breakpoints == 0) {
621 result.AppendError("No breakpoints exist for which to list commands");
622 result.SetStatus(eReturnStatusFailed);
626 if (command.empty()) {
628 "No breakpoint specified for which to list the commands");
629 result.SetStatus(eReturnStatusFailed);
633 BreakpointIDList valid_bp_ids;
634 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
635 command, target, result, &valid_bp_ids,
636 BreakpointName::Permissions::PermissionKinds::listPerm);
638 if (result.Succeeded()) {
639 const size_t count = valid_bp_ids.GetSize();
640 for (size_t i = 0; i < count; ++i) {
641 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
642 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
644 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
647 BreakpointLocationSP bp_loc_sp;
648 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
649 bp_loc_sp = bp->FindLocationByID(cur_bp_id.GetLocationID());
652 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
653 cur_bp_id.GetBreakpointID(),
654 cur_bp_id.GetLocationID());
655 result.SetStatus(eReturnStatusFailed);
661 BreakpointID::GetCanonicalReference(&id_str,
662 cur_bp_id.GetBreakpointID(),
663 cur_bp_id.GetLocationID());
664 const Baton *baton = nullptr;
667 ->GetOptionsSpecifyingKind(BreakpointOptions::eCallback)
670 baton = bp->GetOptions()->GetBaton();
673 result.GetOutputStream().Printf("Breakpoint %s:\n",
675 result.GetOutputStream().IndentMore();
676 baton->GetDescription(&result.GetOutputStream(),
677 eDescriptionLevelFull);
678 result.GetOutputStream().IndentLess();
680 result.AppendMessageWithFormat(
681 "Breakpoint %s does not have an associated command.\n",
685 result.SetStatus(eReturnStatusSuccessFinishResult);
687 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
688 cur_bp_id.GetBreakpointID());
689 result.SetStatus(eReturnStatusFailed);
694 return result.Succeeded();
698 // CommandObjectBreakpointCommand
700 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
701 CommandInterpreter &interpreter)
702 : CommandObjectMultiword(
703 interpreter, "command", "Commands for adding, removing and listing "
704 "LLDB commands executed when a breakpoint is "
706 "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
707 CommandObjectSP add_command_object(
708 new CommandObjectBreakpointCommandAdd(interpreter));
709 CommandObjectSP delete_command_object(
710 new CommandObjectBreakpointCommandDelete(interpreter));
711 CommandObjectSP list_command_object(
712 new CommandObjectBreakpointCommandList(interpreter));
714 add_command_object->SetCommandName("breakpoint command add");
715 delete_command_object->SetCommandName("breakpoint command delete");
716 list_command_object->SetCommandName("breakpoint command list");
718 LoadSubCommand("add", add_command_object);
719 LoadSubCommand("delete", delete_command_object);
720 LoadSubCommand("list", list_command_object);
723 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;