LLDB mainline
CommandObjectWatchpointCommand.cpp
Go to the documentation of this file.
1//===-- CommandObjectWatchpointCommand.cpp --------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include <vector>
10
15#include "lldb/Core/IOHandler.h"
21#include "lldb/Target/Target.h"
22
23using namespace lldb;
24using namespace lldb_private;
25
26#define LLDB_OPTIONS_watchpoint_command_add
27#include "CommandOptions.inc"
28
31public:
33 : CommandObjectParsed(interpreter, "add",
34 "Add a set of LLDB commands to a watchpoint, to be "
35 "executed whenever the watchpoint is hit. "
36 "The commands added to the watchpoint replace any "
37 "commands previously added to it.",
38 nullptr, eCommandRequiresTarget),
42 R"(
43General information about entering watchpoint commands
44------------------------------------------------------
45
46)"
47 "This command will prompt for commands to be executed when the specified \
48watchpoint is hit. Each command is typed on its own line following the '> ' \
49prompt until 'DONE' is entered."
50 R"(
51
52)"
53 "Syntactic errors may not be detected when initially entered, and many \
54malformed commands can silently fail when executed. If your watchpoint commands \
55do not appear to be executing, double-check the command syntax."
56 R"(
57
58)"
59 "Note: You may enter any debugger command exactly as you would at the debugger \
60prompt. There is no limit to the number of commands supplied, but do NOT enter \
61more than one command per line."
62 R"(
63
64Special information about PYTHON watchpoint commands
65----------------------------------------------------
66
67)"
68 "You may enter either one or more lines of Python, including function \
69definitions or calls to functions that will have been imported by the time \
70the code executes. Single line watchpoint commands will be interpreted 'as is' \
71when the watchpoint is hit. Multiple lines of Python will be wrapped in a \
72generated function, and a call to the function will be attached to the watchpoint."
73 R"(
74
75This auto-generated function is passed in three arguments:
76
77 frame: an lldb.SBFrame object for the frame which hit the watchpoint.
78
79 wp: the watchpoint that was hit.
80
81)"
82 "When specifying a python function with the --python-function option, you need \
83to supply the function name prepended by the module name:"
84 R"(
86 --python-function myutils.watchpoint_callback
88The function itself must have the following prototype:
90def watchpoint_callback(frame, wp):
91 # Your code goes here
92
93)"
94 "The arguments are the same as the arguments passed to generated functions as \
95described above. Note that the global variable 'lldb.frame' will NOT be updated when \
96this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
97can get you to the thread via frame.GetThread(), the thread can get you to the \
98process via thread.GetProcess(), and the process can get you back to the target \
99via process.GetTarget()."
100 R"(
101
102)"
103 "Important Note: As Python code gets collected into functions, access to global \
104variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
105Python syntax, including indentation, when entering Python watchpoint commands."
106 R"(
107
108Example Python one-line watchpoint command:
109
110(lldb) watchpoint command add -s python 1
111Enter your Python command(s). Type 'DONE' to end.
112> print "Hit this watchpoint!"
113> DONE
114
115As a convenience, this also works for a short Python one-liner:
116
117(lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
118(lldb) run
119Launching '.../a.out' (x86_64)
120(lldb) Fri Sep 10 12:17:45 2010
121Process 21778 Stopped
122* thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
123 36
124 37 int c(int val)
125 38 {
126 39 -> return val + 3;
127 40 }
128 41
129 42 int main (int argc, char const *argv[])
130
131Example multiple line Python watchpoint command, using function definition:
132
133(lldb) watchpoint command add -s python 1
134Enter your Python command(s). Type 'DONE' to end.
135> def watchpoint_output (wp_no):
136> out_string = "Hit watchpoint number " + repr (wp_no)
137> print out_string
138> return True
139> watchpoint_output (1)
140> DONE
141
142Example multiple line Python watchpoint command, using 'loose' Python:
143
144(lldb) watchpoint command add -s p 1
145Enter your Python command(s). Type 'DONE' to end.
146> global wp_count
147> wp_count = wp_count + 1
148> print "Hit this watchpoint " + repr(wp_count) + " times!"
149> DONE
150
151)"
152 "In this case, since there is a reference to a global variable, \
153'wp_count', you will also need to make sure 'wp_count' exists and is \
154initialized:"
155 R"(
156
157(lldb) script
158>>> wp_count = 0
159>>> quit()
160
161)"
162 "Final Note: A warning that no watchpoint command was generated when there \
163are no syntax errors may indicate that a function was declared but never called.");
164
166 }
167
168 ~CommandObjectWatchpointCommandAdd() override = default;
169
170 Options *GetOptions() override { return &m_options; }
171
172 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
173 StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
174 if (output_sp && interactive) {
175 output_sp->PutCString(
176 "Enter your debugger command(s). Type 'DONE' to end.\n");
177 output_sp->Flush();
178 }
179 }
180
181 void IOHandlerInputComplete(IOHandler &io_handler,
182 std::string &line) override {
183 io_handler.SetIsDone(true);
184
185 // The WatchpointOptions object is owned by the watchpoint or watchpoint
186 // location
187 WatchpointOptions *wp_options =
188 (WatchpointOptions *)io_handler.GetUserData();
189 if (wp_options) {
190 std::unique_ptr<WatchpointOptions::CommandData> data_up(
192 if (data_up) {
193 data_up->user_source.SplitIntoLines(line);
194 auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
195 std::move(data_up));
197 }
198 }
199 }
200
202 CommandReturnObject &result) {
204 "> ", // Prompt
205 *this, // IOHandlerDelegate
206 wp_options); // Baton for the "io_handler" that will be passed back into
207 // our IOHandlerDelegate functions
208 }
209
210 /// Set a one-liner as the callback for the watchpoint.
212 const char *oneliner) {
213 std::unique_ptr<WatchpointOptions::CommandData> data_up(
215
216 // It's necessary to set both user_source and script_source to the
217 // oneliner. The former is used to generate callback description (as in
218 // watchpoint command list) while the latter is used for Python to
219 // interpret during the actual callback.
220 data_up->user_source.AppendString(oneliner);
221 data_up->script_source.assign(oneliner);
222 data_up->stop_on_error = m_options.m_stop_on_error;
223
224 auto baton_sp =
225 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
226 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
227 }
228
229 static bool
232 lldb::user_id_t watch_id) {
233 bool ret_value = true;
234 if (baton == nullptr)
235 return true;
236
239 StringList &commands = data->user_source;
240
241 if (commands.GetSize() > 0) {
242 ExecutionContext exe_ctx(context->exe_ctx_ref);
243 Target *target = exe_ctx.GetTargetPtr();
244 if (target) {
245 Debugger &debugger = target->GetDebugger();
246 CommandReturnObject result(debugger.GetUseColor());
247
248 // Rig up the results secondary output stream to the debugger's, so the
249 // output will come out synchronously if the debugger is set up that
250 // way.
251 StreamSP output_stream(debugger.GetAsyncOutputStream());
252 StreamSP error_stream(debugger.GetAsyncErrorStream());
253 result.SetImmediateOutputStream(output_stream);
254 result.SetImmediateErrorStream(error_stream);
257 options.SetStopOnContinue(true);
258 options.SetStopOnError(data->stop_on_error);
259 options.SetEchoCommands(false);
260 options.SetPrintResults(true);
261 options.SetPrintErrors(true);
262 options.SetAddToHistory(false);
264 debugger.GetCommandInterpreter().HandleCommands(commands, exe_ctx,
265 options, result);
266 result.GetImmediateOutputStream()->Flush();
267 result.GetImmediateErrorStream()->Flush();
270 return ret_value;
271 }
272
273 class CommandOptions : public Options {
274 public:
275 CommandOptions() = default;
276
277 ~CommandOptions() override = default;
278
279 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
280 ExecutionContext *execution_context) override {
282 const int short_option = m_getopt_table[option_idx].val;
283
284 switch (short_option) {
285 case 'o':
286 m_use_one_liner = true;
287 m_one_liner = std::string(option_arg);
288 break;
289
290 case 's':
292 option_arg, GetDefinitions()[option_idx].enum_values,
294
295 switch (m_script_language) {
299 break;
302 m_use_script_language = false;
303 break;
304 }
305 break;
306
307 case 'e': {
308 bool success = false;
310 OptionArgParser::ToBoolean(option_arg, false, &success);
311 if (!success)
313 "invalid value for stop-on-error: \"{0}\"", option_arg);
314 } break;
315
316 case 'F':
317 m_use_one_liner = false;
318 m_function_name.assign(std::string(option_arg));
319 break;
320
321 default:
322 llvm_unreachable("Unimplemented option");
323 }
324 return error;
325 }
326
327 void OptionParsingStarting(ExecutionContext *execution_context) override {
328 m_use_commands = true;
329 m_use_script_language = false;
331
332 m_use_one_liner = false;
333 m_stop_on_error = true;
334 m_one_liner.clear();
335 m_function_name.clear();
336 }
337
338 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
339 return llvm::ArrayRef(g_watchpoint_command_add_options);
340 }
341
342 // Instance variables to hold the values for command options.
343
344 bool m_use_commands = false;
345 bool m_use_script_language = false;
347
348 // Instance variables to hold the values for one_liner options.
349 bool m_use_one_liner = false;
350 std::string m_one_liner;
352 std::string m_function_name;
353 };
354
355protected:
356 void DoExecute(Args &command, CommandReturnObject &result) override {
357 Target &target = GetTarget();
358
359 const WatchpointList &watchpoints = target.GetWatchpointList();
360 size_t num_watchpoints = watchpoints.GetSize();
361
362 if (num_watchpoints == 0) {
363 result.AppendError("No watchpoints exist to have commands added");
364 return;
365 }
366
367 if (!m_options.m_function_name.empty()) {
371 }
372 }
373
374 std::vector<uint32_t> valid_wp_ids;
376 valid_wp_ids)) {
377 result.AppendError("Invalid watchpoints specification.");
378 return;
379 }
380
382 const size_t count = valid_wp_ids.size();
383 for (size_t i = 0; i < count; ++i) {
384 uint32_t cur_wp_id = valid_wp_ids.at(i);
385 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
386 Watchpoint *wp = target.GetWatchpointList().FindByID(cur_wp_id).get();
387 // Sanity check wp first.
388 if (wp == nullptr)
389 continue;
390
391 WatchpointOptions *wp_options = wp->GetOptions();
392 // Skip this watchpoint if wp_options is not good.
393 if (wp_options == nullptr)
394 continue;
395
396 // If we are using script language, get the script interpreter in order
397 // to set or collect command callback. Otherwise, call the methods
398 // associated with this object.
401 /*can_create=*/true, m_options.m_script_language);
402 // Special handling for one-liner specified inline.
404 script_interp->SetWatchpointCommandCallback(
405 wp_options, m_options.m_one_liner.c_str(),
406 /*is_callback=*/false);
407 }
408 // Special handling for using a Python function by name instead of
409 // extending the watchpoint callback data structures, we just
410 // automatize what the user would do manually: make their watchpoint
411 // command be a function call
412 else if (!m_options.m_function_name.empty()) {
413 std::string function_signature = m_options.m_function_name;
414 function_signature += "(frame, wp, internal_dict)";
415 script_interp->SetWatchpointCommandCallback(
416 wp_options, function_signature.c_str(), /*is_callback=*/true);
417 } else {
418 script_interp->CollectDataForWatchpointCommandCallback(wp_options,
419 result);
420 }
421 } else {
422 // Special handling for one-liner specified inline.
425 m_options.m_one_liner.c_str());
426 else
427 CollectDataForWatchpointCommandCallback(wp_options, result);
428 }
429 }
430 }
431 }
432
433private:
434 CommandOptions m_options;
435};
436
437// CommandObjectWatchpointCommandDelete
438
440public:
442 : CommandObjectParsed(interpreter, "delete",
443 "Delete the set of commands from a watchpoint.",
444 nullptr, eCommandRequiresTarget) {
446 }
447
449
450protected:
451 void DoExecute(Args &command, CommandReturnObject &result) override {
452 Target &target = GetTarget();
453
454 const WatchpointList &watchpoints = target.GetWatchpointList();
455 size_t num_watchpoints = watchpoints.GetSize();
456
457 if (num_watchpoints == 0) {
458 result.AppendError("No watchpoints exist to have commands deleted");
459 return;
460 }
461
462 if (command.GetArgumentCount() == 0) {
463 result.AppendError(
464 "No watchpoint specified from which to delete the commands");
465 return;
466 }
467
468 std::vector<uint32_t> valid_wp_ids;
470 valid_wp_ids)) {
471 result.AppendError("Invalid watchpoints specification.");
472 return;
473 }
474
476 const size_t count = valid_wp_ids.size();
477 for (size_t i = 0; i < count; ++i) {
478 uint32_t cur_wp_id = valid_wp_ids.at(i);
479 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
480 Watchpoint *wp = target.GetWatchpointList().FindByID(cur_wp_id).get();
481 if (wp)
482 wp->ClearCallback();
483 } else {
484 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
485 return;
486 }
487 }
488 }
489};
490
491// CommandObjectWatchpointCommandList
492
494public:
496 : CommandObjectParsed(interpreter, "list",
497 "List the script or set of commands to be executed "
498 "when the watchpoint is hit.",
499 nullptr, eCommandRequiresTarget) {
501 }
502
504
505protected:
506 void DoExecute(Args &command, CommandReturnObject &result) override {
507 Target &target = GetTarget();
508
509 const WatchpointList &watchpoints = target.GetWatchpointList();
510 size_t num_watchpoints = watchpoints.GetSize();
511
512 if (num_watchpoints == 0) {
513 result.AppendError("No watchpoints exist for which to list commands");
514 return;
515 }
516
517 if (command.GetArgumentCount() == 0) {
518 result.AppendError(
519 "No watchpoint specified for which to list the commands");
520 return;
521 }
522
523 std::vector<uint32_t> valid_wp_ids;
525 valid_wp_ids)) {
526 result.AppendError("Invalid watchpoints specification.");
527 return;
528 }
529
531 const size_t count = valid_wp_ids.size();
532 for (size_t i = 0; i < count; ++i) {
533 uint32_t cur_wp_id = valid_wp_ids.at(i);
534 if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
535 Watchpoint *wp = target.GetWatchpointList().FindByID(cur_wp_id).get();
536
537 if (wp) {
538 const WatchpointOptions *wp_options = wp->GetOptions();
539 if (wp_options) {
540 // Get the callback baton associated with the current watchpoint.
541 const Baton *baton = wp_options->GetBaton();
542 if (baton) {
543 result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
547 2);
548 } else {
550 "Watchpoint %u does not have an associated command.\n",
551 cur_wp_id);
552 }
553 }
555 } else {
556 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
557 cur_wp_id);
558 }
559 }
560 }
561 }
562};
563
564// CommandObjectWatchpointCommand
565
567 CommandInterpreter &interpreter)
569 interpreter, "command",
570 "Commands for adding, removing and examining LLDB commands "
571 "executed when the watchpoint is hit (watchpoint 'commands').",
572 "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
573 CommandObjectSP add_command_object(
574 new CommandObjectWatchpointCommandAdd(interpreter));
575 CommandObjectSP delete_command_object(
576 new CommandObjectWatchpointCommandDelete(interpreter));
577 CommandObjectSP list_command_object(
578 new CommandObjectWatchpointCommandList(interpreter));
579
580 add_command_object->SetCommandName("watchpoint command add");
581 delete_command_object->SetCommandName("watchpoint command delete");
582 list_command_object->SetCommandName("watchpoint command list");
583
584 LoadSubCommand("add", add_command_object);
585 LoadSubCommand("delete", delete_command_object);
586 LoadSubCommand("list", list_command_object);
587}
588
static llvm::raw_ostream & error(Stream &strm)
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *oneliner)
Set a one-liner as the callback for the watchpoint.
CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
static bool WatchpointOptionsCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
~CommandObjectWatchpointCommandAdd() override=default
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
void DoExecute(Args &command, CommandReturnObject &result) override
void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override
Called when a line or lines have been retrieved.
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result)
CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
~CommandObjectWatchpointCommandDelete() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
~CommandObjectWatchpointCommandList() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
A command line argument class.
Definition: Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:120
A class designed to wrap callback batons so they can cleanup any acquired resources.
Definition: Baton.h:35
virtual void GetDescription(llvm::raw_ostream &s, lldb::DescriptionLevel level, unsigned indentation) const =0
void SetStopOnContinue(bool stop_on_continue)
void GetLLDBCommandsFromIOHandler(const char *prompt, IOHandlerDelegate &delegate, void *baton=nullptr)
void HandleCommands(const StringList &commands, const ExecutionContext &context, const CommandInterpreterRunOptions &options, CommandReturnObject &result)
Execute a list of commands in sequence.
static bool VerifyWatchpointIDs(Target &target, Args &args, std::vector< uint32_t > &wp_ids)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
virtual void SetHelpLong(llvm::StringRef str)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
CommandInterpreter & m_interpreter
void SetImmediateErrorStream(const lldb::StreamSP &stream_sp)
void void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void SetImmediateOutputStream(const lldb::StreamSP &stream_sp)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendMessageWithFormat(const char *format,...) __attribute__((format(printf
A class to manage flag bits.
Definition: Debugger.h:80
lldb::StreamSP GetAsyncOutputStream()
Definition: Debugger.cpp:1324
CommandInterpreter & GetCommandInterpreter()
Definition: Debugger.h:168
bool GetUseColor() const
Definition: Debugger.cpp:421
lldb::StreamSP GetAsyncErrorStream()
Definition: Debugger.cpp:1328
lldb::ScriptLanguage GetScriptLanguage() const
Definition: Debugger.cpp:345
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
Definition: Debugger.cpp:1719
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A delegate class for use with IOHandler subclasses.
Definition: IOHandler.h:189
lldb::StreamFileSP GetOutputStreamFileSP()
Definition: IOHandler.cpp:105
void SetIsDone(bool b)
Definition: IOHandler.h:85
A command line option parsing protocol class.
Definition: Options.h:58
std::vector< Option > m_getopt_table
Definition: Options.h:198
virtual void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *user_input, bool is_callback)
Set a one-liner as the callback for the watchpoint.
virtual void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result)
An error handling class.
Definition: Status.h:118
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition: Status.h:151
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition: Stream.h:401
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
unsigned GetIndentLevel() const
Get the current indentation level.
Definition: Stream.cpp:187
size_t GetSize() const
Definition: StringList.cpp:74
Debugger & GetDebugger()
Definition: Target.h:1080
WatchpointList & GetWatchpointList()
Definition: Target.h:790
This class is used by Watchpoint to manage a list of watchpoints,.
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
size_t GetSize() const
Returns the number of elements in this watchpoint list.
"lldb/Breakpoint/WatchpointOptions.h" Class that manages the options on a watchpoint.
void SetCallback(WatchpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the watchpoint option set.
Baton * GetBaton()
Fetch the baton from the callback.
WatchpointOptions * GetOptions()
Returns the WatchpointOptions structure set for this watchpoint.
Definition: Watchpoint.h:138
#define LLDB_INVALID_WATCH_ID
Definition: lldb-defines.h:43
A class that represents a running process on the host machine.
Definition: SBAddress.h:15
ScriptLanguage
Script interpreter types.
@ eScriptLanguageUnknown
@ eScriptLanguageLua
@ eScriptLanguageNone
@ eScriptLanguagePython
@ eDescriptionLevelFull
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
Definition: lldb-forward.h:333
std::shared_ptr< lldb_private::Stream > StreamSP
Definition: lldb-forward.h:432
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeWatchpointID
std::shared_ptr< lldb_private::StreamFile > StreamFileSP
Definition: lldb-forward.h:433
uint64_t user_id_t
Definition: lldb-types.h:82
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)