1e9a5627eSJohnny Chen //===-- CommandObjectWatchpointCommand.cpp ----------------------*- C++ -*-===//
2e9a5627eSJohnny Chen //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e9a5627eSJohnny Chen //
7e9a5627eSJohnny Chen //===----------------------------------------------------------------------===//
8e9a5627eSJohnny Chen 
949bcfd80SEugene Zelenko #include <vector>
10e9a5627eSJohnny Chen 
11e9a5627eSJohnny Chen #include "CommandObjectWatchpoint.h"
12b9c1b51eSKate Stone #include "CommandObjectWatchpointCommand.h"
13b9c1b51eSKate Stone #include "lldb/Breakpoint/StoppointCallbackContext.h"
14b9c1b51eSKate Stone #include "lldb/Breakpoint/Watchpoint.h"
1544d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
163eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
17e9a5627eSJohnny Chen #include "lldb/Interpreter/CommandInterpreter.h"
18e9a5627eSJohnny Chen #include "lldb/Interpreter/CommandReturnObject.h"
1947cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
20e9a5627eSJohnny Chen #include "lldb/Target/Target.h"
21e9a5627eSJohnny Chen #include "lldb/Target/Thread.h"
22d821c997SPavel Labath #include "lldb/Utility/State.h"
23e9a5627eSJohnny Chen 
24e9a5627eSJohnny Chen using namespace lldb;
25e9a5627eSJohnny Chen using namespace lldb_private;
26e9a5627eSJohnny Chen 
27e9a5627eSJohnny Chen // CommandObjectWatchpointCommandAdd
28e9a5627eSJohnny Chen 
291f0f5b5bSZachary Turner // FIXME: "script-type" needs to have its contents determined dynamically, so
301f0f5b5bSZachary Turner // somebody can add a new scripting
311f0f5b5bSZachary Turner // language to lldb and have it pickable here without having to change this
321f0f5b5bSZachary Turner // enumeration by hand and rebuild lldb proper.
331f0f5b5bSZachary Turner 
348fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_option_enumeration[] = {
351f0f5b5bSZachary Turner     {eScriptLanguageNone, "command",
361f0f5b5bSZachary Turner      "Commands are in the lldb command interpreter language"},
371f0f5b5bSZachary Turner     {eScriptLanguagePython, "python", "Commands are in the Python language."},
381f0f5b5bSZachary Turner     {eSortOrderByName, "default-script",
398fe53c49STatyana Krasnukha      "Commands are in the default scripting language."} };
401f0f5b5bSZachary Turner 
418fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptOptionEnum() {
428fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_option_enumeration);
438fe53c49STatyana Krasnukha }
448fe53c49STatyana Krasnukha 
458fe53c49STatyana Krasnukha static constexpr OptionDefinition g_watchpoint_command_add_options[] = {
46*60bd7a9cSRaphael Isemann #define LLDB_OPTIONS_watchpoint_command_add
47*60bd7a9cSRaphael Isemann #include "CommandOptions.inc"
481f0f5b5bSZachary Turner };
491f0f5b5bSZachary Turner 
50b9c1b51eSKate Stone class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
51b9c1b51eSKate Stone                                           public IOHandlerDelegateMultiline {
52e9a5627eSJohnny Chen public:
537428a18cSKate Stone   CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
54b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "add",
55b9c1b51eSKate Stone                             "Add a set of LLDB commands to a watchpoint, to be "
56b9c1b51eSKate Stone                             "executed whenever the watchpoint is hit.",
57b9c1b51eSKate Stone                             nullptr),
58b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE",
59b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
60b9c1b51eSKate Stone         m_options() {
61e9a5627eSJohnny Chen     SetHelpLong(
62ea671fbdSKate Stone         R"(
63ea671fbdSKate Stone General information about entering watchpoint commands
64ea671fbdSKate Stone ------------------------------------------------------
65ea671fbdSKate Stone 
66b9c1b51eSKate Stone )"
67b9c1b51eSKate Stone         "This command will prompt for commands to be executed when the specified \
68ea671fbdSKate Stone watchpoint is hit.  Each command is typed on its own line following the '> ' \
69b9c1b51eSKate Stone prompt until 'DONE' is entered."
70b9c1b51eSKate Stone         R"(
71ea671fbdSKate Stone 
72b9c1b51eSKate Stone )"
73b9c1b51eSKate Stone         "Syntactic errors may not be detected when initially entered, and many \
74ea671fbdSKate Stone malformed commands can silently fail when executed.  If your watchpoint commands \
75b9c1b51eSKate Stone do not appear to be executing, double-check the command syntax."
76b9c1b51eSKate Stone         R"(
77ea671fbdSKate Stone 
78b9c1b51eSKate Stone )"
79b9c1b51eSKate Stone         "Note: You may enter any debugger command exactly as you would at the debugger \
80ea671fbdSKate Stone prompt.  There is no limit to the number of commands supplied, but do NOT enter \
81b9c1b51eSKate Stone more than one command per line."
82b9c1b51eSKate Stone         R"(
83ea671fbdSKate Stone 
84ea671fbdSKate Stone Special information about PYTHON watchpoint commands
85ea671fbdSKate Stone ----------------------------------------------------
86ea671fbdSKate Stone 
87b9c1b51eSKate Stone )"
88b9c1b51eSKate Stone         "You may enter either one or more lines of Python, including function \
89ea671fbdSKate Stone definitions or calls to functions that will have been imported by the time \
90ea671fbdSKate Stone the code executes.  Single line watchpoint commands will be interpreted 'as is' \
91ea671fbdSKate Stone when the watchpoint is hit.  Multiple lines of Python will be wrapped in a \
92b9c1b51eSKate Stone generated function, and a call to the function will be attached to the watchpoint."
93b9c1b51eSKate Stone         R"(
94ea671fbdSKate Stone 
95ea671fbdSKate Stone This auto-generated function is passed in three arguments:
96ea671fbdSKate Stone 
97ea671fbdSKate Stone     frame:  an lldb.SBFrame object for the frame which hit the watchpoint.
98ea671fbdSKate Stone 
99ea671fbdSKate Stone     wp:     the watchpoint that was hit.
100ea671fbdSKate Stone 
101b9c1b51eSKate Stone )"
102b9c1b51eSKate Stone         "When specifying a python function with the --python-function option, you need \
103b9c1b51eSKate Stone to supply the function name prepended by the module name:"
104b9c1b51eSKate Stone         R"(
105ea671fbdSKate Stone 
106ea671fbdSKate Stone     --python-function myutils.watchpoint_callback
107ea671fbdSKate Stone 
108ea671fbdSKate Stone The function itself must have the following prototype:
109ea671fbdSKate Stone 
110ea671fbdSKate Stone def watchpoint_callback(frame, wp):
111ea671fbdSKate Stone   # Your code goes here
112ea671fbdSKate Stone 
113b9c1b51eSKate Stone )"
114b9c1b51eSKate Stone         "The arguments are the same as the arguments passed to generated functions as \
115ea671fbdSKate Stone described above.  Note that the global variable 'lldb.frame' will NOT be updated when \
116ea671fbdSKate Stone this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
117ea671fbdSKate Stone can get you to the thread via frame.GetThread(), the thread can get you to the \
118ea671fbdSKate Stone process via thread.GetProcess(), and the process can get you back to the target \
119b9c1b51eSKate Stone via process.GetTarget()."
120b9c1b51eSKate Stone         R"(
121ea671fbdSKate Stone 
122b9c1b51eSKate Stone )"
123b9c1b51eSKate Stone         "Important Note: As Python code gets collected into functions, access to global \
124ea671fbdSKate Stone variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
125b9c1b51eSKate Stone Python syntax, including indentation, when entering Python watchpoint commands."
126b9c1b51eSKate Stone         R"(
127ea671fbdSKate Stone 
128ea671fbdSKate Stone Example Python one-line watchpoint command:
129ea671fbdSKate Stone 
130ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
131ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
132ea671fbdSKate Stone > print "Hit this watchpoint!"
133ea671fbdSKate Stone > DONE
134ea671fbdSKate Stone 
135ea671fbdSKate Stone As a convenience, this also works for a short Python one-liner:
136ea671fbdSKate Stone 
137ea671fbdSKate Stone (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
138ea671fbdSKate Stone (lldb) run
139ea671fbdSKate Stone Launching '.../a.out'  (x86_64)
140ea671fbdSKate Stone (lldb) Fri Sep 10 12:17:45 2010
141ea671fbdSKate Stone Process 21778 Stopped
142ea671fbdSKate Stone * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
143ea671fbdSKate Stone   36
144ea671fbdSKate Stone   37   	int c(int val)
145ea671fbdSKate Stone   38   	{
146ea671fbdSKate Stone   39 ->	    return val + 3;
147ea671fbdSKate Stone   40   	}
148ea671fbdSKate Stone   41
149ea671fbdSKate Stone   42   	int main (int argc, char const *argv[])
150ea671fbdSKate Stone 
151ea671fbdSKate Stone Example multiple line Python watchpoint command, using function definition:
152ea671fbdSKate Stone 
153ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
154ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
155ea671fbdSKate Stone > def watchpoint_output (wp_no):
156ea671fbdSKate Stone >     out_string = "Hit watchpoint number " + repr (wp_no)
157ea671fbdSKate Stone >     print out_string
158ea671fbdSKate Stone >     return True
159ea671fbdSKate Stone > watchpoint_output (1)
160ea671fbdSKate Stone > DONE
161ea671fbdSKate Stone 
162ea671fbdSKate Stone Example multiple line Python watchpoint command, using 'loose' Python:
163ea671fbdSKate Stone 
164ea671fbdSKate Stone (lldb) watchpoint command add -s p 1
165ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
166ea671fbdSKate Stone > global wp_count
167ea671fbdSKate Stone > wp_count = wp_count + 1
168ea671fbdSKate Stone > print "Hit this watchpoint " + repr(wp_count) + " times!"
169ea671fbdSKate Stone > DONE
170ea671fbdSKate Stone 
171b9c1b51eSKate Stone )"
172b9c1b51eSKate Stone         "In this case, since there is a reference to a global variable, \
173ea671fbdSKate Stone 'wp_count', you will also need to make sure 'wp_count' exists and is \
174b9c1b51eSKate Stone initialized:"
175b9c1b51eSKate Stone         R"(
176ea671fbdSKate Stone 
177ea671fbdSKate Stone (lldb) script
178ea671fbdSKate Stone >>> wp_count = 0
179ea671fbdSKate Stone >>> quit()
180ea671fbdSKate Stone 
181b9c1b51eSKate Stone )"
182b9c1b51eSKate Stone         "Final Note: A warning that no watchpoint command was generated when there \
183b9c1b51eSKate Stone are no syntax errors may indicate that a function was declared but never called.");
184e9a5627eSJohnny Chen 
185e9a5627eSJohnny Chen     CommandArgumentEntry arg;
186e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
187e9a5627eSJohnny Chen 
188e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
189e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
190e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
191e9a5627eSJohnny Chen 
192b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
193b9c1b51eSKate Stone     // argument entry.
194e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
195e9a5627eSJohnny Chen 
196e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
197e9a5627eSJohnny Chen     m_arguments.push_back(arg);
198e9a5627eSJohnny Chen   }
199e9a5627eSJohnny Chen 
20049bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandAdd() override = default;
201e9a5627eSJohnny Chen 
202b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
203e9a5627eSJohnny Chen 
2040affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
20544d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
2060affb582SDave Lee     if (output_sp && interactive) {
207b9c1b51eSKate Stone       output_sp->PutCString(
208b9c1b51eSKate Stone           "Enter your debugger command(s).  Type 'DONE' to end.\n");
20944d93782SGreg Clayton       output_sp->Flush();
21044d93782SGreg Clayton     }
21144d93782SGreg Clayton   }
21244d93782SGreg Clayton 
213b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
214b9c1b51eSKate Stone                               std::string &line) override {
21544d93782SGreg Clayton     io_handler.SetIsDone(true);
21644d93782SGreg Clayton 
217b9c1b51eSKate Stone     // The WatchpointOptions object is owned by the watchpoint or watchpoint
218b9c1b51eSKate Stone     // location
219b9c1b51eSKate Stone     WatchpointOptions *wp_options =
220b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
221b9c1b51eSKate Stone     if (wp_options) {
222d5b44036SJonas Devlieghere       std::unique_ptr<WatchpointOptions::CommandData> data_up(
223b9c1b51eSKate Stone           new WatchpointOptions::CommandData());
224d5b44036SJonas Devlieghere       if (data_up) {
225d5b44036SJonas Devlieghere         data_up->user_source.SplitIntoLines(line);
2264e4fbe82SZachary Turner         auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
227d5b44036SJonas Devlieghere             std::move(data_up));
22844d93782SGreg Clayton         wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
22944d93782SGreg Clayton       }
23044d93782SGreg Clayton     }
23144d93782SGreg Clayton   }
23244d93782SGreg Clayton 
233b9c1b51eSKate Stone   void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
234b9c1b51eSKate Stone                                                CommandReturnObject &result) {
235b9c1b51eSKate Stone     m_interpreter.GetLLDBCommandsFromIOHandler(
236b9c1b51eSKate Stone         "> ",        // Prompt
23744d93782SGreg Clayton         *this,       // IOHandlerDelegate
23844d93782SGreg Clayton         true,        // Run IOHandler in async mode
239b9c1b51eSKate Stone         wp_options); // Baton for the "io_handler" that will be passed back into
240b9c1b51eSKate Stone                      // our IOHandlerDelegate functions
241e9a5627eSJohnny Chen   }
242e9a5627eSJohnny Chen 
243e9a5627eSJohnny Chen   /// Set a one-liner as the callback for the watchpoint.
244b9c1b51eSKate Stone   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
245b9c1b51eSKate Stone                                     const char *oneliner) {
246d5b44036SJonas Devlieghere     std::unique_ptr<WatchpointOptions::CommandData> data_up(
247b9c1b51eSKate Stone         new WatchpointOptions::CommandData());
248e9a5627eSJohnny Chen 
24905097246SAdrian Prantl     // It's necessary to set both user_source and script_source to the
25005097246SAdrian Prantl     // oneliner. The former is used to generate callback description (as in
25105097246SAdrian Prantl     // watchpoint command list) while the latter is used for Python to
25205097246SAdrian Prantl     // interpret during the actual callback.
253d5b44036SJonas Devlieghere     data_up->user_source.AppendString(oneliner);
254d5b44036SJonas Devlieghere     data_up->script_source.assign(oneliner);
255d5b44036SJonas Devlieghere     data_up->stop_on_error = m_options.m_stop_on_error;
256e9a5627eSJohnny Chen 
2574e4fbe82SZachary Turner     auto baton_sp =
258d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
259e9a5627eSJohnny Chen     wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
260e9a5627eSJohnny Chen   }
261e9a5627eSJohnny Chen 
262e9a5627eSJohnny Chen   static bool
263e9a5627eSJohnny Chen   WatchpointOptionsCallbackFunction(void *baton,
264e9a5627eSJohnny Chen                                     StoppointCallbackContext *context,
265b9c1b51eSKate Stone                                     lldb::user_id_t watch_id) {
266e9a5627eSJohnny Chen     bool ret_value = true;
26749bcfd80SEugene Zelenko     if (baton == nullptr)
268e9a5627eSJohnny Chen       return true;
269e9a5627eSJohnny Chen 
270b9c1b51eSKate Stone     WatchpointOptions::CommandData *data =
271b9c1b51eSKate Stone         (WatchpointOptions::CommandData *)baton;
272e9a5627eSJohnny Chen     StringList &commands = data->user_source;
273e9a5627eSJohnny Chen 
274b9c1b51eSKate Stone     if (commands.GetSize() > 0) {
275e9a5627eSJohnny Chen       ExecutionContext exe_ctx(context->exe_ctx_ref);
276e9a5627eSJohnny Chen       Target *target = exe_ctx.GetTargetPtr();
277b9c1b51eSKate Stone       if (target) {
278e9a5627eSJohnny Chen         CommandReturnObject result;
279e9a5627eSJohnny Chen         Debugger &debugger = target->GetDebugger();
280b9c1b51eSKate Stone         // Rig up the results secondary output stream to the debugger's, so the
28105097246SAdrian Prantl         // output will come out synchronously if the debugger is set up that
28205097246SAdrian Prantl         // way.
283e9a5627eSJohnny Chen 
284e9a5627eSJohnny Chen         StreamSP output_stream(debugger.GetAsyncOutputStream());
285e9a5627eSJohnny Chen         StreamSP error_stream(debugger.GetAsyncErrorStream());
286e9a5627eSJohnny Chen         result.SetImmediateOutputStream(output_stream);
287e9a5627eSJohnny Chen         result.SetImmediateErrorStream(error_stream);
288e9a5627eSJohnny Chen 
28926c7bf93SJim Ingham         CommandInterpreterRunOptions options;
29026c7bf93SJim Ingham         options.SetStopOnContinue(true);
29126c7bf93SJim Ingham         options.SetStopOnError(data->stop_on_error);
29226c7bf93SJim Ingham         options.SetEchoCommands(false);
29326c7bf93SJim Ingham         options.SetPrintResults(true);
294c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
29526c7bf93SJim Ingham         options.SetAddToHistory(false);
296e9a5627eSJohnny Chen 
297b9c1b51eSKate Stone         debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
298b9c1b51eSKate Stone                                                         options, result);
299e9a5627eSJohnny Chen         result.GetImmediateOutputStream()->Flush();
300e9a5627eSJohnny Chen         result.GetImmediateErrorStream()->Flush();
301e9a5627eSJohnny Chen       }
302e9a5627eSJohnny Chen     }
303e9a5627eSJohnny Chen     return ret_value;
304e9a5627eSJohnny Chen   }
305e9a5627eSJohnny Chen 
306b9c1b51eSKate Stone   class CommandOptions : public Options {
307e9a5627eSJohnny Chen   public:
308b9c1b51eSKate Stone     CommandOptions()
309b9c1b51eSKate Stone         : Options(), m_use_commands(false), m_use_script_language(false),
310b9c1b51eSKate Stone           m_script_language(eScriptLanguageNone), m_use_one_liner(false),
311b9c1b51eSKate Stone           m_one_liner(), m_function_name() {}
312e9a5627eSJohnny Chen 
31349bcfd80SEugene Zelenko     ~CommandOptions() override = default;
314e9a5627eSJohnny Chen 
31597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
316b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
31797206d57SZachary Turner       Status error;
3183bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
319e9a5627eSJohnny Chen 
320b9c1b51eSKate Stone       switch (short_option) {
321e9a5627eSJohnny Chen       case 'o':
322e9a5627eSJohnny Chen         m_use_one_liner = true;
323e9a5627eSJohnny Chen         m_one_liner = option_arg;
324e9a5627eSJohnny Chen         break;
325e9a5627eSJohnny Chen 
326e9a5627eSJohnny Chen       case 's':
32747cbf4a0SPavel Labath         m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
328fe11483bSZachary Turner             option_arg, GetDefinitions()[option_idx].enum_values,
329fe11483bSZachary Turner             eScriptLanguageNone, error);
330e9a5627eSJohnny Chen 
331b9c1b51eSKate Stone         m_use_script_language = (m_script_language == eScriptLanguagePython ||
332b9c1b51eSKate Stone                                  m_script_language == eScriptLanguageDefault);
333e9a5627eSJohnny Chen         break;
334e9a5627eSJohnny Chen 
335b9c1b51eSKate Stone       case 'e': {
336e9a5627eSJohnny Chen         bool success = false;
33747cbf4a0SPavel Labath         m_stop_on_error =
33847cbf4a0SPavel Labath             OptionArgParser::ToBoolean(option_arg, false, &success);
339e9a5627eSJohnny Chen         if (!success)
340b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
341fe11483bSZachary Turner               "invalid value for stop-on-error: \"%s\"",
342fe11483bSZachary Turner               option_arg.str().c_str());
343b9c1b51eSKate Stone       } break;
344e9a5627eSJohnny Chen 
345e9a5627eSJohnny Chen       case 'F':
346e9a5627eSJohnny Chen         m_use_one_liner = false;
347e9a5627eSJohnny Chen         m_use_script_language = true;
348e9a5627eSJohnny Chen         m_function_name.assign(option_arg);
349e9a5627eSJohnny Chen         break;
350e9a5627eSJohnny Chen 
351e9a5627eSJohnny Chen       default:
352e9a5627eSJohnny Chen         break;
353e9a5627eSJohnny Chen       }
354e9a5627eSJohnny Chen       return error;
355e9a5627eSJohnny Chen     }
35649bcfd80SEugene Zelenko 
357b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
358e9a5627eSJohnny Chen       m_use_commands = true;
359e9a5627eSJohnny Chen       m_use_script_language = false;
360e9a5627eSJohnny Chen       m_script_language = eScriptLanguageNone;
361e9a5627eSJohnny Chen 
362e9a5627eSJohnny Chen       m_use_one_liner = false;
363e9a5627eSJohnny Chen       m_stop_on_error = true;
364e9a5627eSJohnny Chen       m_one_liner.clear();
365e9a5627eSJohnny Chen       m_function_name.clear();
366e9a5627eSJohnny Chen     }
367e9a5627eSJohnny Chen 
3681f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
36970602439SZachary Turner       return llvm::makeArrayRef(g_watchpoint_command_add_options);
3701f0f5b5bSZachary Turner     }
371e9a5627eSJohnny Chen 
372e9a5627eSJohnny Chen     // Instance variables to hold the values for command options.
373e9a5627eSJohnny Chen 
374e9a5627eSJohnny Chen     bool m_use_commands;
375e9a5627eSJohnny Chen     bool m_use_script_language;
376e9a5627eSJohnny Chen     lldb::ScriptLanguage m_script_language;
377e9a5627eSJohnny Chen 
378e9a5627eSJohnny Chen     // Instance variables to hold the values for one_liner options.
379e9a5627eSJohnny Chen     bool m_use_one_liner;
380e9a5627eSJohnny Chen     std::string m_one_liner;
381e9a5627eSJohnny Chen     bool m_stop_on_error;
382e9a5627eSJohnny Chen     std::string m_function_name;
383e9a5627eSJohnny Chen   };
384e9a5627eSJohnny Chen 
385e9a5627eSJohnny Chen protected:
386b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
38757179860SJonas Devlieghere     Target *target = GetDebugger().GetSelectedTarget().get();
388e9a5627eSJohnny Chen 
389b9c1b51eSKate Stone     if (target == nullptr) {
390b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
391b9c1b51eSKate Stone                          "watchpoints to which to add commands");
392e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
393e9a5627eSJohnny Chen       return false;
394e9a5627eSJohnny Chen     }
395e9a5627eSJohnny Chen 
396e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
397e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
398e9a5627eSJohnny Chen 
399b9c1b51eSKate Stone     if (num_watchpoints == 0) {
400e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands added");
401e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
402e9a5627eSJohnny Chen       return false;
403e9a5627eSJohnny Chen     }
404e9a5627eSJohnny Chen 
405b9c1b51eSKate Stone     if (!m_options.m_use_script_language &&
406b9c1b51eSKate Stone         !m_options.m_function_name.empty()) {
407b9c1b51eSKate Stone       result.AppendError("need to enable scripting to have a function run as a "
408b9c1b51eSKate Stone                          "watchpoint command");
409e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
410e9a5627eSJohnny Chen       return false;
411e9a5627eSJohnny Chen     }
412e9a5627eSJohnny Chen 
413e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
414b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
415b9c1b51eSKate Stone                                                                valid_wp_ids)) {
416e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
417e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
418e9a5627eSJohnny Chen       return false;
419e9a5627eSJohnny Chen     }
420e9a5627eSJohnny Chen 
421e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
422e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
423b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
424e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
425b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
426e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
427e9a5627eSJohnny Chen         // Sanity check wp first.
428b9c1b51eSKate Stone         if (wp == nullptr)
429b9c1b51eSKate Stone           continue;
430e9a5627eSJohnny Chen 
431e9a5627eSJohnny Chen         WatchpointOptions *wp_options = wp->GetOptions();
432e9a5627eSJohnny Chen         // Skip this watchpoint if wp_options is not good.
433b9c1b51eSKate Stone         if (wp_options == nullptr)
434b9c1b51eSKate Stone           continue;
435e9a5627eSJohnny Chen 
43605097246SAdrian Prantl         // If we are using script language, get the script interpreter in order
43705097246SAdrian Prantl         // to set or collect command callback.  Otherwise, call the methods
43805097246SAdrian Prantl         // associated with this object.
439b9c1b51eSKate Stone         if (m_options.m_use_script_language) {
440e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
441b9c1b51eSKate Stone           if (m_options.m_use_one_liner) {
4422b29b432SJonas Devlieghere             GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback(
443b9c1b51eSKate Stone                 wp_options, m_options.m_one_liner.c_str());
444e9a5627eSJohnny Chen           }
44505097246SAdrian Prantl           // Special handling for using a Python function by name instead of
44605097246SAdrian Prantl           // extending the watchpoint callback data structures, we just
44705097246SAdrian Prantl           // automatize what the user would do manually: make their watchpoint
44805097246SAdrian Prantl           // command be a function call
449b9c1b51eSKate Stone           else if (!m_options.m_function_name.empty()) {
450e9a5627eSJohnny Chen             std::string oneliner(m_options.m_function_name);
451e9a5627eSJohnny Chen             oneliner += "(frame, wp, internal_dict)";
4522b29b432SJonas Devlieghere             GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback(
453b9c1b51eSKate Stone                 wp_options, oneliner.c_str());
454b9c1b51eSKate Stone           } else {
4552b29b432SJonas Devlieghere             GetDebugger()
4562b29b432SJonas Devlieghere                 .GetScriptInterpreter()
457b9c1b51eSKate Stone                 ->CollectDataForWatchpointCommandCallback(wp_options, result);
458e9a5627eSJohnny Chen           }
459b9c1b51eSKate Stone         } else {
460e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
461e9a5627eSJohnny Chen           if (m_options.m_use_one_liner)
462e9a5627eSJohnny Chen             SetWatchpointCommandCallback(wp_options,
463e9a5627eSJohnny Chen                                          m_options.m_one_liner.c_str());
464e9a5627eSJohnny Chen           else
465b9c1b51eSKate Stone             CollectDataForWatchpointCommandCallback(wp_options, result);
466e9a5627eSJohnny Chen         }
467e9a5627eSJohnny Chen       }
468e9a5627eSJohnny Chen     }
469e9a5627eSJohnny Chen 
470e9a5627eSJohnny Chen     return result.Succeeded();
471e9a5627eSJohnny Chen   }
472e9a5627eSJohnny Chen 
473e9a5627eSJohnny Chen private:
474e9a5627eSJohnny Chen   CommandOptions m_options;
475e9a5627eSJohnny Chen };
476e9a5627eSJohnny Chen 
477e9a5627eSJohnny Chen // CommandObjectWatchpointCommandDelete
478e9a5627eSJohnny Chen 
479b9c1b51eSKate Stone class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
480e9a5627eSJohnny Chen public:
481b9c1b51eSKate Stone   CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
482b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "delete",
483e9a5627eSJohnny Chen                             "Delete the set of commands from a watchpoint.",
484b9c1b51eSKate Stone                             nullptr) {
485e9a5627eSJohnny Chen     CommandArgumentEntry arg;
486e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
487e9a5627eSJohnny Chen 
488e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
489e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
490e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
491e9a5627eSJohnny Chen 
492b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
493b9c1b51eSKate Stone     // argument entry.
494e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
495e9a5627eSJohnny Chen 
496e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
497e9a5627eSJohnny Chen     m_arguments.push_back(arg);
498e9a5627eSJohnny Chen   }
499e9a5627eSJohnny Chen 
50049bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandDelete() override = default;
501e9a5627eSJohnny Chen 
502e9a5627eSJohnny Chen protected:
503b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
50457179860SJonas Devlieghere     Target *target = GetDebugger().GetSelectedTarget().get();
505e9a5627eSJohnny Chen 
506b9c1b51eSKate Stone     if (target == nullptr) {
507b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
508b9c1b51eSKate Stone                          "watchpoints from which to delete commands");
509e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
510e9a5627eSJohnny Chen       return false;
511e9a5627eSJohnny Chen     }
512e9a5627eSJohnny Chen 
513e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
514e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
515e9a5627eSJohnny Chen 
516b9c1b51eSKate Stone     if (num_watchpoints == 0) {
517e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands deleted");
518e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
519e9a5627eSJohnny Chen       return false;
520e9a5627eSJohnny Chen     }
521e9a5627eSJohnny Chen 
522b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
523b9c1b51eSKate Stone       result.AppendError(
524b9c1b51eSKate Stone           "No watchpoint specified from which to delete the commands");
525e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
526e9a5627eSJohnny Chen       return false;
527e9a5627eSJohnny Chen     }
528e9a5627eSJohnny Chen 
529e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
530b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
531b9c1b51eSKate Stone                                                                valid_wp_ids)) {
532e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
533e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
534e9a5627eSJohnny Chen       return false;
535e9a5627eSJohnny Chen     }
536e9a5627eSJohnny Chen 
537e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
538e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
539b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
540e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
541b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
542e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
543e9a5627eSJohnny Chen         if (wp)
544e9a5627eSJohnny Chen           wp->ClearCallback();
545b9c1b51eSKate Stone       } else {
546b9c1b51eSKate Stone         result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
547e9a5627eSJohnny Chen         result.SetStatus(eReturnStatusFailed);
548e9a5627eSJohnny Chen         return false;
549e9a5627eSJohnny Chen       }
550e9a5627eSJohnny Chen     }
551e9a5627eSJohnny Chen     return result.Succeeded();
552e9a5627eSJohnny Chen   }
553e9a5627eSJohnny Chen };
554e9a5627eSJohnny Chen 
555e9a5627eSJohnny Chen // CommandObjectWatchpointCommandList
556e9a5627eSJohnny Chen 
557b9c1b51eSKate Stone class CommandObjectWatchpointCommandList : public CommandObjectParsed {
558e9a5627eSJohnny Chen public:
559b9c1b51eSKate Stone   CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
560b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "list", "List the script or set of "
561b9c1b51eSKate Stone                                                  "commands to be executed when "
562b9c1b51eSKate Stone                                                  "the watchpoint is hit.",
563b9c1b51eSKate Stone                             nullptr) {
564e9a5627eSJohnny Chen     CommandArgumentEntry arg;
565e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
566e9a5627eSJohnny Chen 
567e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
568e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
569e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
570e9a5627eSJohnny Chen 
571b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
572b9c1b51eSKate Stone     // argument entry.
573e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
574e9a5627eSJohnny Chen 
575e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
576e9a5627eSJohnny Chen     m_arguments.push_back(arg);
577e9a5627eSJohnny Chen   }
578e9a5627eSJohnny Chen 
57949bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandList() override = default;
580e9a5627eSJohnny Chen 
581e9a5627eSJohnny Chen protected:
582b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
58357179860SJonas Devlieghere     Target *target = GetDebugger().GetSelectedTarget().get();
584e9a5627eSJohnny Chen 
585b9c1b51eSKate Stone     if (target == nullptr) {
586b9c1b51eSKate Stone       result.AppendError("There is not a current executable; there are no "
587b9c1b51eSKate Stone                          "watchpoints for which to list commands");
588e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
589e9a5627eSJohnny Chen       return false;
590e9a5627eSJohnny Chen     }
591e9a5627eSJohnny Chen 
592e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
593e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
594e9a5627eSJohnny Chen 
595b9c1b51eSKate Stone     if (num_watchpoints == 0) {
596e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist for which to list commands");
597e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
598e9a5627eSJohnny Chen       return false;
599e9a5627eSJohnny Chen     }
600e9a5627eSJohnny Chen 
601b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
602b9c1b51eSKate Stone       result.AppendError(
603b9c1b51eSKate Stone           "No watchpoint specified for which to list the commands");
604e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
605e9a5627eSJohnny Chen       return false;
606e9a5627eSJohnny Chen     }
607e9a5627eSJohnny Chen 
608e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
609b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
610b9c1b51eSKate Stone                                                                valid_wp_ids)) {
611e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
612e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
613e9a5627eSJohnny Chen       return false;
614e9a5627eSJohnny Chen     }
615e9a5627eSJohnny Chen 
616e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
617e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
618b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
619e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
620b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
621e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
622e9a5627eSJohnny Chen 
623b9c1b51eSKate Stone         if (wp) {
624e9a5627eSJohnny Chen           const WatchpointOptions *wp_options = wp->GetOptions();
625b9c1b51eSKate Stone           if (wp_options) {
626e9a5627eSJohnny Chen             // Get the callback baton associated with the current watchpoint.
627e9a5627eSJohnny Chen             const Baton *baton = wp_options->GetBaton();
628b9c1b51eSKate Stone             if (baton) {
629e9a5627eSJohnny Chen               result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
630e9a5627eSJohnny Chen               result.GetOutputStream().IndentMore();
631b9c1b51eSKate Stone               baton->GetDescription(&result.GetOutputStream(),
632b9c1b51eSKate Stone                                     eDescriptionLevelFull);
633e9a5627eSJohnny Chen               result.GetOutputStream().IndentLess();
634b9c1b51eSKate Stone             } else {
635b9c1b51eSKate Stone               result.AppendMessageWithFormat(
636b9c1b51eSKate Stone                   "Watchpoint %u does not have an associated command.\n",
637e9a5627eSJohnny Chen                   cur_wp_id);
638e9a5627eSJohnny Chen             }
639e9a5627eSJohnny Chen           }
640e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusSuccessFinishResult);
641b9c1b51eSKate Stone         } else {
642b9c1b51eSKate Stone           result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
643b9c1b51eSKate Stone                                        cur_wp_id);
644e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusFailed);
645e9a5627eSJohnny Chen         }
646e9a5627eSJohnny Chen       }
647e9a5627eSJohnny Chen     }
648e9a5627eSJohnny Chen 
649e9a5627eSJohnny Chen     return result.Succeeded();
650e9a5627eSJohnny Chen   }
651e9a5627eSJohnny Chen };
652e9a5627eSJohnny Chen 
653e9a5627eSJohnny Chen // CommandObjectWatchpointCommand
654e9a5627eSJohnny Chen 
655b9c1b51eSKate Stone CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
656b9c1b51eSKate Stone     CommandInterpreter &interpreter)
657b9c1b51eSKate Stone     : CommandObjectMultiword(
658b9c1b51eSKate Stone           interpreter, "command",
659b9c1b51eSKate Stone           "Commands for adding, removing and examining LLDB commands "
6604ebdee0aSBruce Mitchener           "executed when the watchpoint is hit (watchpoint 'commands').",
661b9c1b51eSKate Stone           "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
662b9c1b51eSKate Stone   CommandObjectSP add_command_object(
663b9c1b51eSKate Stone       new CommandObjectWatchpointCommandAdd(interpreter));
664b9c1b51eSKate Stone   CommandObjectSP delete_command_object(
665b9c1b51eSKate Stone       new CommandObjectWatchpointCommandDelete(interpreter));
666b9c1b51eSKate Stone   CommandObjectSP list_command_object(
667b9c1b51eSKate Stone       new CommandObjectWatchpointCommandList(interpreter));
668e9a5627eSJohnny Chen 
669e9a5627eSJohnny Chen   add_command_object->SetCommandName("watchpoint command add");
670e9a5627eSJohnny Chen   delete_command_object->SetCommandName("watchpoint command delete");
671e9a5627eSJohnny Chen   list_command_object->SetCommandName("watchpoint command list");
672e9a5627eSJohnny Chen 
67303da4cc2SGreg Clayton   LoadSubCommand("add", add_command_object);
67403da4cc2SGreg Clayton   LoadSubCommand("delete", delete_command_object);
67503da4cc2SGreg Clayton   LoadSubCommand("list", list_command_object);
676e9a5627eSJohnny Chen }
677e9a5627eSJohnny Chen 
67849bcfd80SEugene Zelenko CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;
679