1 //===-- CommandObjectWatchpointCommand.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 //===----------------------------------------------------------------------===//
11 #include "CommandObjectWatchpoint.h"
12 #include "CommandObjectWatchpointCommand.h"
13 #include "lldb/Breakpoint/StoppointCallbackContext.h"
14 #include "lldb/Breakpoint/Watchpoint.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"
25 using namespace lldb_private;
27 // CommandObjectWatchpointCommandAdd
29 // FIXME: "script-type" needs to have its contents determined dynamically, so
30 // somebody can add a new scripting
31 // language to lldb and have it pickable here without having to change this
32 // enumeration by hand and rebuild lldb proper.
34 static constexpr OptionEnumValueElement g_script_option_enumeration[] = {
35 {eScriptLanguageNone, "command",
36 "Commands are in the lldb command interpreter language"},
37 {eScriptLanguagePython, "python", "Commands are in the Python language."},
38 {eSortOrderByName, "default-script",
39 "Commands are in the default scripting language."} };
41 static constexpr OptionEnumValues ScriptOptionEnum() {
42 return OptionEnumValues(g_script_option_enumeration);
45 static constexpr OptionDefinition g_watchpoint_command_add_options[] = {
46 #define LLDB_OPTIONS_watchpoint_command_add
47 #include "CommandOptions.inc"
50 class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
51 public IOHandlerDelegateMultiline {
53 CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
54 : CommandObjectParsed(interpreter, "add",
55 "Add a set of LLDB commands to a watchpoint, to be "
56 "executed whenever the watchpoint is hit.",
58 IOHandlerDelegateMultiline("DONE",
59 IOHandlerDelegate::Completion::LLDBCommand),
63 General information about entering watchpoint commands
64 ------------------------------------------------------
67 "This command will prompt for commands to be executed when the specified \
68 watchpoint is hit. Each command is typed on its own line following the '> ' \
69 prompt until 'DONE' is entered."
73 "Syntactic errors may not be detected when initially entered, and many \
74 malformed commands can silently fail when executed. If your watchpoint commands \
75 do not appear to be executing, double-check the command syntax."
79 "Note: You may enter any debugger command exactly as you would at the debugger \
80 prompt. There is no limit to the number of commands supplied, but do NOT enter \
81 more than one command per line."
84 Special information about PYTHON watchpoint commands
85 ----------------------------------------------------
88 "You may enter either one or more lines of Python, including function \
89 definitions or calls to functions that will have been imported by the time \
90 the code executes. Single line watchpoint commands will be interpreted 'as is' \
91 when the watchpoint is hit. Multiple lines of Python will be wrapped in a \
92 generated function, and a call to the function will be attached to the watchpoint."
95 This auto-generated function is passed in three arguments:
97 frame: an lldb.SBFrame object for the frame which hit the watchpoint.
99 wp: the watchpoint that was hit.
102 "When specifying a python function with the --python-function option, you need \
103 to supply the function name prepended by the module name:"
106 --python-function myutils.watchpoint_callback
108 The function itself must have the following prototype:
110 def watchpoint_callback(frame, wp):
111 # Your code goes here
114 "The arguments are the same as the arguments passed to generated functions as \
115 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
116 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
117 can get you to the thread via frame.GetThread(), the thread can get you to the \
118 process via thread.GetProcess(), and the process can get you back to the target \
119 via process.GetTarget()."
123 "Important Note: As Python code gets collected into functions, access to global \
124 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
125 Python syntax, including indentation, when entering Python watchpoint commands."
128 Example Python one-line watchpoint command:
130 (lldb) watchpoint command add -s python 1
131 Enter your Python command(s). Type 'DONE' to end.
132 > print "Hit this watchpoint!"
135 As a convenience, this also works for a short Python one-liner:
137 (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
139 Launching '.../a.out' (x86_64)
140 (lldb) Fri Sep 10 12:17:45 2010
141 Process 21778 Stopped
142 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
146 39 -> return val + 3;
149 42 int main (int argc, char const *argv[])
151 Example multiple line Python watchpoint command, using function definition:
153 (lldb) watchpoint command add -s python 1
154 Enter your Python command(s). Type 'DONE' to end.
155 > def watchpoint_output (wp_no):
156 > out_string = "Hit watchpoint number " + repr (wp_no)
159 > watchpoint_output (1)
162 Example multiple line Python watchpoint command, using 'loose' Python:
164 (lldb) watchpoint command add -s p 1
165 Enter your Python command(s). Type 'DONE' to end.
167 > wp_count = wp_count + 1
168 > print "Hit this watchpoint " + repr(wp_count) + " times!"
172 "In this case, since there is a reference to a global variable, \
173 'wp_count', you will also need to make sure 'wp_count' exists and is \
182 "Final Note: A warning that no watchpoint command was generated when there \
183 are no syntax errors may indicate that a function was declared but never called.");
185 CommandArgumentEntry arg;
186 CommandArgumentData wp_id_arg;
188 // Define the first (and only) variant of this arg.
189 wp_id_arg.arg_type = eArgTypeWatchpointID;
190 wp_id_arg.arg_repetition = eArgRepeatPlain;
192 // There is only one variant this argument could be; put it into the
194 arg.push_back(wp_id_arg);
196 // Push the data for the first argument into the m_arguments vector.
197 m_arguments.push_back(arg);
200 ~CommandObjectWatchpointCommandAdd() override = default;
202 Options *GetOptions() override { return &m_options; }
204 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
205 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
206 if (output_sp && interactive) {
207 output_sp->PutCString(
208 "Enter your debugger command(s). Type 'DONE' to end.\n");
213 void IOHandlerInputComplete(IOHandler &io_handler,
214 std::string &line) override {
215 io_handler.SetIsDone(true);
217 // The WatchpointOptions object is owned by the watchpoint or watchpoint
219 WatchpointOptions *wp_options =
220 (WatchpointOptions *)io_handler.GetUserData();
222 std::unique_ptr<WatchpointOptions::CommandData> data_up(
223 new WatchpointOptions::CommandData());
225 data_up->user_source.SplitIntoLines(line);
226 auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
228 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
233 void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
234 CommandReturnObject &result) {
235 m_interpreter.GetLLDBCommandsFromIOHandler(
237 *this, // IOHandlerDelegate
238 true, // Run IOHandler in async mode
239 wp_options); // Baton for the "io_handler" that will be passed back into
240 // our IOHandlerDelegate functions
243 /// Set a one-liner as the callback for the watchpoint.
244 void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
245 const char *oneliner) {
246 std::unique_ptr<WatchpointOptions::CommandData> data_up(
247 new WatchpointOptions::CommandData());
249 // It's necessary to set both user_source and script_source to the
250 // oneliner. The former is used to generate callback description (as in
251 // watchpoint command list) while the latter is used for Python to
252 // interpret during the actual callback.
253 data_up->user_source.AppendString(oneliner);
254 data_up->script_source.assign(oneliner);
255 data_up->stop_on_error = m_options.m_stop_on_error;
258 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
259 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
263 WatchpointOptionsCallbackFunction(void *baton,
264 StoppointCallbackContext *context,
265 lldb::user_id_t watch_id) {
266 bool ret_value = true;
267 if (baton == nullptr)
270 WatchpointOptions::CommandData *data =
271 (WatchpointOptions::CommandData *)baton;
272 StringList &commands = data->user_source;
274 if (commands.GetSize() > 0) {
275 ExecutionContext exe_ctx(context->exe_ctx_ref);
276 Target *target = exe_ctx.GetTargetPtr();
278 CommandReturnObject result;
279 Debugger &debugger = target->GetDebugger();
280 // Rig up the results secondary output stream to the debugger's, so the
281 // output will come out synchronously if the debugger is set up that
284 StreamSP output_stream(debugger.GetAsyncOutputStream());
285 StreamSP error_stream(debugger.GetAsyncErrorStream());
286 result.SetImmediateOutputStream(output_stream);
287 result.SetImmediateErrorStream(error_stream);
289 CommandInterpreterRunOptions options;
290 options.SetStopOnContinue(true);
291 options.SetStopOnError(data->stop_on_error);
292 options.SetEchoCommands(false);
293 options.SetPrintResults(true);
294 options.SetPrintErrors(true);
295 options.SetAddToHistory(false);
297 debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
299 result.GetImmediateOutputStream()->Flush();
300 result.GetImmediateErrorStream()->Flush();
306 class CommandOptions : public Options {
309 : Options(), m_use_commands(false), m_use_script_language(false),
310 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
311 m_one_liner(), m_function_name() {}
313 ~CommandOptions() override = default;
315 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
316 ExecutionContext *execution_context) override {
318 const int short_option = m_getopt_table[option_idx].val;
320 switch (short_option) {
322 m_use_one_liner = true;
323 m_one_liner = option_arg;
327 m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
328 option_arg, GetDefinitions()[option_idx].enum_values,
329 eScriptLanguageNone, error);
331 m_use_script_language = (m_script_language == eScriptLanguagePython ||
332 m_script_language == eScriptLanguageDefault);
336 bool success = false;
338 OptionArgParser::ToBoolean(option_arg, false, &success);
340 error.SetErrorStringWithFormat(
341 "invalid value for stop-on-error: \"%s\"",
342 option_arg.str().c_str());
346 m_use_one_liner = false;
347 m_use_script_language = true;
348 m_function_name.assign(option_arg);
357 void OptionParsingStarting(ExecutionContext *execution_context) override {
358 m_use_commands = true;
359 m_use_script_language = false;
360 m_script_language = eScriptLanguageNone;
362 m_use_one_liner = false;
363 m_stop_on_error = true;
365 m_function_name.clear();
368 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
369 return llvm::makeArrayRef(g_watchpoint_command_add_options);
372 // Instance variables to hold the values for command options.
375 bool m_use_script_language;
376 lldb::ScriptLanguage m_script_language;
378 // Instance variables to hold the values for one_liner options.
379 bool m_use_one_liner;
380 std::string m_one_liner;
381 bool m_stop_on_error;
382 std::string m_function_name;
386 bool DoExecute(Args &command, CommandReturnObject &result) override {
387 Target *target = GetDebugger().GetSelectedTarget().get();
389 if (target == nullptr) {
390 result.AppendError("There is not a current executable; there are no "
391 "watchpoints to which to add commands");
392 result.SetStatus(eReturnStatusFailed);
396 const WatchpointList &watchpoints = target->GetWatchpointList();
397 size_t num_watchpoints = watchpoints.GetSize();
399 if (num_watchpoints == 0) {
400 result.AppendError("No watchpoints exist to have commands added");
401 result.SetStatus(eReturnStatusFailed);
405 if (!m_options.m_use_script_language &&
406 !m_options.m_function_name.empty()) {
407 result.AppendError("need to enable scripting to have a function run as a "
408 "watchpoint command");
409 result.SetStatus(eReturnStatusFailed);
413 std::vector<uint32_t> valid_wp_ids;
414 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
416 result.AppendError("Invalid watchpoints specification.");
417 result.SetStatus(eReturnStatusFailed);
421 result.SetStatus(eReturnStatusSuccessFinishNoResult);
422 const size_t count = valid_wp_ids.size();
423 for (size_t i = 0; i < count; ++i) {
424 uint32_t cur_wp_id = valid_wp_ids.at(i);
425 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
426 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
427 // Sanity check wp first.
431 WatchpointOptions *wp_options = wp->GetOptions();
432 // Skip this watchpoint if wp_options is not good.
433 if (wp_options == nullptr)
436 // If we are using script language, get the script interpreter in order
437 // to set or collect command callback. Otherwise, call the methods
438 // associated with this object.
439 if (m_options.m_use_script_language) {
440 // Special handling for one-liner specified inline.
441 if (m_options.m_use_one_liner) {
442 GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback(
443 wp_options, m_options.m_one_liner.c_str());
445 // Special handling for using a Python function by name instead of
446 // extending the watchpoint callback data structures, we just
447 // automatize what the user would do manually: make their watchpoint
448 // command be a function call
449 else if (!m_options.m_function_name.empty()) {
450 std::string oneliner(m_options.m_function_name);
451 oneliner += "(frame, wp, internal_dict)";
452 GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback(
453 wp_options, oneliner.c_str());
456 .GetScriptInterpreter()
457 ->CollectDataForWatchpointCommandCallback(wp_options, result);
460 // Special handling for one-liner specified inline.
461 if (m_options.m_use_one_liner)
462 SetWatchpointCommandCallback(wp_options,
463 m_options.m_one_liner.c_str());
465 CollectDataForWatchpointCommandCallback(wp_options, result);
470 return result.Succeeded();
474 CommandOptions m_options;
477 // CommandObjectWatchpointCommandDelete
479 class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
481 CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
482 : CommandObjectParsed(interpreter, "delete",
483 "Delete the set of commands from a watchpoint.",
485 CommandArgumentEntry arg;
486 CommandArgumentData wp_id_arg;
488 // Define the first (and only) variant of this arg.
489 wp_id_arg.arg_type = eArgTypeWatchpointID;
490 wp_id_arg.arg_repetition = eArgRepeatPlain;
492 // There is only one variant this argument could be; put it into the
494 arg.push_back(wp_id_arg);
496 // Push the data for the first argument into the m_arguments vector.
497 m_arguments.push_back(arg);
500 ~CommandObjectWatchpointCommandDelete() override = default;
503 bool DoExecute(Args &command, CommandReturnObject &result) override {
504 Target *target = GetDebugger().GetSelectedTarget().get();
506 if (target == nullptr) {
507 result.AppendError("There is not a current executable; there are no "
508 "watchpoints from which to delete commands");
509 result.SetStatus(eReturnStatusFailed);
513 const WatchpointList &watchpoints = target->GetWatchpointList();
514 size_t num_watchpoints = watchpoints.GetSize();
516 if (num_watchpoints == 0) {
517 result.AppendError("No watchpoints exist to have commands deleted");
518 result.SetStatus(eReturnStatusFailed);
522 if (command.GetArgumentCount() == 0) {
524 "No watchpoint specified from which to delete the commands");
525 result.SetStatus(eReturnStatusFailed);
529 std::vector<uint32_t> valid_wp_ids;
530 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
532 result.AppendError("Invalid watchpoints specification.");
533 result.SetStatus(eReturnStatusFailed);
537 result.SetStatus(eReturnStatusSuccessFinishNoResult);
538 const size_t count = valid_wp_ids.size();
539 for (size_t i = 0; i < count; ++i) {
540 uint32_t cur_wp_id = valid_wp_ids.at(i);
541 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
542 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
546 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
547 result.SetStatus(eReturnStatusFailed);
551 return result.Succeeded();
555 // CommandObjectWatchpointCommandList
557 class CommandObjectWatchpointCommandList : public CommandObjectParsed {
559 CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
560 : CommandObjectParsed(interpreter, "list", "List the script or set of "
561 "commands to be executed when "
562 "the watchpoint is hit.",
564 CommandArgumentEntry arg;
565 CommandArgumentData wp_id_arg;
567 // Define the first (and only) variant of this arg.
568 wp_id_arg.arg_type = eArgTypeWatchpointID;
569 wp_id_arg.arg_repetition = eArgRepeatPlain;
571 // There is only one variant this argument could be; put it into the
573 arg.push_back(wp_id_arg);
575 // Push the data for the first argument into the m_arguments vector.
576 m_arguments.push_back(arg);
579 ~CommandObjectWatchpointCommandList() override = default;
582 bool DoExecute(Args &command, CommandReturnObject &result) override {
583 Target *target = GetDebugger().GetSelectedTarget().get();
585 if (target == nullptr) {
586 result.AppendError("There is not a current executable; there are no "
587 "watchpoints for which to list commands");
588 result.SetStatus(eReturnStatusFailed);
592 const WatchpointList &watchpoints = target->GetWatchpointList();
593 size_t num_watchpoints = watchpoints.GetSize();
595 if (num_watchpoints == 0) {
596 result.AppendError("No watchpoints exist for which to list commands");
597 result.SetStatus(eReturnStatusFailed);
601 if (command.GetArgumentCount() == 0) {
603 "No watchpoint specified for which to list the commands");
604 result.SetStatus(eReturnStatusFailed);
608 std::vector<uint32_t> valid_wp_ids;
609 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
611 result.AppendError("Invalid watchpoints specification.");
612 result.SetStatus(eReturnStatusFailed);
616 result.SetStatus(eReturnStatusSuccessFinishNoResult);
617 const size_t count = valid_wp_ids.size();
618 for (size_t i = 0; i < count; ++i) {
619 uint32_t cur_wp_id = valid_wp_ids.at(i);
620 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
621 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
624 const WatchpointOptions *wp_options = wp->GetOptions();
626 // Get the callback baton associated with the current watchpoint.
627 const Baton *baton = wp_options->GetBaton();
629 result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
630 result.GetOutputStream().IndentMore();
631 baton->GetDescription(&result.GetOutputStream(),
632 eDescriptionLevelFull);
633 result.GetOutputStream().IndentLess();
635 result.AppendMessageWithFormat(
636 "Watchpoint %u does not have an associated command.\n",
640 result.SetStatus(eReturnStatusSuccessFinishResult);
642 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
644 result.SetStatus(eReturnStatusFailed);
649 return result.Succeeded();
653 // CommandObjectWatchpointCommand
655 CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
656 CommandInterpreter &interpreter)
657 : CommandObjectMultiword(
658 interpreter, "command",
659 "Commands for adding, removing and examining LLDB commands "
660 "executed when the watchpoint is hit (watchpoint 'commands').",
661 "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
662 CommandObjectSP add_command_object(
663 new CommandObjectWatchpointCommandAdd(interpreter));
664 CommandObjectSP delete_command_object(
665 new CommandObjectWatchpointCommandDelete(interpreter));
666 CommandObjectSP list_command_object(
667 new CommandObjectWatchpointCommandList(interpreter));
669 add_command_object->SetCommandName("watchpoint command add");
670 delete_command_object->SetCommandName("watchpoint command delete");
671 list_command_object->SetCommandName("watchpoint command list");
673 LoadSubCommand("add", add_command_object);
674 LoadSubCommand("delete", delete_command_object);
675 LoadSubCommand("list", list_command_object);
678 CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;