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