1e9a5627eSJohnny Chen //===-- CommandObjectWatchpointCommand.cpp ----------------------*- C++ -*-===//
2e9a5627eSJohnny Chen //
3e9a5627eSJohnny Chen //                     The LLVM Compiler Infrastructure
4e9a5627eSJohnny Chen //
5e9a5627eSJohnny Chen // This file is distributed under the University of Illinois Open Source
6e9a5627eSJohnny Chen // License. See LICENSE.TXT for details.
7e9a5627eSJohnny Chen //
8e9a5627eSJohnny Chen //===----------------------------------------------------------------------===//
9e9a5627eSJohnny Chen 
10e9a5627eSJohnny Chen // C Includes
11e9a5627eSJohnny Chen // C++ Includes
1249bcfd80SEugene Zelenko #include <vector>
13e9a5627eSJohnny Chen 
1449bcfd80SEugene Zelenko // Other libraries and framework includes
1549bcfd80SEugene Zelenko // Project includes
16e9a5627eSJohnny Chen #include "CommandObjectWatchpoint.h"
17b9c1b51eSKate Stone #include "CommandObjectWatchpointCommand.h"
18b9c1b51eSKate Stone #include "lldb/Breakpoint/StoppointCallbackContext.h"
19b9c1b51eSKate Stone #include "lldb/Breakpoint/Watchpoint.h"
2044d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
21b9c1b51eSKate Stone #include "lldb/Core/State.h"
22e9a5627eSJohnny Chen #include "lldb/Interpreter/CommandInterpreter.h"
23e9a5627eSJohnny Chen #include "lldb/Interpreter/CommandReturnObject.h"
24e9a5627eSJohnny Chen #include "lldb/Target/Target.h"
25e9a5627eSJohnny Chen #include "lldb/Target/Thread.h"
26e9a5627eSJohnny Chen 
27e9a5627eSJohnny Chen using namespace lldb;
28e9a5627eSJohnny Chen using namespace lldb_private;
29e9a5627eSJohnny Chen 
30e9a5627eSJohnny Chen //-------------------------------------------------------------------------
31e9a5627eSJohnny Chen // CommandObjectWatchpointCommandAdd
32e9a5627eSJohnny Chen //-------------------------------------------------------------------------
33e9a5627eSJohnny Chen 
34b9c1b51eSKate Stone class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
35b9c1b51eSKate Stone                                           public IOHandlerDelegateMultiline {
36e9a5627eSJohnny Chen public:
377428a18cSKate Stone   CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
38b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "add",
39b9c1b51eSKate Stone                             "Add a set of LLDB commands to a watchpoint, to be "
40b9c1b51eSKate Stone                             "executed whenever the watchpoint is hit.",
41b9c1b51eSKate Stone                             nullptr),
42b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE",
43b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
44b9c1b51eSKate Stone         m_options() {
45e9a5627eSJohnny Chen     SetHelpLong(
46ea671fbdSKate Stone         R"(
47ea671fbdSKate Stone General information about entering watchpoint commands
48ea671fbdSKate Stone ------------------------------------------------------
49ea671fbdSKate Stone 
50b9c1b51eSKate Stone )"
51b9c1b51eSKate Stone         "This command will prompt for commands to be executed when the specified \
52ea671fbdSKate Stone watchpoint is hit.  Each command is typed on its own line following the '> ' \
53b9c1b51eSKate Stone prompt until 'DONE' is entered."
54b9c1b51eSKate Stone         R"(
55ea671fbdSKate Stone 
56b9c1b51eSKate Stone )"
57b9c1b51eSKate Stone         "Syntactic errors may not be detected when initially entered, and many \
58ea671fbdSKate Stone malformed commands can silently fail when executed.  If your watchpoint commands \
59b9c1b51eSKate Stone do not appear to be executing, double-check the command syntax."
60b9c1b51eSKate Stone         R"(
61ea671fbdSKate Stone 
62b9c1b51eSKate Stone )"
63b9c1b51eSKate Stone         "Note: You may enter any debugger command exactly as you would at the debugger \
64ea671fbdSKate Stone prompt.  There is no limit to the number of commands supplied, but do NOT enter \
65b9c1b51eSKate Stone more than one command per line."
66b9c1b51eSKate Stone         R"(
67ea671fbdSKate Stone 
68ea671fbdSKate Stone Special information about PYTHON watchpoint commands
69ea671fbdSKate Stone ----------------------------------------------------
70ea671fbdSKate Stone 
71b9c1b51eSKate Stone )"
72b9c1b51eSKate Stone         "You may enter either one or more lines of Python, including function \
73ea671fbdSKate Stone definitions or calls to functions that will have been imported by the time \
74ea671fbdSKate Stone the code executes.  Single line watchpoint commands will be interpreted 'as is' \
75ea671fbdSKate Stone when the watchpoint is hit.  Multiple lines of Python will be wrapped in a \
76b9c1b51eSKate Stone generated function, and a call to the function will be attached to the watchpoint."
77b9c1b51eSKate Stone         R"(
78ea671fbdSKate Stone 
79ea671fbdSKate Stone This auto-generated function is passed in three arguments:
80ea671fbdSKate Stone 
81ea671fbdSKate Stone     frame:  an lldb.SBFrame object for the frame which hit the watchpoint.
82ea671fbdSKate Stone 
83ea671fbdSKate Stone     wp:     the watchpoint that was hit.
84ea671fbdSKate Stone 
85b9c1b51eSKate Stone )"
86b9c1b51eSKate Stone         "When specifying a python function with the --python-function option, you need \
87b9c1b51eSKate Stone to supply the function name prepended by the module name:"
88b9c1b51eSKate Stone         R"(
89ea671fbdSKate Stone 
90ea671fbdSKate Stone     --python-function myutils.watchpoint_callback
91ea671fbdSKate Stone 
92ea671fbdSKate Stone The function itself must have the following prototype:
93ea671fbdSKate Stone 
94ea671fbdSKate Stone def watchpoint_callback(frame, wp):
95ea671fbdSKate Stone   # Your code goes here
96ea671fbdSKate Stone 
97b9c1b51eSKate Stone )"
98b9c1b51eSKate Stone         "The arguments are the same as the arguments passed to generated functions as \
99ea671fbdSKate Stone described above.  Note that the global variable 'lldb.frame' will NOT be updated when \
100ea671fbdSKate Stone this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
101ea671fbdSKate Stone can get you to the thread via frame.GetThread(), the thread can get you to the \
102ea671fbdSKate Stone process via thread.GetProcess(), and the process can get you back to the target \
103b9c1b51eSKate Stone via process.GetTarget()."
104b9c1b51eSKate Stone         R"(
105ea671fbdSKate Stone 
106b9c1b51eSKate Stone )"
107b9c1b51eSKate Stone         "Important Note: As Python code gets collected into functions, access to global \
108ea671fbdSKate Stone variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
109b9c1b51eSKate Stone Python syntax, including indentation, when entering Python watchpoint commands."
110b9c1b51eSKate Stone         R"(
111ea671fbdSKate Stone 
112ea671fbdSKate Stone Example Python one-line watchpoint command:
113ea671fbdSKate Stone 
114ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
115ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
116ea671fbdSKate Stone > print "Hit this watchpoint!"
117ea671fbdSKate Stone > DONE
118ea671fbdSKate Stone 
119ea671fbdSKate Stone As a convenience, this also works for a short Python one-liner:
120ea671fbdSKate Stone 
121ea671fbdSKate Stone (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
122ea671fbdSKate Stone (lldb) run
123ea671fbdSKate Stone Launching '.../a.out'  (x86_64)
124ea671fbdSKate Stone (lldb) Fri Sep 10 12:17:45 2010
125ea671fbdSKate Stone Process 21778 Stopped
126ea671fbdSKate Stone * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
127ea671fbdSKate Stone   36
128ea671fbdSKate Stone   37   	int c(int val)
129ea671fbdSKate Stone   38   	{
130ea671fbdSKate Stone   39 ->	    return val + 3;
131ea671fbdSKate Stone   40   	}
132ea671fbdSKate Stone   41
133ea671fbdSKate Stone   42   	int main (int argc, char const *argv[])
134ea671fbdSKate Stone 
135ea671fbdSKate Stone Example multiple line Python watchpoint command, using function definition:
136ea671fbdSKate Stone 
137ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
138ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
139ea671fbdSKate Stone > def watchpoint_output (wp_no):
140ea671fbdSKate Stone >     out_string = "Hit watchpoint number " + repr (wp_no)
141ea671fbdSKate Stone >     print out_string
142ea671fbdSKate Stone >     return True
143ea671fbdSKate Stone > watchpoint_output (1)
144ea671fbdSKate Stone > DONE
145ea671fbdSKate Stone 
146ea671fbdSKate Stone Example multiple line Python watchpoint command, using 'loose' Python:
147ea671fbdSKate Stone 
148ea671fbdSKate Stone (lldb) watchpoint command add -s p 1
149ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
150ea671fbdSKate Stone > global wp_count
151ea671fbdSKate Stone > wp_count = wp_count + 1
152ea671fbdSKate Stone > print "Hit this watchpoint " + repr(wp_count) + " times!"
153ea671fbdSKate Stone > DONE
154ea671fbdSKate Stone 
155b9c1b51eSKate Stone )"
156b9c1b51eSKate Stone         "In this case, since there is a reference to a global variable, \
157ea671fbdSKate Stone 'wp_count', you will also need to make sure 'wp_count' exists and is \
158b9c1b51eSKate Stone initialized:"
159b9c1b51eSKate Stone         R"(
160ea671fbdSKate Stone 
161ea671fbdSKate Stone (lldb) script
162ea671fbdSKate Stone >>> wp_count = 0
163ea671fbdSKate Stone >>> quit()
164ea671fbdSKate Stone 
165b9c1b51eSKate Stone )"
166b9c1b51eSKate Stone         "Final Note: A warning that no watchpoint command was generated when there \
167b9c1b51eSKate Stone are no syntax errors may indicate that a function was declared but never called.");
168e9a5627eSJohnny Chen 
169e9a5627eSJohnny Chen     CommandArgumentEntry arg;
170e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
171e9a5627eSJohnny Chen 
172e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
173e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
174e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
175e9a5627eSJohnny Chen 
176b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
177b9c1b51eSKate Stone     // argument entry.
178e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
179e9a5627eSJohnny Chen 
180e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
181e9a5627eSJohnny Chen     m_arguments.push_back(arg);
182e9a5627eSJohnny Chen   }
183e9a5627eSJohnny Chen 
18449bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandAdd() override = default;
185e9a5627eSJohnny Chen 
186b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
187e9a5627eSJohnny Chen 
188b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
18944d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
190b9c1b51eSKate Stone     if (output_sp) {
191b9c1b51eSKate Stone       output_sp->PutCString(
192b9c1b51eSKate Stone           "Enter your debugger command(s).  Type 'DONE' to end.\n");
19344d93782SGreg Clayton       output_sp->Flush();
19444d93782SGreg Clayton     }
19544d93782SGreg Clayton   }
19644d93782SGreg Clayton 
197b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
198b9c1b51eSKate Stone                               std::string &line) override {
19944d93782SGreg Clayton     io_handler.SetIsDone(true);
20044d93782SGreg Clayton 
201b9c1b51eSKate Stone     // The WatchpointOptions object is owned by the watchpoint or watchpoint
202b9c1b51eSKate Stone     // location
203b9c1b51eSKate Stone     WatchpointOptions *wp_options =
204b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
205b9c1b51eSKate Stone     if (wp_options) {
206b9c1b51eSKate Stone       std::unique_ptr<WatchpointOptions::CommandData> data_ap(
207b9c1b51eSKate Stone           new WatchpointOptions::CommandData());
208b9c1b51eSKate Stone       if (data_ap) {
20944d93782SGreg Clayton         data_ap->user_source.SplitIntoLines(line);
2104e4fbe82SZachary Turner         auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
2114e4fbe82SZachary Turner             std::move(data_ap));
21244d93782SGreg Clayton         wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
21344d93782SGreg Clayton       }
21444d93782SGreg Clayton     }
21544d93782SGreg Clayton   }
21644d93782SGreg Clayton 
217b9c1b51eSKate Stone   void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
218b9c1b51eSKate Stone                                                CommandReturnObject &result) {
219b9c1b51eSKate Stone     m_interpreter.GetLLDBCommandsFromIOHandler(
220b9c1b51eSKate Stone         "> ",        // Prompt
22144d93782SGreg Clayton         *this,       // IOHandlerDelegate
22244d93782SGreg Clayton         true,        // Run IOHandler in async mode
223b9c1b51eSKate Stone         wp_options); // Baton for the "io_handler" that will be passed back into
224b9c1b51eSKate Stone                      // our IOHandlerDelegate functions
225e9a5627eSJohnny Chen   }
226e9a5627eSJohnny Chen 
227e9a5627eSJohnny Chen   /// Set a one-liner as the callback for the watchpoint.
228b9c1b51eSKate Stone   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
229b9c1b51eSKate Stone                                     const char *oneliner) {
230b9c1b51eSKate Stone     std::unique_ptr<WatchpointOptions::CommandData> data_ap(
231b9c1b51eSKate Stone         new WatchpointOptions::CommandData());
232e9a5627eSJohnny Chen 
233e9a5627eSJohnny Chen     // It's necessary to set both user_source and script_source to the oneliner.
234b9c1b51eSKate Stone     // The former is used to generate callback description (as in watchpoint
235b9c1b51eSKate Stone     // command list)
236b9c1b51eSKate Stone     // while the latter is used for Python to interpret during the actual
237b9c1b51eSKate Stone     // callback.
238e9a5627eSJohnny Chen     data_ap->user_source.AppendString(oneliner);
239e9a5627eSJohnny Chen     data_ap->script_source.assign(oneliner);
240e9a5627eSJohnny Chen     data_ap->stop_on_error = m_options.m_stop_on_error;
241e9a5627eSJohnny Chen 
2424e4fbe82SZachary Turner     auto baton_sp =
2434e4fbe82SZachary Turner         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
244e9a5627eSJohnny Chen     wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
245e9a5627eSJohnny Chen   }
246e9a5627eSJohnny Chen 
247e9a5627eSJohnny Chen   static bool
248e9a5627eSJohnny Chen   WatchpointOptionsCallbackFunction(void *baton,
249e9a5627eSJohnny Chen                                     StoppointCallbackContext *context,
250b9c1b51eSKate Stone                                     lldb::user_id_t watch_id) {
251e9a5627eSJohnny Chen     bool ret_value = true;
25249bcfd80SEugene Zelenko     if (baton == nullptr)
253e9a5627eSJohnny Chen       return true;
254e9a5627eSJohnny Chen 
255b9c1b51eSKate Stone     WatchpointOptions::CommandData *data =
256b9c1b51eSKate Stone         (WatchpointOptions::CommandData *)baton;
257e9a5627eSJohnny Chen     StringList &commands = data->user_source;
258e9a5627eSJohnny Chen 
259b9c1b51eSKate Stone     if (commands.GetSize() > 0) {
260e9a5627eSJohnny Chen       ExecutionContext exe_ctx(context->exe_ctx_ref);
261e9a5627eSJohnny Chen       Target *target = exe_ctx.GetTargetPtr();
262b9c1b51eSKate Stone       if (target) {
263e9a5627eSJohnny Chen         CommandReturnObject result;
264e9a5627eSJohnny Chen         Debugger &debugger = target->GetDebugger();
265b9c1b51eSKate Stone         // Rig up the results secondary output stream to the debugger's, so the
266b9c1b51eSKate Stone         // output will come out synchronously
267e9a5627eSJohnny Chen         // if the debugger is set up that way.
268e9a5627eSJohnny Chen 
269e9a5627eSJohnny Chen         StreamSP output_stream(debugger.GetAsyncOutputStream());
270e9a5627eSJohnny Chen         StreamSP error_stream(debugger.GetAsyncErrorStream());
271e9a5627eSJohnny Chen         result.SetImmediateOutputStream(output_stream);
272e9a5627eSJohnny Chen         result.SetImmediateErrorStream(error_stream);
273e9a5627eSJohnny Chen 
27426c7bf93SJim Ingham         CommandInterpreterRunOptions options;
27526c7bf93SJim Ingham         options.SetStopOnContinue(true);
27626c7bf93SJim Ingham         options.SetStopOnError(data->stop_on_error);
27726c7bf93SJim Ingham         options.SetEchoCommands(false);
27826c7bf93SJim Ingham         options.SetPrintResults(true);
27926c7bf93SJim Ingham         options.SetAddToHistory(false);
280e9a5627eSJohnny Chen 
281b9c1b51eSKate Stone         debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
282b9c1b51eSKate Stone                                                         options, result);
283e9a5627eSJohnny Chen         result.GetImmediateOutputStream()->Flush();
284e9a5627eSJohnny Chen         result.GetImmediateErrorStream()->Flush();
285e9a5627eSJohnny Chen       }
286e9a5627eSJohnny Chen     }
287e9a5627eSJohnny Chen     return ret_value;
288e9a5627eSJohnny Chen   }
289e9a5627eSJohnny Chen 
290b9c1b51eSKate Stone   class CommandOptions : public Options {
291e9a5627eSJohnny Chen   public:
292b9c1b51eSKate Stone     CommandOptions()
293b9c1b51eSKate Stone         : Options(), m_use_commands(false), m_use_script_language(false),
294b9c1b51eSKate Stone           m_script_language(eScriptLanguageNone), m_use_one_liner(false),
295b9c1b51eSKate Stone           m_one_liner(), m_function_name() {}
296e9a5627eSJohnny Chen 
29749bcfd80SEugene Zelenko     ~CommandOptions() override = default;
298e9a5627eSJohnny Chen 
299b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
300b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
301e9a5627eSJohnny Chen       Error error;
3023bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
303e9a5627eSJohnny Chen 
304b9c1b51eSKate Stone       switch (short_option) {
305e9a5627eSJohnny Chen       case 'o':
306e9a5627eSJohnny Chen         m_use_one_liner = true;
307e9a5627eSJohnny Chen         m_one_liner = option_arg;
308e9a5627eSJohnny Chen         break;
309e9a5627eSJohnny Chen 
310e9a5627eSJohnny Chen       case 's':
311b9c1b51eSKate Stone         m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum(
312b9c1b51eSKate Stone             option_arg, g_option_table[option_idx].enum_values,
313b9c1b51eSKate Stone             eScriptLanguageNone, error);
314e9a5627eSJohnny Chen 
315b9c1b51eSKate Stone         m_use_script_language = (m_script_language == eScriptLanguagePython ||
316b9c1b51eSKate Stone                                  m_script_language == eScriptLanguageDefault);
317e9a5627eSJohnny Chen         break;
318e9a5627eSJohnny Chen 
319b9c1b51eSKate Stone       case 'e': {
320e9a5627eSJohnny Chen         bool success = false;
321*ecbb0bb1SZachary Turner         m_stop_on_error = Args::StringToBoolean(
322*ecbb0bb1SZachary Turner             llvm::StringRef::withNullAsEmpty(option_arg), false, &success);
323e9a5627eSJohnny Chen         if (!success)
324b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
325b9c1b51eSKate Stone               "invalid value for stop-on-error: \"%s\"", option_arg);
326b9c1b51eSKate Stone       } break;
327e9a5627eSJohnny Chen 
328e9a5627eSJohnny Chen       case 'F':
329e9a5627eSJohnny Chen         m_use_one_liner = false;
330e9a5627eSJohnny Chen         m_use_script_language = true;
331e9a5627eSJohnny Chen         m_function_name.assign(option_arg);
332e9a5627eSJohnny Chen         break;
333e9a5627eSJohnny Chen 
334e9a5627eSJohnny Chen       default:
335e9a5627eSJohnny Chen         break;
336e9a5627eSJohnny Chen       }
337e9a5627eSJohnny Chen       return error;
338e9a5627eSJohnny Chen     }
33949bcfd80SEugene Zelenko 
340b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
341e9a5627eSJohnny Chen       m_use_commands = true;
342e9a5627eSJohnny Chen       m_use_script_language = false;
343e9a5627eSJohnny Chen       m_script_language = eScriptLanguageNone;
344e9a5627eSJohnny Chen 
345e9a5627eSJohnny Chen       m_use_one_liner = false;
346e9a5627eSJohnny Chen       m_stop_on_error = true;
347e9a5627eSJohnny Chen       m_one_liner.clear();
348e9a5627eSJohnny Chen       m_function_name.clear();
349e9a5627eSJohnny Chen     }
350e9a5627eSJohnny Chen 
351b9c1b51eSKate Stone     const OptionDefinition *GetDefinitions() override { return g_option_table; }
352e9a5627eSJohnny Chen 
353e9a5627eSJohnny Chen     // Options table: Required for subclasses of Options.
354e9a5627eSJohnny Chen 
355e9a5627eSJohnny Chen     static OptionDefinition g_option_table[];
356e9a5627eSJohnny Chen 
357e9a5627eSJohnny Chen     // Instance variables to hold the values for command options.
358e9a5627eSJohnny Chen 
359e9a5627eSJohnny Chen     bool m_use_commands;
360e9a5627eSJohnny Chen     bool m_use_script_language;
361e9a5627eSJohnny Chen     lldb::ScriptLanguage m_script_language;
362e9a5627eSJohnny Chen 
363e9a5627eSJohnny Chen     // Instance variables to hold the values for one_liner options.
364e9a5627eSJohnny Chen     bool m_use_one_liner;
365e9a5627eSJohnny Chen     std::string m_one_liner;
366e9a5627eSJohnny Chen     bool m_stop_on_error;
367e9a5627eSJohnny Chen     std::string m_function_name;
368e9a5627eSJohnny Chen   };
369e9a5627eSJohnny Chen 
370e9a5627eSJohnny Chen protected:
371b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
372e9a5627eSJohnny Chen     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
373e9a5627eSJohnny Chen 
374b9c1b51eSKate Stone     if (target == nullptr) {
375b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
376b9c1b51eSKate Stone                          "watchpoints to which to add commands");
377e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
378e9a5627eSJohnny Chen       return false;
379e9a5627eSJohnny Chen     }
380e9a5627eSJohnny Chen 
381e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
382e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
383e9a5627eSJohnny Chen 
384b9c1b51eSKate Stone     if (num_watchpoints == 0) {
385e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands added");
386e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
387e9a5627eSJohnny Chen       return false;
388e9a5627eSJohnny Chen     }
389e9a5627eSJohnny Chen 
390b9c1b51eSKate Stone     if (!m_options.m_use_script_language &&
391b9c1b51eSKate Stone         !m_options.m_function_name.empty()) {
392b9c1b51eSKate Stone       result.AppendError("need to enable scripting to have a function run as a "
393b9c1b51eSKate Stone                          "watchpoint command");
394e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
395e9a5627eSJohnny Chen       return false;
396e9a5627eSJohnny Chen     }
397e9a5627eSJohnny Chen 
398e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
399b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
400b9c1b51eSKate Stone                                                                valid_wp_ids)) {
401e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
402e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
403e9a5627eSJohnny Chen       return false;
404e9a5627eSJohnny Chen     }
405e9a5627eSJohnny Chen 
406e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
407e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
408b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
409e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
410b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
411e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
412e9a5627eSJohnny Chen         // Sanity check wp first.
413b9c1b51eSKate Stone         if (wp == nullptr)
414b9c1b51eSKate Stone           continue;
415e9a5627eSJohnny Chen 
416e9a5627eSJohnny Chen         WatchpointOptions *wp_options = wp->GetOptions();
417e9a5627eSJohnny Chen         // Skip this watchpoint if wp_options is not good.
418b9c1b51eSKate Stone         if (wp_options == nullptr)
419b9c1b51eSKate Stone           continue;
420e9a5627eSJohnny Chen 
421e9a5627eSJohnny Chen         // If we are using script language, get the script interpreter
422e9a5627eSJohnny Chen         // in order to set or collect command callback.  Otherwise, call
423e9a5627eSJohnny Chen         // the methods associated with this object.
424b9c1b51eSKate Stone         if (m_options.m_use_script_language) {
425e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
426b9c1b51eSKate Stone           if (m_options.m_use_one_liner) {
427b9c1b51eSKate Stone             m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback(
428b9c1b51eSKate Stone                 wp_options, m_options.m_one_liner.c_str());
429e9a5627eSJohnny Chen           }
430e9a5627eSJohnny Chen           // Special handling for using a Python function by name
431b9c1b51eSKate Stone           // instead of extending the watchpoint callback data structures, we
432b9c1b51eSKate Stone           // just automatize
433b9c1b51eSKate Stone           // what the user would do manually: make their watchpoint command be a
434b9c1b51eSKate Stone           // function call
435b9c1b51eSKate Stone           else if (!m_options.m_function_name.empty()) {
436e9a5627eSJohnny Chen             std::string oneliner(m_options.m_function_name);
437e9a5627eSJohnny Chen             oneliner += "(frame, wp, internal_dict)";
438b9c1b51eSKate Stone             m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback(
439b9c1b51eSKate Stone                 wp_options, oneliner.c_str());
440b9c1b51eSKate Stone           } else {
441b9c1b51eSKate Stone             m_interpreter.GetScriptInterpreter()
442b9c1b51eSKate Stone                 ->CollectDataForWatchpointCommandCallback(wp_options, result);
443e9a5627eSJohnny Chen           }
444b9c1b51eSKate Stone         } else {
445e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
446e9a5627eSJohnny Chen           if (m_options.m_use_one_liner)
447e9a5627eSJohnny Chen             SetWatchpointCommandCallback(wp_options,
448e9a5627eSJohnny Chen                                          m_options.m_one_liner.c_str());
449e9a5627eSJohnny Chen           else
450b9c1b51eSKate Stone             CollectDataForWatchpointCommandCallback(wp_options, result);
451e9a5627eSJohnny Chen         }
452e9a5627eSJohnny Chen       }
453e9a5627eSJohnny Chen     }
454e9a5627eSJohnny Chen 
455e9a5627eSJohnny Chen     return result.Succeeded();
456e9a5627eSJohnny Chen   }
457e9a5627eSJohnny Chen 
458e9a5627eSJohnny Chen private:
459e9a5627eSJohnny Chen   CommandOptions m_options;
460e9a5627eSJohnny Chen };
461e9a5627eSJohnny Chen 
462b9c1b51eSKate Stone // FIXME: "script-type" needs to have its contents determined dynamically, so
463b9c1b51eSKate Stone // somebody can add a new scripting
464b9c1b51eSKate Stone // language to lldb and have it pickable here without having to change this
465b9c1b51eSKate Stone // enumeration by hand and rebuild lldb proper.
466e9a5627eSJohnny Chen 
467b9c1b51eSKate Stone static OptionEnumValueElement g_script_option_enumeration[4] = {
468b9c1b51eSKate Stone     {eScriptLanguageNone, "command",
469b9c1b51eSKate Stone      "Commands are in the lldb command interpreter language"},
470e9a5627eSJohnny Chen     {eScriptLanguagePython, "python", "Commands are in the Python language."},
471b9c1b51eSKate Stone     {eSortOrderByName, "default-script",
472b9c1b51eSKate Stone      "Commands are in the default scripting language."},
473b9c1b51eSKate Stone     {0, nullptr, nullptr}};
474e9a5627eSJohnny Chen 
475e9a5627eSJohnny Chen OptionDefinition
476b9c1b51eSKate Stone     CommandObjectWatchpointCommandAdd::CommandOptions::g_option_table[] = {
477ac9c3a62SKate Stone         // clang-format off
478ac9c3a62SKate Stone   {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."},
479ac9c3a62SKate Stone   {LLDB_OPT_SET_ALL, false, "stop-on-error",   'e', OptionParser::eRequiredArgument, nullptr, nullptr,                     0, eArgTypeBoolean,        "Specify whether watchpoint command execution should terminate on error."},
480ac9c3a62SKate Stone   {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."},
481ac9c3a62SKate Stone   {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."},
48249bcfd80SEugene Zelenko   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
483ac9c3a62SKate Stone         // clang-format on
484e9a5627eSJohnny Chen };
485e9a5627eSJohnny Chen 
486e9a5627eSJohnny Chen //-------------------------------------------------------------------------
487e9a5627eSJohnny Chen // CommandObjectWatchpointCommandDelete
488e9a5627eSJohnny Chen //-------------------------------------------------------------------------
489e9a5627eSJohnny Chen 
490b9c1b51eSKate Stone class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
491e9a5627eSJohnny Chen public:
492b9c1b51eSKate Stone   CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
493b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "delete",
494e9a5627eSJohnny Chen                             "Delete the set of commands from a watchpoint.",
495b9c1b51eSKate Stone                             nullptr) {
496e9a5627eSJohnny Chen     CommandArgumentEntry arg;
497e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
498e9a5627eSJohnny Chen 
499e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
500e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
501e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
502e9a5627eSJohnny Chen 
503b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
504b9c1b51eSKate Stone     // argument entry.
505e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
506e9a5627eSJohnny Chen 
507e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
508e9a5627eSJohnny Chen     m_arguments.push_back(arg);
509e9a5627eSJohnny Chen   }
510e9a5627eSJohnny Chen 
51149bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandDelete() override = default;
512e9a5627eSJohnny Chen 
513e9a5627eSJohnny Chen protected:
514b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
515e9a5627eSJohnny Chen     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
516e9a5627eSJohnny Chen 
517b9c1b51eSKate Stone     if (target == nullptr) {
518b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
519b9c1b51eSKate Stone                          "watchpoints from which to delete commands");
520e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
521e9a5627eSJohnny Chen       return false;
522e9a5627eSJohnny Chen     }
523e9a5627eSJohnny Chen 
524e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
525e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
526e9a5627eSJohnny Chen 
527b9c1b51eSKate Stone     if (num_watchpoints == 0) {
528e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands deleted");
529e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
530e9a5627eSJohnny Chen       return false;
531e9a5627eSJohnny Chen     }
532e9a5627eSJohnny Chen 
533b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
534b9c1b51eSKate Stone       result.AppendError(
535b9c1b51eSKate Stone           "No watchpoint specified from which to delete the commands");
536e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
537e9a5627eSJohnny Chen       return false;
538e9a5627eSJohnny Chen     }
539e9a5627eSJohnny Chen 
540e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
541b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
542b9c1b51eSKate Stone                                                                valid_wp_ids)) {
543e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
544e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
545e9a5627eSJohnny Chen       return false;
546e9a5627eSJohnny Chen     }
547e9a5627eSJohnny Chen 
548e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
549e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
550b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
551e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
552b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
553e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
554e9a5627eSJohnny Chen         if (wp)
555e9a5627eSJohnny Chen           wp->ClearCallback();
556b9c1b51eSKate Stone       } else {
557b9c1b51eSKate Stone         result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
558e9a5627eSJohnny Chen         result.SetStatus(eReturnStatusFailed);
559e9a5627eSJohnny Chen         return false;
560e9a5627eSJohnny Chen       }
561e9a5627eSJohnny Chen     }
562e9a5627eSJohnny Chen     return result.Succeeded();
563e9a5627eSJohnny Chen   }
564e9a5627eSJohnny Chen };
565e9a5627eSJohnny Chen 
566e9a5627eSJohnny Chen //-------------------------------------------------------------------------
567e9a5627eSJohnny Chen // CommandObjectWatchpointCommandList
568e9a5627eSJohnny Chen //-------------------------------------------------------------------------
569e9a5627eSJohnny Chen 
570b9c1b51eSKate Stone class CommandObjectWatchpointCommandList : public CommandObjectParsed {
571e9a5627eSJohnny Chen public:
572b9c1b51eSKate Stone   CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
573b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "list", "List the script or set of "
574b9c1b51eSKate Stone                                                  "commands to be executed when "
575b9c1b51eSKate Stone                                                  "the watchpoint is hit.",
576b9c1b51eSKate Stone                             nullptr) {
577e9a5627eSJohnny Chen     CommandArgumentEntry arg;
578e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
579e9a5627eSJohnny Chen 
580e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
581e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
582e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
583e9a5627eSJohnny Chen 
584b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
585b9c1b51eSKate Stone     // argument entry.
586e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
587e9a5627eSJohnny Chen 
588e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
589e9a5627eSJohnny Chen     m_arguments.push_back(arg);
590e9a5627eSJohnny Chen   }
591e9a5627eSJohnny Chen 
59249bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandList() override = default;
593e9a5627eSJohnny Chen 
594e9a5627eSJohnny Chen protected:
595b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
596e9a5627eSJohnny Chen     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
597e9a5627eSJohnny Chen 
598b9c1b51eSKate Stone     if (target == nullptr) {
599b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
600b9c1b51eSKate Stone                          "watchpoints for which to list commands");
601e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
602e9a5627eSJohnny Chen       return false;
603e9a5627eSJohnny Chen     }
604e9a5627eSJohnny Chen 
605e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
606e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
607e9a5627eSJohnny Chen 
608b9c1b51eSKate Stone     if (num_watchpoints == 0) {
609e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist for which to list commands");
610e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
611e9a5627eSJohnny Chen       return false;
612e9a5627eSJohnny Chen     }
613e9a5627eSJohnny Chen 
614b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
615b9c1b51eSKate Stone       result.AppendError(
616b9c1b51eSKate Stone           "No watchpoint specified for which to list the commands");
617e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
618e9a5627eSJohnny Chen       return false;
619e9a5627eSJohnny Chen     }
620e9a5627eSJohnny Chen 
621e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
622b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
623b9c1b51eSKate Stone                                                                valid_wp_ids)) {
624e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
625e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
626e9a5627eSJohnny Chen       return false;
627e9a5627eSJohnny Chen     }
628e9a5627eSJohnny Chen 
629e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
630e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
631b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
632e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
633b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
634e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
635e9a5627eSJohnny Chen 
636b9c1b51eSKate Stone         if (wp) {
637e9a5627eSJohnny Chen           const WatchpointOptions *wp_options = wp->GetOptions();
638b9c1b51eSKate Stone           if (wp_options) {
639e9a5627eSJohnny Chen             // Get the callback baton associated with the current watchpoint.
640e9a5627eSJohnny Chen             const Baton *baton = wp_options->GetBaton();
641b9c1b51eSKate Stone             if (baton) {
642e9a5627eSJohnny Chen               result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
643e9a5627eSJohnny Chen               result.GetOutputStream().IndentMore();
644b9c1b51eSKate Stone               baton->GetDescription(&result.GetOutputStream(),
645b9c1b51eSKate Stone                                     eDescriptionLevelFull);
646e9a5627eSJohnny Chen               result.GetOutputStream().IndentLess();
647b9c1b51eSKate Stone             } else {
648b9c1b51eSKate Stone               result.AppendMessageWithFormat(
649b9c1b51eSKate Stone                   "Watchpoint %u does not have an associated command.\n",
650e9a5627eSJohnny Chen                   cur_wp_id);
651e9a5627eSJohnny Chen             }
652e9a5627eSJohnny Chen           }
653e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusSuccessFinishResult);
654b9c1b51eSKate Stone         } else {
655b9c1b51eSKate Stone           result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
656b9c1b51eSKate Stone                                        cur_wp_id);
657e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusFailed);
658e9a5627eSJohnny Chen         }
659e9a5627eSJohnny Chen       }
660e9a5627eSJohnny Chen     }
661e9a5627eSJohnny Chen 
662e9a5627eSJohnny Chen     return result.Succeeded();
663e9a5627eSJohnny Chen   }
664e9a5627eSJohnny Chen };
665e9a5627eSJohnny Chen 
666e9a5627eSJohnny Chen //-------------------------------------------------------------------------
667e9a5627eSJohnny Chen // CommandObjectWatchpointCommand
668e9a5627eSJohnny Chen //-------------------------------------------------------------------------
669e9a5627eSJohnny Chen 
670b9c1b51eSKate Stone CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
671b9c1b51eSKate Stone     CommandInterpreter &interpreter)
672b9c1b51eSKate Stone     : CommandObjectMultiword(
673b9c1b51eSKate Stone           interpreter, "command",
674b9c1b51eSKate Stone           "Commands for adding, removing and examining LLDB commands "
6757428a18cSKate Stone           "executed when the watchpoint is hit (watchpoint 'commmands').",
676b9c1b51eSKate Stone           "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
677b9c1b51eSKate Stone   CommandObjectSP add_command_object(
678b9c1b51eSKate Stone       new CommandObjectWatchpointCommandAdd(interpreter));
679b9c1b51eSKate Stone   CommandObjectSP delete_command_object(
680b9c1b51eSKate Stone       new CommandObjectWatchpointCommandDelete(interpreter));
681b9c1b51eSKate Stone   CommandObjectSP list_command_object(
682b9c1b51eSKate Stone       new CommandObjectWatchpointCommandList(interpreter));
683e9a5627eSJohnny Chen 
684e9a5627eSJohnny Chen   add_command_object->SetCommandName("watchpoint command add");
685e9a5627eSJohnny Chen   delete_command_object->SetCommandName("watchpoint command delete");
686e9a5627eSJohnny Chen   list_command_object->SetCommandName("watchpoint command list");
687e9a5627eSJohnny Chen 
68803da4cc2SGreg Clayton   LoadSubCommand("add", add_command_object);
68903da4cc2SGreg Clayton   LoadSubCommand("delete", delete_command_object);
69003da4cc2SGreg Clayton   LoadSubCommand("list", list_command_object);
691e9a5627eSJohnny Chen }
692e9a5627eSJohnny Chen 
69349bcfd80SEugene Zelenko CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;
694