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 
22e9a5627eSJohnny Chen using namespace lldb;
23e9a5627eSJohnny Chen using namespace lldb_private;
24e9a5627eSJohnny Chen 
251f0f5b5bSZachary Turner // FIXME: "script-type" needs to have its contents determined dynamically, so
26e063ecccSJonas Devlieghere // somebody can add a new scripting language to lldb and have it pickable here
27e063ecccSJonas Devlieghere // without having to change this enumeration by hand and rebuild lldb proper.
288fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_option_enumeration[] = {
29e063ecccSJonas Devlieghere     {
30e063ecccSJonas Devlieghere         eScriptLanguageNone,
31e063ecccSJonas Devlieghere         "command",
32e063ecccSJonas Devlieghere         "Commands are in the lldb command interpreter language",
33e063ecccSJonas Devlieghere     },
34e063ecccSJonas Devlieghere     {
35e063ecccSJonas Devlieghere         eScriptLanguagePython,
36e063ecccSJonas Devlieghere         "python",
37e063ecccSJonas Devlieghere         "Commands are in the Python language.",
38e063ecccSJonas Devlieghere     },
39e063ecccSJonas Devlieghere     {
40*68cb7d85SJonas Devlieghere         eScriptLanguageLua,
41*68cb7d85SJonas Devlieghere         "lua",
42*68cb7d85SJonas Devlieghere         "Commands are in the Python language.",
43*68cb7d85SJonas Devlieghere     },
44*68cb7d85SJonas Devlieghere     {
45e063ecccSJonas Devlieghere         eSortOrderByName,
46e063ecccSJonas Devlieghere         "default-script",
47e063ecccSJonas Devlieghere         "Commands are in the default scripting language.",
48e063ecccSJonas Devlieghere     },
49e063ecccSJonas Devlieghere };
501f0f5b5bSZachary Turner 
518fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptOptionEnum() {
528fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_option_enumeration);
538fe53c49STatyana Krasnukha }
548fe53c49STatyana Krasnukha 
5560bd7a9cSRaphael Isemann #define LLDB_OPTIONS_watchpoint_command_add
5660bd7a9cSRaphael Isemann #include "CommandOptions.inc"
571f0f5b5bSZachary Turner 
58b9c1b51eSKate Stone class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
59b9c1b51eSKate Stone                                           public IOHandlerDelegateMultiline {
60e9a5627eSJohnny Chen public:
617428a18cSKate Stone   CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
62b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "add",
63b9c1b51eSKate Stone                             "Add a set of LLDB commands to a watchpoint, to be "
64b9c1b51eSKate Stone                             "executed whenever the watchpoint is hit.",
6504a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget),
66b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE",
67b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
68b9c1b51eSKate Stone         m_options() {
69e9a5627eSJohnny Chen     SetHelpLong(
70ea671fbdSKate Stone         R"(
71ea671fbdSKate Stone General information about entering watchpoint commands
72ea671fbdSKate Stone ------------------------------------------------------
73ea671fbdSKate Stone 
74b9c1b51eSKate Stone )"
75b9c1b51eSKate Stone         "This command will prompt for commands to be executed when the specified \
76ea671fbdSKate Stone watchpoint is hit.  Each command is typed on its own line following the '> ' \
77b9c1b51eSKate Stone prompt until 'DONE' is entered."
78b9c1b51eSKate Stone         R"(
79ea671fbdSKate Stone 
80b9c1b51eSKate Stone )"
81b9c1b51eSKate Stone         "Syntactic errors may not be detected when initially entered, and many \
82ea671fbdSKate Stone malformed commands can silently fail when executed.  If your watchpoint commands \
83b9c1b51eSKate Stone do not appear to be executing, double-check the command syntax."
84b9c1b51eSKate Stone         R"(
85ea671fbdSKate Stone 
86b9c1b51eSKate Stone )"
87b9c1b51eSKate Stone         "Note: You may enter any debugger command exactly as you would at the debugger \
88ea671fbdSKate Stone prompt.  There is no limit to the number of commands supplied, but do NOT enter \
89b9c1b51eSKate Stone more than one command per line."
90b9c1b51eSKate Stone         R"(
91ea671fbdSKate Stone 
92ea671fbdSKate Stone Special information about PYTHON watchpoint commands
93ea671fbdSKate Stone ----------------------------------------------------
94ea671fbdSKate Stone 
95b9c1b51eSKate Stone )"
96b9c1b51eSKate Stone         "You may enter either one or more lines of Python, including function \
97ea671fbdSKate Stone definitions or calls to functions that will have been imported by the time \
98ea671fbdSKate Stone the code executes.  Single line watchpoint commands will be interpreted 'as is' \
99ea671fbdSKate Stone when the watchpoint is hit.  Multiple lines of Python will be wrapped in a \
100b9c1b51eSKate Stone generated function, and a call to the function will be attached to the watchpoint."
101b9c1b51eSKate Stone         R"(
102ea671fbdSKate Stone 
103ea671fbdSKate Stone This auto-generated function is passed in three arguments:
104ea671fbdSKate Stone 
105ea671fbdSKate Stone     frame:  an lldb.SBFrame object for the frame which hit the watchpoint.
106ea671fbdSKate Stone 
107ea671fbdSKate Stone     wp:     the watchpoint that was hit.
108ea671fbdSKate Stone 
109b9c1b51eSKate Stone )"
110b9c1b51eSKate Stone         "When specifying a python function with the --python-function option, you need \
111b9c1b51eSKate Stone to supply the function name prepended by the module name:"
112b9c1b51eSKate Stone         R"(
113ea671fbdSKate Stone 
114ea671fbdSKate Stone     --python-function myutils.watchpoint_callback
115ea671fbdSKate Stone 
116ea671fbdSKate Stone The function itself must have the following prototype:
117ea671fbdSKate Stone 
118ea671fbdSKate Stone def watchpoint_callback(frame, wp):
119ea671fbdSKate Stone   # Your code goes here
120ea671fbdSKate Stone 
121b9c1b51eSKate Stone )"
122b9c1b51eSKate Stone         "The arguments are the same as the arguments passed to generated functions as \
123ea671fbdSKate Stone described above.  Note that the global variable 'lldb.frame' will NOT be updated when \
124ea671fbdSKate Stone this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
125ea671fbdSKate Stone can get you to the thread via frame.GetThread(), the thread can get you to the \
126ea671fbdSKate Stone process via thread.GetProcess(), and the process can get you back to the target \
127b9c1b51eSKate Stone via process.GetTarget()."
128b9c1b51eSKate Stone         R"(
129ea671fbdSKate Stone 
130b9c1b51eSKate Stone )"
131b9c1b51eSKate Stone         "Important Note: As Python code gets collected into functions, access to global \
132ea671fbdSKate Stone variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
133b9c1b51eSKate Stone Python syntax, including indentation, when entering Python watchpoint commands."
134b9c1b51eSKate Stone         R"(
135ea671fbdSKate Stone 
136ea671fbdSKate Stone Example Python one-line watchpoint command:
137ea671fbdSKate Stone 
138ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
139ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
140ea671fbdSKate Stone > print "Hit this watchpoint!"
141ea671fbdSKate Stone > DONE
142ea671fbdSKate Stone 
143ea671fbdSKate Stone As a convenience, this also works for a short Python one-liner:
144ea671fbdSKate Stone 
145ea671fbdSKate Stone (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
146ea671fbdSKate Stone (lldb) run
147ea671fbdSKate Stone Launching '.../a.out'  (x86_64)
148ea671fbdSKate Stone (lldb) Fri Sep 10 12:17:45 2010
149ea671fbdSKate Stone Process 21778 Stopped
150ea671fbdSKate Stone * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
151ea671fbdSKate Stone   36
152ea671fbdSKate Stone   37   	int c(int val)
153ea671fbdSKate Stone   38   	{
154ea671fbdSKate Stone   39 ->	    return val + 3;
155ea671fbdSKate Stone   40   	}
156ea671fbdSKate Stone   41
157ea671fbdSKate Stone   42   	int main (int argc, char const *argv[])
158ea671fbdSKate Stone 
159ea671fbdSKate Stone Example multiple line Python watchpoint command, using function definition:
160ea671fbdSKate Stone 
161ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
162ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
163ea671fbdSKate Stone > def watchpoint_output (wp_no):
164ea671fbdSKate Stone >     out_string = "Hit watchpoint number " + repr (wp_no)
165ea671fbdSKate Stone >     print out_string
166ea671fbdSKate Stone >     return True
167ea671fbdSKate Stone > watchpoint_output (1)
168ea671fbdSKate Stone > DONE
169ea671fbdSKate Stone 
170ea671fbdSKate Stone Example multiple line Python watchpoint command, using 'loose' Python:
171ea671fbdSKate Stone 
172ea671fbdSKate Stone (lldb) watchpoint command add -s p 1
173ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
174ea671fbdSKate Stone > global wp_count
175ea671fbdSKate Stone > wp_count = wp_count + 1
176ea671fbdSKate Stone > print "Hit this watchpoint " + repr(wp_count) + " times!"
177ea671fbdSKate Stone > DONE
178ea671fbdSKate Stone 
179b9c1b51eSKate Stone )"
180b9c1b51eSKate Stone         "In this case, since there is a reference to a global variable, \
181ea671fbdSKate Stone 'wp_count', you will also need to make sure 'wp_count' exists and is \
182b9c1b51eSKate Stone initialized:"
183b9c1b51eSKate Stone         R"(
184ea671fbdSKate Stone 
185ea671fbdSKate Stone (lldb) script
186ea671fbdSKate Stone >>> wp_count = 0
187ea671fbdSKate Stone >>> quit()
188ea671fbdSKate Stone 
189b9c1b51eSKate Stone )"
190b9c1b51eSKate Stone         "Final Note: A warning that no watchpoint command was generated when there \
191b9c1b51eSKate Stone are no syntax errors may indicate that a function was declared but never called.");
192e9a5627eSJohnny Chen 
193e9a5627eSJohnny Chen     CommandArgumentEntry arg;
194e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
195e9a5627eSJohnny Chen 
196e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
197e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
198e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
199e9a5627eSJohnny Chen 
200b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
201b9c1b51eSKate Stone     // argument entry.
202e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
203e9a5627eSJohnny Chen 
204e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
205e9a5627eSJohnny Chen     m_arguments.push_back(arg);
206e9a5627eSJohnny Chen   }
207e9a5627eSJohnny Chen 
20849bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandAdd() override = default;
209e9a5627eSJohnny Chen 
210b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
211e9a5627eSJohnny Chen 
2120affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
2137ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
2140affb582SDave Lee     if (output_sp && interactive) {
215b9c1b51eSKate Stone       output_sp->PutCString(
216b9c1b51eSKate Stone           "Enter your debugger command(s).  Type 'DONE' to end.\n");
21744d93782SGreg Clayton       output_sp->Flush();
21844d93782SGreg Clayton     }
21944d93782SGreg Clayton   }
22044d93782SGreg Clayton 
221b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
222b9c1b51eSKate Stone                               std::string &line) override {
22344d93782SGreg Clayton     io_handler.SetIsDone(true);
22444d93782SGreg Clayton 
225b9c1b51eSKate Stone     // The WatchpointOptions object is owned by the watchpoint or watchpoint
226b9c1b51eSKate Stone     // location
227b9c1b51eSKate Stone     WatchpointOptions *wp_options =
228b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
229b9c1b51eSKate Stone     if (wp_options) {
230d5b44036SJonas Devlieghere       std::unique_ptr<WatchpointOptions::CommandData> data_up(
231b9c1b51eSKate Stone           new WatchpointOptions::CommandData());
232d5b44036SJonas Devlieghere       if (data_up) {
233d5b44036SJonas Devlieghere         data_up->user_source.SplitIntoLines(line);
2344e4fbe82SZachary Turner         auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
235d5b44036SJonas Devlieghere             std::move(data_up));
23644d93782SGreg Clayton         wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
23744d93782SGreg Clayton       }
23844d93782SGreg Clayton     }
23944d93782SGreg Clayton   }
24044d93782SGreg Clayton 
241b9c1b51eSKate Stone   void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
242b9c1b51eSKate Stone                                                CommandReturnObject &result) {
243b9c1b51eSKate Stone     m_interpreter.GetLLDBCommandsFromIOHandler(
244b9c1b51eSKate Stone         "> ",        // Prompt
24544d93782SGreg Clayton         *this,       // IOHandlerDelegate
24644d93782SGreg Clayton         true,        // Run IOHandler in async mode
247b9c1b51eSKate Stone         wp_options); // Baton for the "io_handler" that will be passed back into
248b9c1b51eSKate Stone                      // our IOHandlerDelegate functions
249e9a5627eSJohnny Chen   }
250e9a5627eSJohnny Chen 
251e9a5627eSJohnny Chen   /// Set a one-liner as the callback for the watchpoint.
252b9c1b51eSKate Stone   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
253b9c1b51eSKate Stone                                     const char *oneliner) {
254d5b44036SJonas Devlieghere     std::unique_ptr<WatchpointOptions::CommandData> data_up(
255b9c1b51eSKate Stone         new WatchpointOptions::CommandData());
256e9a5627eSJohnny Chen 
25705097246SAdrian Prantl     // It's necessary to set both user_source and script_source to the
25805097246SAdrian Prantl     // oneliner. The former is used to generate callback description (as in
25905097246SAdrian Prantl     // watchpoint command list) while the latter is used for Python to
26005097246SAdrian Prantl     // interpret during the actual callback.
261d5b44036SJonas Devlieghere     data_up->user_source.AppendString(oneliner);
262d5b44036SJonas Devlieghere     data_up->script_source.assign(oneliner);
263d5b44036SJonas Devlieghere     data_up->stop_on_error = m_options.m_stop_on_error;
264e9a5627eSJohnny Chen 
2654e4fbe82SZachary Turner     auto baton_sp =
266d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
267e9a5627eSJohnny Chen     wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
268e9a5627eSJohnny Chen   }
269e9a5627eSJohnny Chen 
270e9a5627eSJohnny Chen   static bool
271e9a5627eSJohnny Chen   WatchpointOptionsCallbackFunction(void *baton,
272e9a5627eSJohnny Chen                                     StoppointCallbackContext *context,
273b9c1b51eSKate Stone                                     lldb::user_id_t watch_id) {
274e9a5627eSJohnny Chen     bool ret_value = true;
27549bcfd80SEugene Zelenko     if (baton == nullptr)
276e9a5627eSJohnny Chen       return true;
277e9a5627eSJohnny Chen 
278b9c1b51eSKate Stone     WatchpointOptions::CommandData *data =
279b9c1b51eSKate Stone         (WatchpointOptions::CommandData *)baton;
280e9a5627eSJohnny Chen     StringList &commands = data->user_source;
281e9a5627eSJohnny Chen 
282b9c1b51eSKate Stone     if (commands.GetSize() > 0) {
283e9a5627eSJohnny Chen       ExecutionContext exe_ctx(context->exe_ctx_ref);
284e9a5627eSJohnny Chen       Target *target = exe_ctx.GetTargetPtr();
285b9c1b51eSKate Stone       if (target) {
286e9a5627eSJohnny Chen         CommandReturnObject result;
287e9a5627eSJohnny Chen         Debugger &debugger = target->GetDebugger();
288b9c1b51eSKate Stone         // Rig up the results secondary output stream to the debugger's, so the
28905097246SAdrian Prantl         // output will come out synchronously if the debugger is set up that
29005097246SAdrian Prantl         // way.
291e9a5627eSJohnny Chen 
292e9a5627eSJohnny Chen         StreamSP output_stream(debugger.GetAsyncOutputStream());
293e9a5627eSJohnny Chen         StreamSP error_stream(debugger.GetAsyncErrorStream());
294e9a5627eSJohnny Chen         result.SetImmediateOutputStream(output_stream);
295e9a5627eSJohnny Chen         result.SetImmediateErrorStream(error_stream);
296e9a5627eSJohnny Chen 
29726c7bf93SJim Ingham         CommandInterpreterRunOptions options;
29826c7bf93SJim Ingham         options.SetStopOnContinue(true);
29926c7bf93SJim Ingham         options.SetStopOnError(data->stop_on_error);
30026c7bf93SJim Ingham         options.SetEchoCommands(false);
30126c7bf93SJim Ingham         options.SetPrintResults(true);
302c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
30326c7bf93SJim Ingham         options.SetAddToHistory(false);
304e9a5627eSJohnny Chen 
305b9c1b51eSKate Stone         debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
306b9c1b51eSKate Stone                                                         options, result);
307e9a5627eSJohnny Chen         result.GetImmediateOutputStream()->Flush();
308e9a5627eSJohnny Chen         result.GetImmediateErrorStream()->Flush();
309e9a5627eSJohnny Chen       }
310e9a5627eSJohnny Chen     }
311e9a5627eSJohnny Chen     return ret_value;
312e9a5627eSJohnny Chen   }
313e9a5627eSJohnny Chen 
314b9c1b51eSKate Stone   class CommandOptions : public Options {
315e9a5627eSJohnny Chen   public:
316b9c1b51eSKate Stone     CommandOptions()
317b9c1b51eSKate Stone         : Options(), m_use_commands(false), m_use_script_language(false),
318b9c1b51eSKate Stone           m_script_language(eScriptLanguageNone), m_use_one_liner(false),
319b9c1b51eSKate Stone           m_one_liner(), m_function_name() {}
320e9a5627eSJohnny Chen 
32149bcfd80SEugene Zelenko     ~CommandOptions() override = default;
322e9a5627eSJohnny Chen 
32397206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
324b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
32597206d57SZachary Turner       Status error;
3263bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
327e9a5627eSJohnny Chen 
328b9c1b51eSKate Stone       switch (short_option) {
329e9a5627eSJohnny Chen       case 'o':
330e9a5627eSJohnny Chen         m_use_one_liner = true;
331e9a5627eSJohnny Chen         m_one_liner = option_arg;
332e9a5627eSJohnny Chen         break;
333e9a5627eSJohnny Chen 
334e9a5627eSJohnny Chen       case 's':
33547cbf4a0SPavel Labath         m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
336fe11483bSZachary Turner             option_arg, GetDefinitions()[option_idx].enum_values,
337fe11483bSZachary Turner             eScriptLanguageNone, error);
338e9a5627eSJohnny Chen 
339*68cb7d85SJonas Devlieghere         switch (m_script_language) {
340*68cb7d85SJonas Devlieghere         case eScriptLanguagePython:
341*68cb7d85SJonas Devlieghere         case eScriptLanguageLua:
342*68cb7d85SJonas Devlieghere           m_use_script_language = true;
343*68cb7d85SJonas Devlieghere           break;
344*68cb7d85SJonas Devlieghere         case eScriptLanguageNone:
345*68cb7d85SJonas Devlieghere         case eScriptLanguageUnknown:
346*68cb7d85SJonas Devlieghere           m_use_script_language = false;
347*68cb7d85SJonas Devlieghere           break;
348*68cb7d85SJonas Devlieghere         }
349e9a5627eSJohnny Chen         break;
350e9a5627eSJohnny Chen 
351b9c1b51eSKate Stone       case 'e': {
352e9a5627eSJohnny Chen         bool success = false;
35347cbf4a0SPavel Labath         m_stop_on_error =
35447cbf4a0SPavel Labath             OptionArgParser::ToBoolean(option_arg, false, &success);
355e9a5627eSJohnny Chen         if (!success)
356b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
357fe11483bSZachary Turner               "invalid value for stop-on-error: \"%s\"",
358fe11483bSZachary Turner               option_arg.str().c_str());
359b9c1b51eSKate Stone       } break;
360e9a5627eSJohnny Chen 
361e9a5627eSJohnny Chen       case 'F':
362e9a5627eSJohnny Chen         m_use_one_liner = false;
363e9a5627eSJohnny Chen         m_function_name.assign(option_arg);
364e9a5627eSJohnny Chen         break;
365e9a5627eSJohnny Chen 
366e9a5627eSJohnny Chen       default:
36736162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
368e9a5627eSJohnny Chen       }
369e9a5627eSJohnny Chen       return error;
370e9a5627eSJohnny Chen     }
37149bcfd80SEugene Zelenko 
372b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
373e9a5627eSJohnny Chen       m_use_commands = true;
374e9a5627eSJohnny Chen       m_use_script_language = false;
375e9a5627eSJohnny Chen       m_script_language = eScriptLanguageNone;
376e9a5627eSJohnny Chen 
377e9a5627eSJohnny Chen       m_use_one_liner = false;
378e9a5627eSJohnny Chen       m_stop_on_error = true;
379e9a5627eSJohnny Chen       m_one_liner.clear();
380e9a5627eSJohnny Chen       m_function_name.clear();
381e9a5627eSJohnny Chen     }
382e9a5627eSJohnny Chen 
3831f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
38470602439SZachary Turner       return llvm::makeArrayRef(g_watchpoint_command_add_options);
3851f0f5b5bSZachary Turner     }
386e9a5627eSJohnny Chen 
387e9a5627eSJohnny Chen     // Instance variables to hold the values for command options.
388e9a5627eSJohnny Chen 
389e9a5627eSJohnny Chen     bool m_use_commands;
390e9a5627eSJohnny Chen     bool m_use_script_language;
391e9a5627eSJohnny Chen     lldb::ScriptLanguage m_script_language;
392e9a5627eSJohnny Chen 
393e9a5627eSJohnny Chen     // Instance variables to hold the values for one_liner options.
394e9a5627eSJohnny Chen     bool m_use_one_liner;
395e9a5627eSJohnny Chen     std::string m_one_liner;
396e9a5627eSJohnny Chen     bool m_stop_on_error;
397e9a5627eSJohnny Chen     std::string m_function_name;
398e9a5627eSJohnny Chen   };
399e9a5627eSJohnny Chen 
400e9a5627eSJohnny Chen protected:
401b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
40204a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
403e9a5627eSJohnny Chen 
404e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
405e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
406e9a5627eSJohnny Chen 
407b9c1b51eSKate Stone     if (num_watchpoints == 0) {
408e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands added");
409e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
410e9a5627eSJohnny Chen       return false;
411e9a5627eSJohnny Chen     }
412e9a5627eSJohnny Chen 
413*68cb7d85SJonas Devlieghere     if (!m_options.m_function_name.empty()) {
414*68cb7d85SJonas Devlieghere       if (!m_options.m_use_script_language) {
415*68cb7d85SJonas Devlieghere         m_options.m_script_language = GetDebugger().GetScriptLanguage();
416*68cb7d85SJonas Devlieghere         m_options.m_use_script_language = true;
417*68cb7d85SJonas Devlieghere       }
418e9a5627eSJohnny Chen     }
419e9a5627eSJohnny Chen 
420e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
421b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
422b9c1b51eSKate Stone                                                                valid_wp_ids)) {
423e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
424e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
425e9a5627eSJohnny Chen       return false;
426e9a5627eSJohnny Chen     }
427e9a5627eSJohnny Chen 
428e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
429e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
430b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
431e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
432b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
433e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
434e9a5627eSJohnny Chen         // Sanity check wp first.
435b9c1b51eSKate Stone         if (wp == nullptr)
436b9c1b51eSKate Stone           continue;
437e9a5627eSJohnny Chen 
438e9a5627eSJohnny Chen         WatchpointOptions *wp_options = wp->GetOptions();
439e9a5627eSJohnny Chen         // Skip this watchpoint if wp_options is not good.
440b9c1b51eSKate Stone         if (wp_options == nullptr)
441b9c1b51eSKate Stone           continue;
442e9a5627eSJohnny Chen 
44305097246SAdrian Prantl         // If we are using script language, get the script interpreter in order
44405097246SAdrian Prantl         // to set or collect command callback.  Otherwise, call the methods
44505097246SAdrian Prantl         // associated with this object.
446b9c1b51eSKate Stone         if (m_options.m_use_script_language) {
447*68cb7d85SJonas Devlieghere           ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(
448*68cb7d85SJonas Devlieghere               /*can_create=*/true, m_options.m_script_language);
449e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
450b9c1b51eSKate Stone           if (m_options.m_use_one_liner) {
451*68cb7d85SJonas Devlieghere             script_interp->SetWatchpointCommandCallback(
452b9c1b51eSKate Stone                 wp_options, m_options.m_one_liner.c_str());
453e9a5627eSJohnny Chen           }
45405097246SAdrian Prantl           // Special handling for using a Python function by name instead of
45505097246SAdrian Prantl           // extending the watchpoint callback data structures, we just
45605097246SAdrian Prantl           // automatize what the user would do manually: make their watchpoint
45705097246SAdrian Prantl           // command be a function call
458b9c1b51eSKate Stone           else if (!m_options.m_function_name.empty()) {
459e9a5627eSJohnny Chen             std::string oneliner(m_options.m_function_name);
460e9a5627eSJohnny Chen             oneliner += "(frame, wp, internal_dict)";
461*68cb7d85SJonas Devlieghere             script_interp->SetWatchpointCommandCallback(
462b9c1b51eSKate Stone                 wp_options, oneliner.c_str());
463b9c1b51eSKate Stone           } else {
464*68cb7d85SJonas Devlieghere             script_interp->CollectDataForWatchpointCommandCallback(wp_options,
465*68cb7d85SJonas Devlieghere                                                                    result);
466e9a5627eSJohnny Chen           }
467b9c1b51eSKate Stone         } else {
468e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
469e9a5627eSJohnny Chen           if (m_options.m_use_one_liner)
470e9a5627eSJohnny Chen             SetWatchpointCommandCallback(wp_options,
471e9a5627eSJohnny Chen                                          m_options.m_one_liner.c_str());
472e9a5627eSJohnny Chen           else
473b9c1b51eSKate Stone             CollectDataForWatchpointCommandCallback(wp_options, result);
474e9a5627eSJohnny Chen         }
475e9a5627eSJohnny Chen       }
476e9a5627eSJohnny Chen     }
477e9a5627eSJohnny Chen 
478e9a5627eSJohnny Chen     return result.Succeeded();
479e9a5627eSJohnny Chen   }
480e9a5627eSJohnny Chen 
481e9a5627eSJohnny Chen private:
482e9a5627eSJohnny Chen   CommandOptions m_options;
483e9a5627eSJohnny Chen };
484e9a5627eSJohnny Chen 
485e9a5627eSJohnny Chen // CommandObjectWatchpointCommandDelete
486e9a5627eSJohnny Chen 
487b9c1b51eSKate Stone class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
488e9a5627eSJohnny Chen public:
489b9c1b51eSKate Stone   CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
490b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "delete",
491e9a5627eSJohnny Chen                             "Delete the set of commands from a watchpoint.",
49204a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget) {
493e9a5627eSJohnny Chen     CommandArgumentEntry arg;
494e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
495e9a5627eSJohnny Chen 
496e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
497e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
498e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
499e9a5627eSJohnny Chen 
500b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
501b9c1b51eSKate Stone     // argument entry.
502e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
503e9a5627eSJohnny Chen 
504e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
505e9a5627eSJohnny Chen     m_arguments.push_back(arg);
506e9a5627eSJohnny Chen   }
507e9a5627eSJohnny Chen 
50849bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandDelete() override = default;
509e9a5627eSJohnny Chen 
510e9a5627eSJohnny Chen protected:
511b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
51204a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
513e9a5627eSJohnny Chen 
514e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
515e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
516e9a5627eSJohnny Chen 
517b9c1b51eSKate Stone     if (num_watchpoints == 0) {
518e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands deleted");
519e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
520e9a5627eSJohnny Chen       return false;
521e9a5627eSJohnny Chen     }
522e9a5627eSJohnny Chen 
523b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
524b9c1b51eSKate Stone       result.AppendError(
525b9c1b51eSKate Stone           "No watchpoint specified from which to delete the commands");
526e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
527e9a5627eSJohnny Chen       return false;
528e9a5627eSJohnny Chen     }
529e9a5627eSJohnny Chen 
530e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
531b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
532b9c1b51eSKate Stone                                                                valid_wp_ids)) {
533e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
534e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
535e9a5627eSJohnny Chen       return false;
536e9a5627eSJohnny Chen     }
537e9a5627eSJohnny Chen 
538e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
539e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
540b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
541e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
542b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
543e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
544e9a5627eSJohnny Chen         if (wp)
545e9a5627eSJohnny Chen           wp->ClearCallback();
546b9c1b51eSKate Stone       } else {
547b9c1b51eSKate Stone         result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
548e9a5627eSJohnny Chen         result.SetStatus(eReturnStatusFailed);
549e9a5627eSJohnny Chen         return false;
550e9a5627eSJohnny Chen       }
551e9a5627eSJohnny Chen     }
552e9a5627eSJohnny Chen     return result.Succeeded();
553e9a5627eSJohnny Chen   }
554e9a5627eSJohnny Chen };
555e9a5627eSJohnny Chen 
556e9a5627eSJohnny Chen // CommandObjectWatchpointCommandList
557e9a5627eSJohnny Chen 
558b9c1b51eSKate Stone class CommandObjectWatchpointCommandList : public CommandObjectParsed {
559e9a5627eSJohnny Chen public:
560b9c1b51eSKate Stone   CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
56104a4c091SRaphael Isemann       : CommandObjectParsed(interpreter, "list",
56204a4c091SRaphael Isemann                             "List the script or set of commands to be executed "
56304a4c091SRaphael Isemann                             "when the watchpoint is hit.",
56404a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget) {
565e9a5627eSJohnny Chen     CommandArgumentEntry arg;
566e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
567e9a5627eSJohnny Chen 
568e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
569e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
570e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
571e9a5627eSJohnny Chen 
572b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
573b9c1b51eSKate Stone     // argument entry.
574e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
575e9a5627eSJohnny Chen 
576e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
577e9a5627eSJohnny Chen     m_arguments.push_back(arg);
578e9a5627eSJohnny Chen   }
579e9a5627eSJohnny Chen 
58049bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandList() override = default;
581e9a5627eSJohnny Chen 
582e9a5627eSJohnny Chen protected:
583b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
58404a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
585e9a5627eSJohnny Chen 
586e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
587e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
588e9a5627eSJohnny Chen 
589b9c1b51eSKate Stone     if (num_watchpoints == 0) {
590e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist for which to list commands");
591e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
592e9a5627eSJohnny Chen       return false;
593e9a5627eSJohnny Chen     }
594e9a5627eSJohnny Chen 
595b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
596b9c1b51eSKate Stone       result.AppendError(
597b9c1b51eSKate Stone           "No watchpoint specified for which to list the commands");
598e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
599e9a5627eSJohnny Chen       return false;
600e9a5627eSJohnny Chen     }
601e9a5627eSJohnny Chen 
602e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
603b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
604b9c1b51eSKate Stone                                                                valid_wp_ids)) {
605e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
606e9a5627eSJohnny Chen       result.SetStatus(eReturnStatusFailed);
607e9a5627eSJohnny Chen       return false;
608e9a5627eSJohnny Chen     }
609e9a5627eSJohnny Chen 
610e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
611e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
612b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
613e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
614b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
615e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
616e9a5627eSJohnny Chen 
617b9c1b51eSKate Stone         if (wp) {
618e9a5627eSJohnny Chen           const WatchpointOptions *wp_options = wp->GetOptions();
619b9c1b51eSKate Stone           if (wp_options) {
620e9a5627eSJohnny Chen             // Get the callback baton associated with the current watchpoint.
621e9a5627eSJohnny Chen             const Baton *baton = wp_options->GetBaton();
622b9c1b51eSKate Stone             if (baton) {
623e9a5627eSJohnny Chen               result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
6244f728bfcSRaphael Isemann               baton->GetDescription(result.GetOutputStream().AsRawOstream(),
6254f728bfcSRaphael Isemann                                     eDescriptionLevelFull,
6264f728bfcSRaphael Isemann                                     result.GetOutputStream().GetIndentLevel() +
6274f728bfcSRaphael Isemann                                         2);
628b9c1b51eSKate Stone             } else {
629b9c1b51eSKate Stone               result.AppendMessageWithFormat(
630b9c1b51eSKate Stone                   "Watchpoint %u does not have an associated command.\n",
631e9a5627eSJohnny Chen                   cur_wp_id);
632e9a5627eSJohnny Chen             }
633e9a5627eSJohnny Chen           }
634e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusSuccessFinishResult);
635b9c1b51eSKate Stone         } else {
636b9c1b51eSKate Stone           result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
637b9c1b51eSKate Stone                                        cur_wp_id);
638e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusFailed);
639e9a5627eSJohnny Chen         }
640e9a5627eSJohnny Chen       }
641e9a5627eSJohnny Chen     }
642e9a5627eSJohnny Chen 
643e9a5627eSJohnny Chen     return result.Succeeded();
644e9a5627eSJohnny Chen   }
645e9a5627eSJohnny Chen };
646e9a5627eSJohnny Chen 
647e9a5627eSJohnny Chen // CommandObjectWatchpointCommand
648e9a5627eSJohnny Chen 
649b9c1b51eSKate Stone CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
650b9c1b51eSKate Stone     CommandInterpreter &interpreter)
651b9c1b51eSKate Stone     : CommandObjectMultiword(
652b9c1b51eSKate Stone           interpreter, "command",
653b9c1b51eSKate Stone           "Commands for adding, removing and examining LLDB commands "
6544ebdee0aSBruce Mitchener           "executed when the watchpoint is hit (watchpoint 'commands').",
655b9c1b51eSKate Stone           "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
656b9c1b51eSKate Stone   CommandObjectSP add_command_object(
657b9c1b51eSKate Stone       new CommandObjectWatchpointCommandAdd(interpreter));
658b9c1b51eSKate Stone   CommandObjectSP delete_command_object(
659b9c1b51eSKate Stone       new CommandObjectWatchpointCommandDelete(interpreter));
660b9c1b51eSKate Stone   CommandObjectSP list_command_object(
661b9c1b51eSKate Stone       new CommandObjectWatchpointCommandList(interpreter));
662e9a5627eSJohnny Chen 
663e9a5627eSJohnny Chen   add_command_object->SetCommandName("watchpoint command add");
664e9a5627eSJohnny Chen   delete_command_object->SetCommandName("watchpoint command delete");
665e9a5627eSJohnny Chen   list_command_object->SetCommandName("watchpoint command list");
666e9a5627eSJohnny Chen 
66703da4cc2SGreg Clayton   LoadSubCommand("add", add_command_object);
66803da4cc2SGreg Clayton   LoadSubCommand("delete", delete_command_object);
66903da4cc2SGreg Clayton   LoadSubCommand("list", list_command_object);
670e9a5627eSJohnny Chen }
671e9a5627eSJohnny Chen 
67249bcfd80SEugene Zelenko CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;
673