180814287SRaphael Isemann //===-- CommandObjectWatchpointCommand.cpp --------------------------------===//
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"
18*7ced9fffSJonas Devlieghere #include "lldb/Interpreter/CommandOptionArgumentTable.h"
19e9a5627eSJohnny Chen #include "lldb/Interpreter/CommandReturnObject.h"
2047cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
21e9a5627eSJohnny Chen #include "lldb/Target/Target.h"
22e9a5627eSJohnny Chen 
23e9a5627eSJohnny Chen using namespace lldb;
24e9a5627eSJohnny Chen using namespace lldb_private;
25e9a5627eSJohnny Chen 
2660bd7a9cSRaphael Isemann #define LLDB_OPTIONS_watchpoint_command_add
2760bd7a9cSRaphael Isemann #include "CommandOptions.inc"
281f0f5b5bSZachary Turner 
29b9c1b51eSKate Stone class CommandObjectWatchpointCommandAdd : public CommandObjectParsed,
30b9c1b51eSKate Stone                                           public IOHandlerDelegateMultiline {
31e9a5627eSJohnny Chen public:
CommandObjectWatchpointCommandAdd(CommandInterpreter & interpreter)327428a18cSKate Stone   CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter)
33b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "add",
34b9c1b51eSKate Stone                             "Add a set of LLDB commands to a watchpoint, to be "
3560ad0fd3SJim Ingham                             "executed whenever the watchpoint is hit.  "
3660ad0fd3SJim Ingham                             "The commands added to the watchpoint replace any "
3760ad0fd3SJim Ingham                             "commands previously added to it.",
3804a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget),
39b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE",
40abb0ed44SKazu Hirata                                    IOHandlerDelegate::Completion::LLDBCommand) {
41e9a5627eSJohnny Chen     SetHelpLong(
42ea671fbdSKate Stone         R"(
43ea671fbdSKate Stone General information about entering watchpoint commands
44ea671fbdSKate Stone ------------------------------------------------------
45ea671fbdSKate Stone 
46b9c1b51eSKate Stone )"
47b9c1b51eSKate Stone         "This command will prompt for commands to be executed when the specified \
48ea671fbdSKate Stone watchpoint is hit.  Each command is typed on its own line following the '> ' \
49b9c1b51eSKate Stone prompt until 'DONE' is entered."
50b9c1b51eSKate Stone         R"(
51ea671fbdSKate Stone 
52b9c1b51eSKate Stone )"
53b9c1b51eSKate Stone         "Syntactic errors may not be detected when initially entered, and many \
54ea671fbdSKate Stone malformed commands can silently fail when executed.  If your watchpoint commands \
55b9c1b51eSKate Stone do not appear to be executing, double-check the command syntax."
56b9c1b51eSKate Stone         R"(
57ea671fbdSKate Stone 
58b9c1b51eSKate Stone )"
59b9c1b51eSKate Stone         "Note: You may enter any debugger command exactly as you would at the debugger \
60ea671fbdSKate Stone prompt.  There is no limit to the number of commands supplied, but do NOT enter \
61b9c1b51eSKate Stone more than one command per line."
62b9c1b51eSKate Stone         R"(
63ea671fbdSKate Stone 
64ea671fbdSKate Stone Special information about PYTHON watchpoint commands
65ea671fbdSKate Stone ----------------------------------------------------
66ea671fbdSKate Stone 
67b9c1b51eSKate Stone )"
68b9c1b51eSKate Stone         "You may enter either one or more lines of Python, including function \
69ea671fbdSKate Stone definitions or calls to functions that will have been imported by the time \
70ea671fbdSKate Stone the code executes.  Single line watchpoint commands will be interpreted 'as is' \
71ea671fbdSKate Stone when the watchpoint is hit.  Multiple lines of Python will be wrapped in a \
72b9c1b51eSKate Stone generated function, and a call to the function will be attached to the watchpoint."
73b9c1b51eSKate Stone         R"(
74ea671fbdSKate Stone 
75ea671fbdSKate Stone This auto-generated function is passed in three arguments:
76ea671fbdSKate Stone 
77ea671fbdSKate Stone     frame:  an lldb.SBFrame object for the frame which hit the watchpoint.
78ea671fbdSKate Stone 
79ea671fbdSKate Stone     wp:     the watchpoint that was hit.
80ea671fbdSKate Stone 
81b9c1b51eSKate Stone )"
82b9c1b51eSKate Stone         "When specifying a python function with the --python-function option, you need \
83b9c1b51eSKate Stone to supply the function name prepended by the module name:"
84b9c1b51eSKate Stone         R"(
85ea671fbdSKate Stone 
86ea671fbdSKate Stone     --python-function myutils.watchpoint_callback
87ea671fbdSKate Stone 
88ea671fbdSKate Stone The function itself must have the following prototype:
89ea671fbdSKate Stone 
90ea671fbdSKate Stone def watchpoint_callback(frame, wp):
91ea671fbdSKate Stone   # Your code goes here
92ea671fbdSKate Stone 
93b9c1b51eSKate Stone )"
94b9c1b51eSKate Stone         "The arguments are the same as the arguments passed to generated functions as \
95ea671fbdSKate Stone described above.  Note that the global variable 'lldb.frame' will NOT be updated when \
96ea671fbdSKate Stone this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
97ea671fbdSKate Stone can get you to the thread via frame.GetThread(), the thread can get you to the \
98ea671fbdSKate Stone process via thread.GetProcess(), and the process can get you back to the target \
99b9c1b51eSKate Stone via process.GetTarget()."
100b9c1b51eSKate Stone         R"(
101ea671fbdSKate Stone 
102b9c1b51eSKate Stone )"
103b9c1b51eSKate Stone         "Important Note: As Python code gets collected into functions, access to global \
104ea671fbdSKate Stone variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
105b9c1b51eSKate Stone Python syntax, including indentation, when entering Python watchpoint commands."
106b9c1b51eSKate Stone         R"(
107ea671fbdSKate Stone 
108ea671fbdSKate Stone Example Python one-line watchpoint command:
109ea671fbdSKate Stone 
110ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
111ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
112ea671fbdSKate Stone > print "Hit this watchpoint!"
113ea671fbdSKate Stone > DONE
114ea671fbdSKate Stone 
115ea671fbdSKate Stone As a convenience, this also works for a short Python one-liner:
116ea671fbdSKate Stone 
117ea671fbdSKate Stone (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()'
118ea671fbdSKate Stone (lldb) run
119ea671fbdSKate Stone Launching '.../a.out'  (x86_64)
120ea671fbdSKate Stone (lldb) Fri Sep 10 12:17:45 2010
121ea671fbdSKate Stone Process 21778 Stopped
122ea671fbdSKate Stone * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread
123ea671fbdSKate Stone   36
124ea671fbdSKate Stone   37   	int c(int val)
125ea671fbdSKate Stone   38   	{
126ea671fbdSKate Stone   39 ->	    return val + 3;
127ea671fbdSKate Stone   40   	}
128ea671fbdSKate Stone   41
129ea671fbdSKate Stone   42   	int main (int argc, char const *argv[])
130ea671fbdSKate Stone 
131ea671fbdSKate Stone Example multiple line Python watchpoint command, using function definition:
132ea671fbdSKate Stone 
133ea671fbdSKate Stone (lldb) watchpoint command add -s python 1
134ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
135ea671fbdSKate Stone > def watchpoint_output (wp_no):
136ea671fbdSKate Stone >     out_string = "Hit watchpoint number " + repr (wp_no)
137ea671fbdSKate Stone >     print out_string
138ea671fbdSKate Stone >     return True
139ea671fbdSKate Stone > watchpoint_output (1)
140ea671fbdSKate Stone > DONE
141ea671fbdSKate Stone 
142ea671fbdSKate Stone Example multiple line Python watchpoint command, using 'loose' Python:
143ea671fbdSKate Stone 
144ea671fbdSKate Stone (lldb) watchpoint command add -s p 1
145ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
146ea671fbdSKate Stone > global wp_count
147ea671fbdSKate Stone > wp_count = wp_count + 1
148ea671fbdSKate Stone > print "Hit this watchpoint " + repr(wp_count) + " times!"
149ea671fbdSKate Stone > DONE
150ea671fbdSKate Stone 
151b9c1b51eSKate Stone )"
152b9c1b51eSKate Stone         "In this case, since there is a reference to a global variable, \
153ea671fbdSKate Stone 'wp_count', you will also need to make sure 'wp_count' exists and is \
154b9c1b51eSKate Stone initialized:"
155b9c1b51eSKate Stone         R"(
156ea671fbdSKate Stone 
157ea671fbdSKate Stone (lldb) script
158ea671fbdSKate Stone >>> wp_count = 0
159ea671fbdSKate Stone >>> quit()
160ea671fbdSKate Stone 
161b9c1b51eSKate Stone )"
162b9c1b51eSKate Stone         "Final Note: A warning that no watchpoint command was generated when there \
163b9c1b51eSKate Stone are no syntax errors may indicate that a function was declared but never called.");
164e9a5627eSJohnny Chen 
165e9a5627eSJohnny Chen     CommandArgumentEntry arg;
166e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
167e9a5627eSJohnny Chen 
168e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
169e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
170e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
171e9a5627eSJohnny Chen 
172b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
173b9c1b51eSKate Stone     // argument entry.
174e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
175e9a5627eSJohnny Chen 
176e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
177e9a5627eSJohnny Chen     m_arguments.push_back(arg);
178e9a5627eSJohnny Chen   }
179e9a5627eSJohnny Chen 
18049bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandAdd() override = default;
181e9a5627eSJohnny Chen 
GetOptions()182b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
183e9a5627eSJohnny Chen 
IOHandlerActivated(IOHandler & io_handler,bool interactive)1840affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
1857ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
1860affb582SDave Lee     if (output_sp && interactive) {
187b9c1b51eSKate Stone       output_sp->PutCString(
188b9c1b51eSKate Stone           "Enter your debugger command(s).  Type 'DONE' to end.\n");
18944d93782SGreg Clayton       output_sp->Flush();
19044d93782SGreg Clayton     }
19144d93782SGreg Clayton   }
19244d93782SGreg Clayton 
IOHandlerInputComplete(IOHandler & io_handler,std::string & line)193b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
194b9c1b51eSKate Stone                               std::string &line) override {
19544d93782SGreg Clayton     io_handler.SetIsDone(true);
19644d93782SGreg Clayton 
197b9c1b51eSKate Stone     // The WatchpointOptions object is owned by the watchpoint or watchpoint
198b9c1b51eSKate Stone     // location
199b9c1b51eSKate Stone     WatchpointOptions *wp_options =
200b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
201b9c1b51eSKate Stone     if (wp_options) {
202d5b44036SJonas Devlieghere       std::unique_ptr<WatchpointOptions::CommandData> data_up(
203b9c1b51eSKate Stone           new WatchpointOptions::CommandData());
204d5b44036SJonas Devlieghere       if (data_up) {
205d5b44036SJonas Devlieghere         data_up->user_source.SplitIntoLines(line);
2064e4fbe82SZachary Turner         auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(
207d5b44036SJonas Devlieghere             std::move(data_up));
20844d93782SGreg Clayton         wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
20944d93782SGreg Clayton       }
21044d93782SGreg Clayton     }
21144d93782SGreg Clayton   }
21244d93782SGreg Clayton 
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)213b9c1b51eSKate Stone   void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options,
214b9c1b51eSKate Stone                                                CommandReturnObject &result) {
215b9c1b51eSKate Stone     m_interpreter.GetLLDBCommandsFromIOHandler(
216b9c1b51eSKate Stone         "> ",        // Prompt
21744d93782SGreg Clayton         *this,       // IOHandlerDelegate
218b9c1b51eSKate Stone         wp_options); // Baton for the "io_handler" that will be passed back into
219b9c1b51eSKate Stone                      // our IOHandlerDelegate functions
220e9a5627eSJohnny Chen   }
221e9a5627eSJohnny Chen 
222e9a5627eSJohnny Chen   /// Set a one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * oneliner)223b9c1b51eSKate Stone   void SetWatchpointCommandCallback(WatchpointOptions *wp_options,
224b9c1b51eSKate Stone                                     const char *oneliner) {
225d5b44036SJonas Devlieghere     std::unique_ptr<WatchpointOptions::CommandData> data_up(
226b9c1b51eSKate Stone         new WatchpointOptions::CommandData());
227e9a5627eSJohnny Chen 
22805097246SAdrian Prantl     // It's necessary to set both user_source and script_source to the
22905097246SAdrian Prantl     // oneliner. The former is used to generate callback description (as in
23005097246SAdrian Prantl     // watchpoint command list) while the latter is used for Python to
23105097246SAdrian Prantl     // interpret during the actual callback.
232d5b44036SJonas Devlieghere     data_up->user_source.AppendString(oneliner);
233d5b44036SJonas Devlieghere     data_up->script_source.assign(oneliner);
234d5b44036SJonas Devlieghere     data_up->stop_on_error = m_options.m_stop_on_error;
235e9a5627eSJohnny Chen 
2364e4fbe82SZachary Turner     auto baton_sp =
237d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
238e9a5627eSJohnny Chen     wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp);
239e9a5627eSJohnny Chen   }
240e9a5627eSJohnny Chen 
241e9a5627eSJohnny Chen   static bool
WatchpointOptionsCallbackFunction(void * baton,StoppointCallbackContext * context,lldb::user_id_t watch_id)242e9a5627eSJohnny Chen   WatchpointOptionsCallbackFunction(void *baton,
243e9a5627eSJohnny Chen                                     StoppointCallbackContext *context,
244b9c1b51eSKate Stone                                     lldb::user_id_t watch_id) {
245e9a5627eSJohnny Chen     bool ret_value = true;
24649bcfd80SEugene Zelenko     if (baton == nullptr)
247e9a5627eSJohnny Chen       return true;
248e9a5627eSJohnny Chen 
249b9c1b51eSKate Stone     WatchpointOptions::CommandData *data =
250b9c1b51eSKate Stone         (WatchpointOptions::CommandData *)baton;
251e9a5627eSJohnny Chen     StringList &commands = data->user_source;
252e9a5627eSJohnny Chen 
253b9c1b51eSKate Stone     if (commands.GetSize() > 0) {
254e9a5627eSJohnny Chen       ExecutionContext exe_ctx(context->exe_ctx_ref);
255e9a5627eSJohnny Chen       Target *target = exe_ctx.GetTargetPtr();
256b9c1b51eSKate Stone       if (target) {
257e9a5627eSJohnny Chen         Debugger &debugger = target->GetDebugger();
258de019b88SJonas Devlieghere         CommandReturnObject result(debugger.GetUseColor());
259de019b88SJonas Devlieghere 
260b9c1b51eSKate Stone         // Rig up the results secondary output stream to the debugger's, so the
26105097246SAdrian Prantl         // output will come out synchronously if the debugger is set up that
26205097246SAdrian Prantl         // way.
263e9a5627eSJohnny Chen         StreamSP output_stream(debugger.GetAsyncOutputStream());
264e9a5627eSJohnny Chen         StreamSP error_stream(debugger.GetAsyncErrorStream());
265e9a5627eSJohnny Chen         result.SetImmediateOutputStream(output_stream);
266e9a5627eSJohnny Chen         result.SetImmediateErrorStream(error_stream);
267e9a5627eSJohnny Chen 
26826c7bf93SJim Ingham         CommandInterpreterRunOptions options;
26926c7bf93SJim Ingham         options.SetStopOnContinue(true);
27026c7bf93SJim Ingham         options.SetStopOnError(data->stop_on_error);
27126c7bf93SJim Ingham         options.SetEchoCommands(false);
27226c7bf93SJim Ingham         options.SetPrintResults(true);
273c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
27426c7bf93SJim Ingham         options.SetAddToHistory(false);
275e9a5627eSJohnny Chen 
27636de94cfSTatyana Krasnukha         debugger.GetCommandInterpreter().HandleCommands(commands, exe_ctx,
277b9c1b51eSKate Stone                                                         options, result);
278e9a5627eSJohnny Chen         result.GetImmediateOutputStream()->Flush();
279e9a5627eSJohnny Chen         result.GetImmediateErrorStream()->Flush();
280e9a5627eSJohnny Chen       }
281e9a5627eSJohnny Chen     }
282e9a5627eSJohnny Chen     return ret_value;
283e9a5627eSJohnny Chen   }
284e9a5627eSJohnny Chen 
285b9c1b51eSKate Stone   class CommandOptions : public Options {
286e9a5627eSJohnny Chen   public:
28724f9a2f5SShafik Yaghmour     CommandOptions() = default;
288e9a5627eSJohnny Chen 
28949bcfd80SEugene Zelenko     ~CommandOptions() override = default;
290e9a5627eSJohnny Chen 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)29197206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
292b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
29397206d57SZachary Turner       Status error;
2943bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
295e9a5627eSJohnny Chen 
296b9c1b51eSKate Stone       switch (short_option) {
297e9a5627eSJohnny Chen       case 'o':
298e9a5627eSJohnny Chen         m_use_one_liner = true;
299adcd0268SBenjamin Kramer         m_one_liner = std::string(option_arg);
300e9a5627eSJohnny Chen         break;
301e9a5627eSJohnny Chen 
302e9a5627eSJohnny Chen       case 's':
30347cbf4a0SPavel Labath         m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
304fe11483bSZachary Turner             option_arg, GetDefinitions()[option_idx].enum_values,
305fe11483bSZachary Turner             eScriptLanguageNone, error);
306e9a5627eSJohnny Chen 
30768cb7d85SJonas Devlieghere         switch (m_script_language) {
30868cb7d85SJonas Devlieghere         case eScriptLanguagePython:
30968cb7d85SJonas Devlieghere         case eScriptLanguageLua:
31068cb7d85SJonas Devlieghere           m_use_script_language = true;
31168cb7d85SJonas Devlieghere           break;
31268cb7d85SJonas Devlieghere         case eScriptLanguageNone:
31368cb7d85SJonas Devlieghere         case eScriptLanguageUnknown:
31468cb7d85SJonas Devlieghere           m_use_script_language = false;
31568cb7d85SJonas Devlieghere           break;
31668cb7d85SJonas Devlieghere         }
317e9a5627eSJohnny Chen         break;
318e9a5627eSJohnny Chen 
319b9c1b51eSKate Stone       case 'e': {
320e9a5627eSJohnny Chen         bool success = false;
32147cbf4a0SPavel Labath         m_stop_on_error =
32247cbf4a0SPavel Labath             OptionArgParser::ToBoolean(option_arg, false, &success);
323e9a5627eSJohnny Chen         if (!success)
324b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
325fe11483bSZachary Turner               "invalid value for stop-on-error: \"%s\"",
326fe11483bSZachary Turner               option_arg.str().c_str());
327b9c1b51eSKate Stone       } break;
328e9a5627eSJohnny Chen 
329e9a5627eSJohnny Chen       case 'F':
330e9a5627eSJohnny Chen         m_use_one_liner = false;
331adcd0268SBenjamin Kramer         m_function_name.assign(std::string(option_arg));
332e9a5627eSJohnny Chen         break;
333e9a5627eSJohnny Chen 
334e9a5627eSJohnny Chen       default:
33536162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
336e9a5627eSJohnny Chen       }
337e9a5627eSJohnny Chen       return error;
338e9a5627eSJohnny Chen     }
33949bcfd80SEugene Zelenko 
OptionParsingStarting(ExecutionContext * execution_context)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 
GetDefinitions()3511f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
35270602439SZachary Turner       return llvm::makeArrayRef(g_watchpoint_command_add_options);
3531f0f5b5bSZachary Turner     }
354e9a5627eSJohnny Chen 
355e9a5627eSJohnny Chen     // Instance variables to hold the values for command options.
356e9a5627eSJohnny Chen 
3579494c510SJonas Devlieghere     bool m_use_commands = false;
3589494c510SJonas Devlieghere     bool m_use_script_language = false;
3599494c510SJonas Devlieghere     lldb::ScriptLanguage m_script_language = eScriptLanguageNone;
360e9a5627eSJohnny Chen 
361e9a5627eSJohnny Chen     // Instance variables to hold the values for one_liner options.
3629494c510SJonas Devlieghere     bool m_use_one_liner = false;
363e9a5627eSJohnny Chen     std::string m_one_liner;
364e9a5627eSJohnny Chen     bool m_stop_on_error;
365e9a5627eSJohnny Chen     std::string m_function_name;
366e9a5627eSJohnny Chen   };
367e9a5627eSJohnny Chen 
368e9a5627eSJohnny Chen protected:
DoExecute(Args & command,CommandReturnObject & result)369b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
37004a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
371e9a5627eSJohnny Chen 
372e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
373e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
374e9a5627eSJohnny Chen 
375b9c1b51eSKate Stone     if (num_watchpoints == 0) {
376e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands added");
377e9a5627eSJohnny Chen       return false;
378e9a5627eSJohnny Chen     }
379e9a5627eSJohnny Chen 
38068cb7d85SJonas Devlieghere     if (!m_options.m_function_name.empty()) {
38168cb7d85SJonas Devlieghere       if (!m_options.m_use_script_language) {
38268cb7d85SJonas Devlieghere         m_options.m_script_language = GetDebugger().GetScriptLanguage();
38368cb7d85SJonas Devlieghere         m_options.m_use_script_language = true;
38468cb7d85SJonas Devlieghere       }
385e9a5627eSJohnny Chen     }
386e9a5627eSJohnny Chen 
387e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
388b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
389b9c1b51eSKate Stone                                                                valid_wp_ids)) {
390e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
391e9a5627eSJohnny Chen       return false;
392e9a5627eSJohnny Chen     }
393e9a5627eSJohnny Chen 
394e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
395e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
396b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
397e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
398b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
399e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
400e9a5627eSJohnny Chen         // Sanity check wp first.
401b9c1b51eSKate Stone         if (wp == nullptr)
402b9c1b51eSKate Stone           continue;
403e9a5627eSJohnny Chen 
404e9a5627eSJohnny Chen         WatchpointOptions *wp_options = wp->GetOptions();
405e9a5627eSJohnny Chen         // Skip this watchpoint if wp_options is not good.
406b9c1b51eSKate Stone         if (wp_options == nullptr)
407b9c1b51eSKate Stone           continue;
408e9a5627eSJohnny Chen 
40905097246SAdrian Prantl         // If we are using script language, get the script interpreter in order
41005097246SAdrian Prantl         // to set or collect command callback.  Otherwise, call the methods
41105097246SAdrian Prantl         // associated with this object.
412b9c1b51eSKate Stone         if (m_options.m_use_script_language) {
41368cb7d85SJonas Devlieghere           ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(
41468cb7d85SJonas Devlieghere               /*can_create=*/true, m_options.m_script_language);
415e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
416b9c1b51eSKate Stone           if (m_options.m_use_one_liner) {
41768cb7d85SJonas Devlieghere             script_interp->SetWatchpointCommandCallback(
418b9c1b51eSKate Stone                 wp_options, m_options.m_one_liner.c_str());
419e9a5627eSJohnny Chen           }
42005097246SAdrian Prantl           // Special handling for using a Python function by name instead of
42105097246SAdrian Prantl           // extending the watchpoint callback data structures, we just
42205097246SAdrian Prantl           // automatize what the user would do manually: make their watchpoint
42305097246SAdrian Prantl           // command be a function call
424b9c1b51eSKate Stone           else if (!m_options.m_function_name.empty()) {
425e9a5627eSJohnny Chen             std::string oneliner(m_options.m_function_name);
426e9a5627eSJohnny Chen             oneliner += "(frame, wp, internal_dict)";
42768cb7d85SJonas Devlieghere             script_interp->SetWatchpointCommandCallback(
428b9c1b51eSKate Stone                 wp_options, oneliner.c_str());
429b9c1b51eSKate Stone           } else {
43068cb7d85SJonas Devlieghere             script_interp->CollectDataForWatchpointCommandCallback(wp_options,
43168cb7d85SJonas Devlieghere                                                                    result);
432e9a5627eSJohnny Chen           }
433b9c1b51eSKate Stone         } else {
434e9a5627eSJohnny Chen           // Special handling for one-liner specified inline.
435e9a5627eSJohnny Chen           if (m_options.m_use_one_liner)
436e9a5627eSJohnny Chen             SetWatchpointCommandCallback(wp_options,
437e9a5627eSJohnny Chen                                          m_options.m_one_liner.c_str());
438e9a5627eSJohnny Chen           else
439b9c1b51eSKate Stone             CollectDataForWatchpointCommandCallback(wp_options, result);
440e9a5627eSJohnny Chen         }
441e9a5627eSJohnny Chen       }
442e9a5627eSJohnny Chen     }
443e9a5627eSJohnny Chen 
444e9a5627eSJohnny Chen     return result.Succeeded();
445e9a5627eSJohnny Chen   }
446e9a5627eSJohnny Chen 
447e9a5627eSJohnny Chen private:
448e9a5627eSJohnny Chen   CommandOptions m_options;
449e9a5627eSJohnny Chen };
450e9a5627eSJohnny Chen 
451e9a5627eSJohnny Chen // CommandObjectWatchpointCommandDelete
452e9a5627eSJohnny Chen 
453b9c1b51eSKate Stone class CommandObjectWatchpointCommandDelete : public CommandObjectParsed {
454e9a5627eSJohnny Chen public:
CommandObjectWatchpointCommandDelete(CommandInterpreter & interpreter)455b9c1b51eSKate Stone   CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter)
456b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "delete",
457e9a5627eSJohnny Chen                             "Delete the set of commands from a watchpoint.",
45804a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget) {
459e9a5627eSJohnny Chen     CommandArgumentEntry arg;
460e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
461e9a5627eSJohnny Chen 
462e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
463e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
464e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
465e9a5627eSJohnny Chen 
466b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
467b9c1b51eSKate Stone     // argument entry.
468e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
469e9a5627eSJohnny Chen 
470e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
471e9a5627eSJohnny Chen     m_arguments.push_back(arg);
472e9a5627eSJohnny Chen   }
473e9a5627eSJohnny Chen 
47449bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandDelete() override = default;
475e9a5627eSJohnny Chen 
476e9a5627eSJohnny Chen protected:
DoExecute(Args & command,CommandReturnObject & result)477b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
47804a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
479e9a5627eSJohnny Chen 
480e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
481e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
482e9a5627eSJohnny Chen 
483b9c1b51eSKate Stone     if (num_watchpoints == 0) {
484e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist to have commands deleted");
485e9a5627eSJohnny Chen       return false;
486e9a5627eSJohnny Chen     }
487e9a5627eSJohnny Chen 
488b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
489b9c1b51eSKate Stone       result.AppendError(
490b9c1b51eSKate Stone           "No watchpoint specified from which to delete the commands");
491e9a5627eSJohnny Chen       return false;
492e9a5627eSJohnny Chen     }
493e9a5627eSJohnny Chen 
494e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
495b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
496b9c1b51eSKate Stone                                                                valid_wp_ids)) {
497e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
498e9a5627eSJohnny Chen       return false;
499e9a5627eSJohnny Chen     }
500e9a5627eSJohnny Chen 
501e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
502e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
503b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
504e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
505b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
506e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
507e9a5627eSJohnny Chen         if (wp)
508e9a5627eSJohnny Chen           wp->ClearCallback();
509b9c1b51eSKate Stone       } else {
510b9c1b51eSKate Stone         result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id);
511e9a5627eSJohnny Chen         return false;
512e9a5627eSJohnny Chen       }
513e9a5627eSJohnny Chen     }
514e9a5627eSJohnny Chen     return result.Succeeded();
515e9a5627eSJohnny Chen   }
516e9a5627eSJohnny Chen };
517e9a5627eSJohnny Chen 
518e9a5627eSJohnny Chen // CommandObjectWatchpointCommandList
519e9a5627eSJohnny Chen 
520b9c1b51eSKate Stone class CommandObjectWatchpointCommandList : public CommandObjectParsed {
521e9a5627eSJohnny Chen public:
CommandObjectWatchpointCommandList(CommandInterpreter & interpreter)522b9c1b51eSKate Stone   CommandObjectWatchpointCommandList(CommandInterpreter &interpreter)
52304a4c091SRaphael Isemann       : CommandObjectParsed(interpreter, "list",
52404a4c091SRaphael Isemann                             "List the script or set of commands to be executed "
52504a4c091SRaphael Isemann                             "when the watchpoint is hit.",
52604a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget) {
527e9a5627eSJohnny Chen     CommandArgumentEntry arg;
528e9a5627eSJohnny Chen     CommandArgumentData wp_id_arg;
529e9a5627eSJohnny Chen 
530e9a5627eSJohnny Chen     // Define the first (and only) variant of this arg.
531e9a5627eSJohnny Chen     wp_id_arg.arg_type = eArgTypeWatchpointID;
532e9a5627eSJohnny Chen     wp_id_arg.arg_repetition = eArgRepeatPlain;
533e9a5627eSJohnny Chen 
534b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
535b9c1b51eSKate Stone     // argument entry.
536e9a5627eSJohnny Chen     arg.push_back(wp_id_arg);
537e9a5627eSJohnny Chen 
538e9a5627eSJohnny Chen     // Push the data for the first argument into the m_arguments vector.
539e9a5627eSJohnny Chen     m_arguments.push_back(arg);
540e9a5627eSJohnny Chen   }
541e9a5627eSJohnny Chen 
54249bcfd80SEugene Zelenko   ~CommandObjectWatchpointCommandList() override = default;
543e9a5627eSJohnny Chen 
544e9a5627eSJohnny Chen protected:
DoExecute(Args & command,CommandReturnObject & result)545b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
54604a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
547e9a5627eSJohnny Chen 
548e9a5627eSJohnny Chen     const WatchpointList &watchpoints = target->GetWatchpointList();
549e9a5627eSJohnny Chen     size_t num_watchpoints = watchpoints.GetSize();
550e9a5627eSJohnny Chen 
551b9c1b51eSKate Stone     if (num_watchpoints == 0) {
552e9a5627eSJohnny Chen       result.AppendError("No watchpoints exist for which to list commands");
553e9a5627eSJohnny Chen       return false;
554e9a5627eSJohnny Chen     }
555e9a5627eSJohnny Chen 
556b9c1b51eSKate Stone     if (command.GetArgumentCount() == 0) {
557b9c1b51eSKate Stone       result.AppendError(
558b9c1b51eSKate Stone           "No watchpoint specified for which to list the commands");
559e9a5627eSJohnny Chen       return false;
560e9a5627eSJohnny Chen     }
561e9a5627eSJohnny Chen 
562e9a5627eSJohnny Chen     std::vector<uint32_t> valid_wp_ids;
563b9c1b51eSKate Stone     if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command,
564b9c1b51eSKate Stone                                                                valid_wp_ids)) {
565e9a5627eSJohnny Chen       result.AppendError("Invalid watchpoints specification.");
566e9a5627eSJohnny Chen       return false;
567e9a5627eSJohnny Chen     }
568e9a5627eSJohnny Chen 
569e9a5627eSJohnny Chen     result.SetStatus(eReturnStatusSuccessFinishNoResult);
570e9a5627eSJohnny Chen     const size_t count = valid_wp_ids.size();
571b9c1b51eSKate Stone     for (size_t i = 0; i < count; ++i) {
572e9a5627eSJohnny Chen       uint32_t cur_wp_id = valid_wp_ids.at(i);
573b9c1b51eSKate Stone       if (cur_wp_id != LLDB_INVALID_WATCH_ID) {
574e9a5627eSJohnny Chen         Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get();
575e9a5627eSJohnny Chen 
576b9c1b51eSKate Stone         if (wp) {
577e9a5627eSJohnny Chen           const WatchpointOptions *wp_options = wp->GetOptions();
578b9c1b51eSKate Stone           if (wp_options) {
579e9a5627eSJohnny Chen             // Get the callback baton associated with the current watchpoint.
580e9a5627eSJohnny Chen             const Baton *baton = wp_options->GetBaton();
581b9c1b51eSKate Stone             if (baton) {
582e9a5627eSJohnny Chen               result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id);
5834f728bfcSRaphael Isemann               baton->GetDescription(result.GetOutputStream().AsRawOstream(),
5844f728bfcSRaphael Isemann                                     eDescriptionLevelFull,
5854f728bfcSRaphael Isemann                                     result.GetOutputStream().GetIndentLevel() +
5864f728bfcSRaphael Isemann                                         2);
587b9c1b51eSKate Stone             } else {
588b9c1b51eSKate Stone               result.AppendMessageWithFormat(
589b9c1b51eSKate Stone                   "Watchpoint %u does not have an associated command.\n",
590e9a5627eSJohnny Chen                   cur_wp_id);
591e9a5627eSJohnny Chen             }
592e9a5627eSJohnny Chen           }
593e9a5627eSJohnny Chen           result.SetStatus(eReturnStatusSuccessFinishResult);
594b9c1b51eSKate Stone         } else {
595b9c1b51eSKate Stone           result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n",
596b9c1b51eSKate Stone                                        cur_wp_id);
597e9a5627eSJohnny Chen         }
598e9a5627eSJohnny Chen       }
599e9a5627eSJohnny Chen     }
600e9a5627eSJohnny Chen 
601e9a5627eSJohnny Chen     return result.Succeeded();
602e9a5627eSJohnny Chen   }
603e9a5627eSJohnny Chen };
604e9a5627eSJohnny Chen 
605e9a5627eSJohnny Chen // CommandObjectWatchpointCommand
606e9a5627eSJohnny Chen 
CommandObjectWatchpointCommand(CommandInterpreter & interpreter)607b9c1b51eSKate Stone CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(
608b9c1b51eSKate Stone     CommandInterpreter &interpreter)
609b9c1b51eSKate Stone     : CommandObjectMultiword(
610b9c1b51eSKate Stone           interpreter, "command",
611b9c1b51eSKate Stone           "Commands for adding, removing and examining LLDB commands "
6124ebdee0aSBruce Mitchener           "executed when the watchpoint is hit (watchpoint 'commands').",
613b9c1b51eSKate Stone           "command <sub-command> [<sub-command-options>] <watchpoint-id>") {
614b9c1b51eSKate Stone   CommandObjectSP add_command_object(
615b9c1b51eSKate Stone       new CommandObjectWatchpointCommandAdd(interpreter));
616b9c1b51eSKate Stone   CommandObjectSP delete_command_object(
617b9c1b51eSKate Stone       new CommandObjectWatchpointCommandDelete(interpreter));
618b9c1b51eSKate Stone   CommandObjectSP list_command_object(
619b9c1b51eSKate Stone       new CommandObjectWatchpointCommandList(interpreter));
620e9a5627eSJohnny Chen 
621e9a5627eSJohnny Chen   add_command_object->SetCommandName("watchpoint command add");
622e9a5627eSJohnny Chen   delete_command_object->SetCommandName("watchpoint command delete");
623e9a5627eSJohnny Chen   list_command_object->SetCommandName("watchpoint command list");
624e9a5627eSJohnny Chen 
62503da4cc2SGreg Clayton   LoadSubCommand("add", add_command_object);
62603da4cc2SGreg Clayton   LoadSubCommand("delete", delete_command_object);
62703da4cc2SGreg Clayton   LoadSubCommand("list", list_command_object);
628e9a5627eSJohnny Chen }
629e9a5627eSJohnny Chen 
63049bcfd80SEugene Zelenko CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default;
631