1 //===-- CommandObjectWatchpointCommand.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 //===----------------------------------------------------------------------===//
14 // Other libraries and framework includes
16 #include "CommandObjectWatchpoint.h"
17 #include "CommandObjectWatchpointCommand.h"
18 #include "lldb/Breakpoint/StoppointCallbackContext.h"
19 #include "lldb/Breakpoint/Watchpoint.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"
29 using namespace lldb_private;
31 //-------------------------------------------------------------------------
32 // CommandObjectWatchpointCommandAdd
33 //-------------------------------------------------------------------------
35 // FIXME: "script-type" needs to have its contents determined dynamically, so
36 // somebody can add a new scripting
37 // language to lldb and have it pickable here without having to change this
38 // enumeration by hand and rebuild lldb proper.
40 static OptionEnumValueElement g_script_option_enumeration[4] = {
41 {eScriptLanguageNone, "command",
42 "Commands are in the lldb command interpreter language"},
43 {eScriptLanguagePython, "python", "Commands are in the Python language."},
44 {eSortOrderByName, "default-script",
45 "Commands are in the default scripting language."},
46 {0, nullptr, nullptr}};
48 static OptionDefinition g_watchpoint_command_add_options[] = {
50 { LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line watchpoint command inline. Be sure to surround it with quotes." },
51 { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Specify whether watchpoint command execution should terminate on error." },
52 { 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." },
53 { 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 watchpoint. Be sure to give a module name if appropriate." }
57 class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
58 public IOHandlerDelegateMultiline {
60 CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
61 : CommandObjectParsed(interpreter, "add",
62 "Add a set of LLDB commands to a watchpoint, to be "
63 "executed whenever the watchpoint is hit.",
65 IOHandlerDelegateMultiline("DONE",
66 IOHandlerDelegate::Completion::LLDBCommand),
70 General information about entering watchpoint commands
71 ------------------------------------------------------
74 "This command will prompt for commands to be executed when the specified \
75 watchpoint is hit. Each command is typed on its own line following the '> ' \
76 prompt until 'DONE' is entered."
80 "Syntactic errors may not be detected when initially entered, and many \
81 malformed commands can silently fail when executed. If your watchpoint commands \
82 do not appear to be executing, double-check the command syntax."
86 "Note: You may enter any debugger command exactly as you would at the debugger \
87 prompt. There is no limit to the number of commands supplied, but do NOT enter \
88 more than one command per line."
91 Special information about PYTHON watchpoint commands
92 ----------------------------------------------------
95 "You may enter either one or more lines of Python, including function \
96 definitions or calls to functions that will have been imported by the time \
97 the code executes. Single line watchpoint commands will be interpreted 'as is' \
98 when the watchpoint is hit. Multiple lines of Python will be wrapped in a \
99 generated function, and a call to the function will be attached to the watchpoint."
102 This auto-generated function is passed in three arguments:
104 frame: an lldb.SBFrame object for the frame which hit the watchpoint.
106 wp: the watchpoint that was hit.
109 "When specifying a python function with the --python-function option, you need \
110 to supply the function name prepended by the module name:"
113 --python-function myutils.watchpoint_callback
115 The function itself must have the following prototype:
117 def watchpoint_callback(frame, wp):
118 # Your code goes here
121 "The arguments are the same as the arguments passed to generated functions as \
122 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
123 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
124 can get you to the thread via frame.GetThread(), the thread can get you to the \
125 process via thread.GetProcess(), and the process can get you back to the target \
126 via process.GetTarget()."
130 "Important Note: As Python code gets collected into functions, access to global \
131 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
132 Python syntax, including indentation, when entering Python watchpoint commands."
135 Example Python one-line watchpoint command:
137 (lldb) watchpoint command add -s python 1
138 Enter your Python command(s). Type 'DONE' to end.
139 > print "Hit this watchpoint!"
142 As a convenience, this also works for a short Python one-liner:
144 (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
146 Launching '.../a.out' (x86_64)
147 (lldb) Fri Sep 10 12:17:45 2010
148 Process 21778 Stopped
149 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
153 39 -> return val + 3;
156 42 int main (int argc, char const *argv[])
158 Example multiple line Python watchpoint command, using function definition:
160 (lldb) watchpoint command add -s python 1
161 Enter your Python command(s). Type 'DONE' to end.
162 > def watchpoint_output (wp_no):
163 > out_string = "Hit watchpoint number " + repr (wp_no)
166 > watchpoint_output (1)
169 Example multiple line Python watchpoint command, using 'loose' Python:
171 (lldb) watchpoint command add -s p 1
172 Enter your Python command(s). Type 'DONE' to end.
174 > wp_count = wp_count + 1
175 > print "Hit this watchpoint " + repr(wp_count) + " times!"
179 "In this case, since there is a reference to a global variable, \
180 'wp_count', you will also need to make sure 'wp_count' exists and is \
189 "Final Note: A warning that no watchpoint command was generated when there \
190 are no syntax errors may indicate that a function was declared but never called.");
192 CommandArgumentEntry arg;
193 CommandArgumentData wp_id_arg;
195 // Define the first (and only) variant of this arg.
196 wp_id_arg.arg_type = eArgTypeWatchpointID;
197 wp_id_arg.arg_repetition = eArgRepeatPlain;
199 // There is only one variant this argument could be; put it into the
201 arg.push_back(wp_id_arg);
203 // Push the data for the first argument into the m_arguments vector.
204 m_arguments.push_back(arg);
207 ~CommandObjectWatchpointCommandAdd() override = default;
209 Options *GetOptions() override { return &m_options; }
211 void IOHandlerActivated(IOHandler &io_handler) override {
212 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
214 output_sp->PutCString(
215 "Enter your debugger command(s). Type 'DONE' to end.\n");
220 void IOHandlerInputComplete(IOHandler &io_handler,
221 std::string &line) override {
222 io_handler.SetIsDone(true);
224 // The WatchpointOptions object is owned by the watchpoint or watchpoint
226 WatchpointOptions *wp_options =
227 (WatchpointOptions *)io_handler.GetUserData();
229 std::unique_ptr<WatchpointOptions::CommandData> data_ap(
230 new WatchpointOptions::CommandData());
232 data_ap->user_source.SplitIntoLines(line);
233 auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
235 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
240 void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
241 CommandReturnObject &result) {
242 m_interpreter.GetLLDBCommandsFromIOHandler(
244 *this, // IOHandlerDelegate
245 true, // Run IOHandler in async mode
246 wp_options); // Baton for the "io_handler" that will be passed back into
247 // our IOHandlerDelegate functions
250 /// Set a one-liner as the callback for the watchpoint.
251 void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
252 const char *oneliner) {
253 std::unique_ptr<WatchpointOptions::CommandData> data_ap(
254 new WatchpointOptions::CommandData());
256 // It's necessary to set both user_source and script_source to the oneliner.
257 // The former is used to generate callback description (as in watchpoint
259 // while the latter is used for Python to interpret during the actual
261 data_ap->user_source.AppendString(oneliner);
262 data_ap->script_source.assign(oneliner);
263 data_ap->stop_on_error = m_options.m_stop_on_error;
266 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
267 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
271 WatchpointOptionsCallbackFunction(void *baton,
272 StoppointCallbackContext *context,
273 lldb::user_id_t watch_id) {
274 bool ret_value = true;
275 if (baton == nullptr)
278 WatchpointOptions::CommandData *data =
279 (WatchpointOptions::CommandData *)baton;
280 StringList &commands = data->user_source;
282 if (commands.GetSize() > 0) {
283 ExecutionContext exe_ctx(context->exe_ctx_ref);
284 Target *target = exe_ctx.GetTargetPtr();
286 CommandReturnObject result;
287 Debugger &debugger = target->GetDebugger();
288 // Rig up the results secondary output stream to the debugger's, so the
289 // output will come out synchronously
290 // if the debugger is set up that way.
292 StreamSP output_stream(debugger.GetAsyncOutputStream());
293 StreamSP error_stream(debugger.GetAsyncErrorStream());
294 result.SetImmediateOutputStream(output_stream);
295 result.SetImmediateErrorStream(error_stream);
297 CommandInterpreterRunOptions options;
298 options.SetStopOnContinue(true);
299 options.SetStopOnError(data->stop_on_error);
300 options.SetEchoCommands(false);
301 options.SetPrintResults(true);
302 options.SetAddToHistory(false);
304 debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
306 result.GetImmediateOutputStream()->Flush();
307 result.GetImmediateErrorStream()->Flush();
313 class CommandOptions : public Options {
316 : Options(), m_use_commands(false), m_use_script_language(false),
317 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
318 m_one_liner(), m_function_name() {}
320 ~CommandOptions() override = default;
322 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
323 ExecutionContext *execution_context) override {
325 const int short_option = m_getopt_table[option_idx].val;
327 switch (short_option) {
329 m_use_one_liner = true;
330 m_one_liner = option_arg;
334 m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum(
335 option_arg, GetDefinitions()[option_idx].enum_values,
336 eScriptLanguageNone, error);
338 m_use_script_language = (m_script_language == eScriptLanguagePython ||
339 m_script_language == eScriptLanguageDefault);
343 bool success = false;
344 m_stop_on_error = Args::StringToBoolean(option_arg, false, &success);
346 error.SetErrorStringWithFormat(
347 "invalid value for stop-on-error: \"%s\"",
348 option_arg.str().c_str());
352 m_use_one_liner = false;
353 m_use_script_language = true;
354 m_function_name.assign(option_arg);
363 void OptionParsingStarting(ExecutionContext *execution_context) override {
364 m_use_commands = true;
365 m_use_script_language = false;
366 m_script_language = eScriptLanguageNone;
368 m_use_one_liner = false;
369 m_stop_on_error = true;
371 m_function_name.clear();
374 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
375 return llvm::makeArrayRef(g_watchpoint_command_add_options);
378 // Instance variables to hold the values for command options.
381 bool m_use_script_language;
382 lldb::ScriptLanguage m_script_language;
384 // Instance variables to hold the values for one_liner options.
385 bool m_use_one_liner;
386 std::string m_one_liner;
387 bool m_stop_on_error;
388 std::string m_function_name;
392 bool DoExecute(Args &command, CommandReturnObject &result) override {
393 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
395 if (target == nullptr) {
396 result.AppendError("There is not a current executable; there are no "
397 "watchpoints to which to add commands");
398 result.SetStatus(eReturnStatusFailed);
402 const WatchpointList &watchpoints = target->GetWatchpointList();
403 size_t num_watchpoints = watchpoints.GetSize();
405 if (num_watchpoints == 0) {
406 result.AppendError("No watchpoints exist to have commands added");
407 result.SetStatus(eReturnStatusFailed);
411 if (!m_options.m_use_script_language &&
412 !m_options.m_function_name.empty()) {
413 result.AppendError("need to enable scripting to have a function run as a "
414 "watchpoint command");
415 result.SetStatus(eReturnStatusFailed);
419 std::vector<uint32_t> valid_wp_ids;
420 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
422 result.AppendError("Invalid watchpoints specification.");
423 result.SetStatus(eReturnStatusFailed);
427 result.SetStatus(eReturnStatusSuccessFinishNoResult);
428 const size_t count = valid_wp_ids.size();
429 for (size_t i = 0; i < count; ++i) {
430 uint32_t cur_wp_id = valid_wp_ids.at(i);
431 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
432 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
433 // Sanity check wp first.
437 WatchpointOptions *wp_options = wp->GetOptions();
438 // Skip this watchpoint if wp_options is not good.
439 if (wp_options == nullptr)
442 // If we are using script language, get the script interpreter
443 // in order to set or collect command callback. Otherwise, call
444 // the methods associated with this object.
445 if (m_options.m_use_script_language) {
446 // Special handling for one-liner specified inline.
447 if (m_options.m_use_one_liner) {
448 m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback(
449 wp_options, m_options.m_one_liner.c_str());
451 // Special handling for using a Python function by name
452 // instead of extending the watchpoint callback data structures, we
454 // what the user would do manually: make their watchpoint command be a
456 else if (!m_options.m_function_name.empty()) {
457 std::string oneliner(m_options.m_function_name);
458 oneliner += "(frame, wp, internal_dict)";
459 m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback(
460 wp_options, oneliner.c_str());
462 m_interpreter.GetScriptInterpreter()
463 ->CollectDataForWatchpointCommandCallback(wp_options, result);
466 // Special handling for one-liner specified inline.
467 if (m_options.m_use_one_liner)
468 SetWatchpointCommandCallback(wp_options,
469 m_options.m_one_liner.c_str());
471 CollectDataForWatchpointCommandCallback(wp_options, result);
476 return result.Succeeded();
480 CommandOptions m_options;
483 //-------------------------------------------------------------------------
484 // CommandObjectWatchpointCommandDelete
485 //-------------------------------------------------------------------------
487 class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
489 CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
490 : CommandObjectParsed(interpreter, "delete",
491 "Delete the set of commands from a watchpoint.",
493 CommandArgumentEntry arg;
494 CommandArgumentData wp_id_arg;
496 // Define the first (and only) variant of this arg.
497 wp_id_arg.arg_type = eArgTypeWatchpointID;
498 wp_id_arg.arg_repetition = eArgRepeatPlain;
500 // There is only one variant this argument could be; put it into the
502 arg.push_back(wp_id_arg);
504 // Push the data for the first argument into the m_arguments vector.
505 m_arguments.push_back(arg);
508 ~CommandObjectWatchpointCommandDelete() override = default;
511 bool DoExecute(Args &command, CommandReturnObject &result) override {
512 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
514 if (target == nullptr) {
515 result.AppendError("There is not a current executable; there are no "
516 "watchpoints from which to delete commands");
517 result.SetStatus(eReturnStatusFailed);
521 const WatchpointList &watchpoints = target->GetWatchpointList();
522 size_t num_watchpoints = watchpoints.GetSize();
524 if (num_watchpoints == 0) {
525 result.AppendError("No watchpoints exist to have commands deleted");
526 result.SetStatus(eReturnStatusFailed);
530 if (command.GetArgumentCount() == 0) {
532 "No watchpoint specified from which to delete the commands");
533 result.SetStatus(eReturnStatusFailed);
537 std::vector<uint32_t> valid_wp_ids;
538 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
540 result.AppendError("Invalid watchpoints specification.");
541 result.SetStatus(eReturnStatusFailed);
545 result.SetStatus(eReturnStatusSuccessFinishNoResult);
546 const size_t count = valid_wp_ids.size();
547 for (size_t i = 0; i < count; ++i) {
548 uint32_t cur_wp_id = valid_wp_ids.at(i);
549 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
550 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
554 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
555 result.SetStatus(eReturnStatusFailed);
559 return result.Succeeded();
563 //-------------------------------------------------------------------------
564 // CommandObjectWatchpointCommandList
565 //-------------------------------------------------------------------------
567 class CommandObjectWatchpointCommandList : public CommandObjectParsed {
569 CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
570 : CommandObjectParsed(interpreter, "list", "List the script or set of "
571 "commands to be executed when "
572 "the watchpoint is hit.",
574 CommandArgumentEntry arg;
575 CommandArgumentData wp_id_arg;
577 // Define the first (and only) variant of this arg.
578 wp_id_arg.arg_type = eArgTypeWatchpointID;
579 wp_id_arg.arg_repetition = eArgRepeatPlain;
581 // There is only one variant this argument could be; put it into the
583 arg.push_back(wp_id_arg);
585 // Push the data for the first argument into the m_arguments vector.
586 m_arguments.push_back(arg);
589 ~CommandObjectWatchpointCommandList() override = default;
592 bool DoExecute(Args &command, CommandReturnObject &result) override {
593 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
595 if (target == nullptr) {
596 result.AppendError("There is not a current executable; there are no "
597 "watchpoints for which to list commands");
598 result.SetStatus(eReturnStatusFailed);
602 const WatchpointList &watchpoints = target->GetWatchpointList();
603 size_t num_watchpoints = watchpoints.GetSize();
605 if (num_watchpoints == 0) {
606 result.AppendError("No watchpoints exist for which to list commands");
607 result.SetStatus(eReturnStatusFailed);
611 if (command.GetArgumentCount() == 0) {
613 "No watchpoint specified for which to list the commands");
614 result.SetStatus(eReturnStatusFailed);
618 std::vector<uint32_t> valid_wp_ids;
619 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
621 result.AppendError("Invalid watchpoints specification.");
622 result.SetStatus(eReturnStatusFailed);
626 result.SetStatus(eReturnStatusSuccessFinishNoResult);
627 const size_t count = valid_wp_ids.size();
628 for (size_t i = 0; i < count; ++i) {
629 uint32_t cur_wp_id = valid_wp_ids.at(i);
630 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
631 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
634 const WatchpointOptions *wp_options = wp->GetOptions();
636 // Get the callback baton associated with the current watchpoint.
637 const Baton *baton = wp_options->GetBaton();
639 result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
640 result.GetOutputStream().IndentMore();
641 baton->GetDescription(&result.GetOutputStream(),
642 eDescriptionLevelFull);
643 result.GetOutputStream().IndentLess();
645 result.AppendMessageWithFormat(
646 "Watchpoint %u does not have an associated command.\n",
650 result.SetStatus(eReturnStatusSuccessFinishResult);
652 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
654 result.SetStatus(eReturnStatusFailed);
659 return result.Succeeded();
663 //-------------------------------------------------------------------------
664 // CommandObjectWatchpointCommand
665 //-------------------------------------------------------------------------
667 CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
668 CommandInterpreter &interpreter)
669 : CommandObjectMultiword(
670 interpreter, "command",
671 "Commands for adding, removing and examining LLDB commands "
672 "executed when the watchpoint is hit (watchpoint 'commmands').",
673 "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
674 CommandObjectSP add_command_object(
675 new CommandObjectWatchpointCommandAdd(interpreter));
676 CommandObjectSP delete_command_object(
677 new CommandObjectWatchpointCommandDelete(interpreter));
678 CommandObjectSP list_command_object(
679 new CommandObjectWatchpointCommandList(interpreter));
681 add_command_object->SetCommandName("watchpoint command add");
682 delete_command_object->SetCommandName("watchpoint command delete");
683 list_command_object->SetCommandName("watchpoint command list");
685 LoadSubCommand("add", add_command_object);
686 LoadSubCommand("delete", delete_command_object);
687 LoadSubCommand("list", list_command_object);
690 CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;