1 //===-- CommandObjectWatchpoint.cpp -----------------------------*- C++ -*-===//
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 "CommandObjectWatchpoint.h"
10 #include "CommandObjectWatchpointCommand.h"
11 
12 #include <vector>
13 
14 #include "llvm/ADT/StringRef.h"
15 
16 #include "lldb/Breakpoint/Watchpoint.h"
17 #include "lldb/Breakpoint/WatchpointList.h"
18 #include "lldb/Core/ValueObject.h"
19 #include "lldb/Core/ValueObjectVariable.h"
20 #include "lldb/Host/OptionParser.h"
21 #include "lldb/Interpreter/CommandCompletions.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Symbol/Variable.h"
25 #include "lldb/Symbol/VariableList.h"
26 #include "lldb/Target/StackFrame.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Utility/StreamString.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 static void AddWatchpointDescription(Stream *s, Watchpoint *wp,
34                                      lldb::DescriptionLevel level) {
35   s->IndentMore();
36   wp->GetDescription(s, level);
37   s->IndentLess();
38   s->EOL();
39 }
40 
41 static bool CheckTargetForWatchpointOperations(Target *target,
42                                                CommandReturnObject &result) {
43   if (target == nullptr) {
44     result.AppendError("Invalid target.  No existing target or watchpoints.");
45     result.SetStatus(eReturnStatusFailed);
46     return false;
47   }
48   bool process_is_valid =
49       target->GetProcessSP() && target->GetProcessSP()->IsAlive();
50   if (!process_is_valid) {
51     result.AppendError("Thre's no process or it is not alive.");
52     result.SetStatus(eReturnStatusFailed);
53     return false;
54   }
55   // Target passes our checks, return true.
56   return true;
57 }
58 
59 // Equivalent class: {"-", "to", "To", "TO"} of range specifier array.
60 static const char *RSA[4] = {"-", "to", "To", "TO"};
61 
62 // Return the index to RSA if found; otherwise -1 is returned.
63 static int32_t WithRSAIndex(llvm::StringRef Arg) {
64 
65   uint32_t i;
66   for (i = 0; i < 4; ++i)
67     if (Arg.find(RSA[i]) != llvm::StringRef::npos)
68       return i;
69   return -1;
70 }
71 
72 // Return true if wp_ids is successfully populated with the watch ids. False
73 // otherwise.
74 bool CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
75     Target *target, Args &args, std::vector<uint32_t> &wp_ids) {
76   // Pre-condition: args.GetArgumentCount() > 0.
77   if (args.GetArgumentCount() == 0) {
78     if (target == nullptr)
79       return false;
80     WatchpointSP watch_sp = target->GetLastCreatedWatchpoint();
81     if (watch_sp) {
82       wp_ids.push_back(watch_sp->GetID());
83       return true;
84     } else
85       return false;
86   }
87 
88   llvm::StringRef Minus("-");
89   std::vector<llvm::StringRef> StrRefArgs;
90   llvm::StringRef first;
91   llvm::StringRef second;
92   size_t i;
93   int32_t idx;
94   // Go through the arguments and make a canonical form of arg list containing
95   // only numbers with possible "-" in between.
96   for (auto &entry : args.entries()) {
97     if ((idx = WithRSAIndex(entry.ref)) == -1) {
98       StrRefArgs.push_back(entry.ref);
99       continue;
100     }
101     // The Arg contains the range specifier, split it, then.
102     std::tie(first, second) = entry.ref.split(RSA[idx]);
103     if (!first.empty())
104       StrRefArgs.push_back(first);
105     StrRefArgs.push_back(Minus);
106     if (!second.empty())
107       StrRefArgs.push_back(second);
108   }
109   // Now process the canonical list and fill in the vector of uint32_t's. If
110   // there is any error, return false and the client should ignore wp_ids.
111   uint32_t beg, end, id;
112   size_t size = StrRefArgs.size();
113   bool in_range = false;
114   for (i = 0; i < size; ++i) {
115     llvm::StringRef Arg = StrRefArgs[i];
116     if (in_range) {
117       // Look for the 'end' of the range.  Note StringRef::getAsInteger()
118       // returns true to signify error while parsing.
119       if (Arg.getAsInteger(0, end))
120         return false;
121       // Found a range!  Now append the elements.
122       for (id = beg; id <= end; ++id)
123         wp_ids.push_back(id);
124       in_range = false;
125       continue;
126     }
127     if (i < (size - 1) && StrRefArgs[i + 1] == Minus) {
128       if (Arg.getAsInteger(0, beg))
129         return false;
130       // Turn on the in_range flag, we are looking for end of range next.
131       ++i;
132       in_range = true;
133       continue;
134     }
135     // Otherwise, we have a simple ID.  Just append it.
136     if (Arg.getAsInteger(0, beg))
137       return false;
138     wp_ids.push_back(beg);
139   }
140 
141   // It is an error if after the loop, we're still in_range.
142   return !in_range;
143 }
144 
145 // CommandObjectWatchpointList
146 
147 // CommandObjectWatchpointList::Options
148 #pragma mark List::CommandOptions
149 #define LLDB_OPTIONS_watchpoint_list
150 #include "CommandOptions.inc"
151 
152 #pragma mark List
153 
154 class CommandObjectWatchpointList : public CommandObjectParsed {
155 public:
156   CommandObjectWatchpointList(CommandInterpreter &interpreter)
157       : CommandObjectParsed(
158             interpreter, "watchpoint list",
159             "List all watchpoints at configurable levels of detail.", nullptr),
160         m_options() {
161     CommandArgumentEntry arg;
162     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
163                                       eArgTypeWatchpointIDRange);
164     // Add the entry for the first argument for this command to the object's
165     // arguments vector.
166     m_arguments.push_back(arg);
167   }
168 
169   ~CommandObjectWatchpointList() override = default;
170 
171   Options *GetOptions() override { return &m_options; }
172 
173   class CommandOptions : public Options {
174   public:
175     CommandOptions()
176         : Options(),
177           m_level(lldb::eDescriptionLevelBrief) // Watchpoint List defaults to
178                                                 // brief descriptions
179     {}
180 
181     ~CommandOptions() override = default;
182 
183     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
184                           ExecutionContext *execution_context) override {
185       Status error;
186       const int short_option = m_getopt_table[option_idx].val;
187 
188       switch (short_option) {
189       case 'b':
190         m_level = lldb::eDescriptionLevelBrief;
191         break;
192       case 'f':
193         m_level = lldb::eDescriptionLevelFull;
194         break;
195       case 'v':
196         m_level = lldb::eDescriptionLevelVerbose;
197         break;
198       default:
199         error.SetErrorStringWithFormat("unrecognized option '%c'",
200                                        short_option);
201         break;
202       }
203 
204       return error;
205     }
206 
207     void OptionParsingStarting(ExecutionContext *execution_context) override {
208       m_level = lldb::eDescriptionLevelFull;
209     }
210 
211     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
212       return llvm::makeArrayRef(g_watchpoint_list_options);
213     }
214 
215     // Instance variables to hold the values for command options.
216 
217     lldb::DescriptionLevel m_level;
218   };
219 
220 protected:
221   bool DoExecute(Args &command, CommandReturnObject &result) override {
222     Target *target = GetDebugger().GetSelectedTarget().get();
223     if (target == nullptr) {
224       result.AppendError("Invalid target. No current target or watchpoints.");
225       result.SetStatus(eReturnStatusSuccessFinishNoResult);
226       return true;
227     }
228 
229     if (target->GetProcessSP() && target->GetProcessSP()->IsAlive()) {
230       uint32_t num_supported_hardware_watchpoints;
231       Status error = target->GetProcessSP()->GetWatchpointSupportInfo(
232           num_supported_hardware_watchpoints);
233       if (error.Success())
234         result.AppendMessageWithFormat(
235             "Number of supported hardware watchpoints: %u\n",
236             num_supported_hardware_watchpoints);
237     }
238 
239     const WatchpointList &watchpoints = target->GetWatchpointList();
240 
241     std::unique_lock<std::recursive_mutex> lock;
242     target->GetWatchpointList().GetListMutex(lock);
243 
244     size_t num_watchpoints = watchpoints.GetSize();
245 
246     if (num_watchpoints == 0) {
247       result.AppendMessage("No watchpoints currently set.");
248       result.SetStatus(eReturnStatusSuccessFinishNoResult);
249       return true;
250     }
251 
252     Stream &output_stream = result.GetOutputStream();
253 
254     if (command.GetArgumentCount() == 0) {
255       // No watchpoint selected; show info about all currently set watchpoints.
256       result.AppendMessage("Current watchpoints:");
257       for (size_t i = 0; i < num_watchpoints; ++i) {
258         Watchpoint *wp = watchpoints.GetByIndex(i).get();
259         AddWatchpointDescription(&output_stream, wp, m_options.m_level);
260       }
261       result.SetStatus(eReturnStatusSuccessFinishNoResult);
262     } else {
263       // Particular watchpoints selected; enable them.
264       std::vector<uint32_t> wp_ids;
265       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
266               target, command, wp_ids)) {
267         result.AppendError("Invalid watchpoints specification.");
268         result.SetStatus(eReturnStatusFailed);
269         return false;
270       }
271 
272       const size_t size = wp_ids.size();
273       for (size_t i = 0; i < size; ++i) {
274         Watchpoint *wp = watchpoints.FindByID(wp_ids[i]).get();
275         if (wp)
276           AddWatchpointDescription(&output_stream, wp, m_options.m_level);
277         result.SetStatus(eReturnStatusSuccessFinishNoResult);
278       }
279     }
280 
281     return result.Succeeded();
282   }
283 
284 private:
285   CommandOptions m_options;
286 };
287 
288 // CommandObjectWatchpointEnable
289 #pragma mark Enable
290 
291 class CommandObjectWatchpointEnable : public CommandObjectParsed {
292 public:
293   CommandObjectWatchpointEnable(CommandInterpreter &interpreter)
294       : CommandObjectParsed(interpreter, "enable",
295                             "Enable the specified disabled watchpoint(s). If "
296                             "no watchpoints are specified, enable all of them.",
297                             nullptr) {
298     CommandArgumentEntry arg;
299     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
300                                       eArgTypeWatchpointIDRange);
301     // Add the entry for the first argument for this command to the object's
302     // arguments vector.
303     m_arguments.push_back(arg);
304   }
305 
306   ~CommandObjectWatchpointEnable() override = default;
307 
308 protected:
309   bool DoExecute(Args &command, CommandReturnObject &result) override {
310     Target *target = GetDebugger().GetSelectedTarget().get();
311     if (!CheckTargetForWatchpointOperations(target, result))
312       return false;
313 
314     std::unique_lock<std::recursive_mutex> lock;
315     target->GetWatchpointList().GetListMutex(lock);
316 
317     const WatchpointList &watchpoints = target->GetWatchpointList();
318 
319     size_t num_watchpoints = watchpoints.GetSize();
320 
321     if (num_watchpoints == 0) {
322       result.AppendError("No watchpoints exist to be enabled.");
323       result.SetStatus(eReturnStatusFailed);
324       return false;
325     }
326 
327     if (command.GetArgumentCount() == 0) {
328       // No watchpoint selected; enable all currently set watchpoints.
329       target->EnableAllWatchpoints();
330       result.AppendMessageWithFormat("All watchpoints enabled. (%" PRIu64
331                                      " watchpoints)\n",
332                                      (uint64_t)num_watchpoints);
333       result.SetStatus(eReturnStatusSuccessFinishNoResult);
334     } else {
335       // Particular watchpoints selected; enable them.
336       std::vector<uint32_t> wp_ids;
337       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
338               target, command, wp_ids)) {
339         result.AppendError("Invalid watchpoints specification.");
340         result.SetStatus(eReturnStatusFailed);
341         return false;
342       }
343 
344       int count = 0;
345       const size_t size = wp_ids.size();
346       for (size_t i = 0; i < size; ++i)
347         if (target->EnableWatchpointByID(wp_ids[i]))
348           ++count;
349       result.AppendMessageWithFormat("%d watchpoints enabled.\n", count);
350       result.SetStatus(eReturnStatusSuccessFinishNoResult);
351     }
352 
353     return result.Succeeded();
354   }
355 };
356 
357 // CommandObjectWatchpointDisable
358 #pragma mark Disable
359 
360 class CommandObjectWatchpointDisable : public CommandObjectParsed {
361 public:
362   CommandObjectWatchpointDisable(CommandInterpreter &interpreter)
363       : CommandObjectParsed(interpreter, "watchpoint disable",
364                             "Disable the specified watchpoint(s) without "
365                             "removing it/them.  If no watchpoints are "
366                             "specified, disable them all.",
367                             nullptr) {
368     CommandArgumentEntry arg;
369     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
370                                       eArgTypeWatchpointIDRange);
371     // Add the entry for the first argument for this command to the object's
372     // arguments vector.
373     m_arguments.push_back(arg);
374   }
375 
376   ~CommandObjectWatchpointDisable() override = default;
377 
378 protected:
379   bool DoExecute(Args &command, CommandReturnObject &result) override {
380     Target *target = GetDebugger().GetSelectedTarget().get();
381     if (!CheckTargetForWatchpointOperations(target, result))
382       return false;
383 
384     std::unique_lock<std::recursive_mutex> lock;
385     target->GetWatchpointList().GetListMutex(lock);
386 
387     const WatchpointList &watchpoints = target->GetWatchpointList();
388     size_t num_watchpoints = watchpoints.GetSize();
389 
390     if (num_watchpoints == 0) {
391       result.AppendError("No watchpoints exist to be disabled.");
392       result.SetStatus(eReturnStatusFailed);
393       return false;
394     }
395 
396     if (command.GetArgumentCount() == 0) {
397       // No watchpoint selected; disable all currently set watchpoints.
398       if (target->DisableAllWatchpoints()) {
399         result.AppendMessageWithFormat("All watchpoints disabled. (%" PRIu64
400                                        " watchpoints)\n",
401                                        (uint64_t)num_watchpoints);
402         result.SetStatus(eReturnStatusSuccessFinishNoResult);
403       } else {
404         result.AppendError("Disable all watchpoints failed\n");
405         result.SetStatus(eReturnStatusFailed);
406       }
407     } else {
408       // Particular watchpoints selected; disable them.
409       std::vector<uint32_t> wp_ids;
410       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
411               target, command, wp_ids)) {
412         result.AppendError("Invalid watchpoints specification.");
413         result.SetStatus(eReturnStatusFailed);
414         return false;
415       }
416 
417       int count = 0;
418       const size_t size = wp_ids.size();
419       for (size_t i = 0; i < size; ++i)
420         if (target->DisableWatchpointByID(wp_ids[i]))
421           ++count;
422       result.AppendMessageWithFormat("%d watchpoints disabled.\n", count);
423       result.SetStatus(eReturnStatusSuccessFinishNoResult);
424     }
425 
426     return result.Succeeded();
427   }
428 };
429 
430 // CommandObjectWatchpointDelete
431 #pragma mark Delete
432 
433 class CommandObjectWatchpointDelete : public CommandObjectParsed {
434 public:
435   CommandObjectWatchpointDelete(CommandInterpreter &interpreter)
436       : CommandObjectParsed(interpreter, "watchpoint delete",
437                             "Delete the specified watchpoint(s).  If no "
438                             "watchpoints are specified, delete them all.",
439                             nullptr) {
440     CommandArgumentEntry arg;
441     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
442                                       eArgTypeWatchpointIDRange);
443     // Add the entry for the first argument for this command to the object's
444     // arguments vector.
445     m_arguments.push_back(arg);
446   }
447 
448   ~CommandObjectWatchpointDelete() override = default;
449 
450 protected:
451   bool DoExecute(Args &command, CommandReturnObject &result) override {
452     Target *target = GetDebugger().GetSelectedTarget().get();
453     if (!CheckTargetForWatchpointOperations(target, result))
454       return false;
455 
456     std::unique_lock<std::recursive_mutex> lock;
457     target->GetWatchpointList().GetListMutex(lock);
458 
459     const WatchpointList &watchpoints = target->GetWatchpointList();
460 
461     size_t num_watchpoints = watchpoints.GetSize();
462 
463     if (num_watchpoints == 0) {
464       result.AppendError("No watchpoints exist to be deleted.");
465       result.SetStatus(eReturnStatusFailed);
466       return false;
467     }
468 
469     if (command.GetArgumentCount() == 0) {
470       if (!m_interpreter.Confirm(
471               "About to delete all watchpoints, do you want to do that?",
472               true)) {
473         result.AppendMessage("Operation cancelled...");
474       } else {
475         target->RemoveAllWatchpoints();
476         result.AppendMessageWithFormat("All watchpoints removed. (%" PRIu64
477                                        " watchpoints)\n",
478                                        (uint64_t)num_watchpoints);
479       }
480       result.SetStatus(eReturnStatusSuccessFinishNoResult);
481     } else {
482       // Particular watchpoints selected; delete them.
483       std::vector<uint32_t> wp_ids;
484       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
485               target, command, wp_ids)) {
486         result.AppendError("Invalid watchpoints specification.");
487         result.SetStatus(eReturnStatusFailed);
488         return false;
489       }
490 
491       int count = 0;
492       const size_t size = wp_ids.size();
493       for (size_t i = 0; i < size; ++i)
494         if (target->RemoveWatchpointByID(wp_ids[i]))
495           ++count;
496       result.AppendMessageWithFormat("%d watchpoints deleted.\n", count);
497       result.SetStatus(eReturnStatusSuccessFinishNoResult);
498     }
499 
500     return result.Succeeded();
501   }
502 };
503 
504 // CommandObjectWatchpointIgnore
505 
506 #pragma mark Ignore::CommandOptions
507 #define LLDB_OPTIONS_watchpoint_ignore
508 #include "CommandOptions.inc"
509 
510 class CommandObjectWatchpointIgnore : public CommandObjectParsed {
511 public:
512   CommandObjectWatchpointIgnore(CommandInterpreter &interpreter)
513       : CommandObjectParsed(interpreter, "watchpoint ignore",
514                             "Set ignore count on the specified watchpoint(s).  "
515                             "If no watchpoints are specified, set them all.",
516                             nullptr),
517         m_options() {
518     CommandArgumentEntry arg;
519     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
520                                       eArgTypeWatchpointIDRange);
521     // Add the entry for the first argument for this command to the object's
522     // arguments vector.
523     m_arguments.push_back(arg);
524   }
525 
526   ~CommandObjectWatchpointIgnore() override = default;
527 
528   Options *GetOptions() override { return &m_options; }
529 
530   class CommandOptions : public Options {
531   public:
532     CommandOptions() : Options(), m_ignore_count(0) {}
533 
534     ~CommandOptions() override = default;
535 
536     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
537                           ExecutionContext *execution_context) override {
538       Status error;
539       const int short_option = m_getopt_table[option_idx].val;
540 
541       switch (short_option) {
542       case 'i':
543         if (option_arg.getAsInteger(0, m_ignore_count))
544           error.SetErrorStringWithFormat("invalid ignore count '%s'",
545                                          option_arg.str().c_str());
546         break;
547       default:
548         error.SetErrorStringWithFormat("unrecognized option '%c'",
549                                        short_option);
550         break;
551       }
552 
553       return error;
554     }
555 
556     void OptionParsingStarting(ExecutionContext *execution_context) override {
557       m_ignore_count = 0;
558     }
559 
560     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
561       return llvm::makeArrayRef(g_watchpoint_ignore_options);
562     }
563 
564     // Instance variables to hold the values for command options.
565 
566     uint32_t m_ignore_count;
567   };
568 
569 protected:
570   bool DoExecute(Args &command, CommandReturnObject &result) override {
571     Target *target = GetDebugger().GetSelectedTarget().get();
572     if (!CheckTargetForWatchpointOperations(target, result))
573       return false;
574 
575     std::unique_lock<std::recursive_mutex> lock;
576     target->GetWatchpointList().GetListMutex(lock);
577 
578     const WatchpointList &watchpoints = target->GetWatchpointList();
579 
580     size_t num_watchpoints = watchpoints.GetSize();
581 
582     if (num_watchpoints == 0) {
583       result.AppendError("No watchpoints exist to be ignored.");
584       result.SetStatus(eReturnStatusFailed);
585       return false;
586     }
587 
588     if (command.GetArgumentCount() == 0) {
589       target->IgnoreAllWatchpoints(m_options.m_ignore_count);
590       result.AppendMessageWithFormat("All watchpoints ignored. (%" PRIu64
591                                      " watchpoints)\n",
592                                      (uint64_t)num_watchpoints);
593       result.SetStatus(eReturnStatusSuccessFinishNoResult);
594     } else {
595       // Particular watchpoints selected; ignore them.
596       std::vector<uint32_t> wp_ids;
597       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
598               target, command, wp_ids)) {
599         result.AppendError("Invalid watchpoints specification.");
600         result.SetStatus(eReturnStatusFailed);
601         return false;
602       }
603 
604       int count = 0;
605       const size_t size = wp_ids.size();
606       for (size_t i = 0; i < size; ++i)
607         if (target->IgnoreWatchpointByID(wp_ids[i], m_options.m_ignore_count))
608           ++count;
609       result.AppendMessageWithFormat("%d watchpoints ignored.\n", count);
610       result.SetStatus(eReturnStatusSuccessFinishNoResult);
611     }
612 
613     return result.Succeeded();
614   }
615 
616 private:
617   CommandOptions m_options;
618 };
619 
620 // CommandObjectWatchpointModify
621 
622 #pragma mark Modify::CommandOptions
623 #define LLDB_OPTIONS_watchpoint_modify
624 #include "CommandOptions.inc"
625 
626 #pragma mark Modify
627 
628 class CommandObjectWatchpointModify : public CommandObjectParsed {
629 public:
630   CommandObjectWatchpointModify(CommandInterpreter &interpreter)
631       : CommandObjectParsed(
632             interpreter, "watchpoint modify",
633             "Modify the options on a watchpoint or set of watchpoints in the "
634             "executable.  "
635             "If no watchpoint is specified, act on the last created "
636             "watchpoint.  "
637             "Passing an empty argument clears the modification.",
638             nullptr),
639         m_options() {
640     CommandArgumentEntry arg;
641     CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
642                                       eArgTypeWatchpointIDRange);
643     // Add the entry for the first argument for this command to the object's
644     // arguments vector.
645     m_arguments.push_back(arg);
646   }
647 
648   ~CommandObjectWatchpointModify() override = default;
649 
650   Options *GetOptions() override { return &m_options; }
651 
652   class CommandOptions : public Options {
653   public:
654     CommandOptions() : Options(), m_condition(), m_condition_passed(false) {}
655 
656     ~CommandOptions() override = default;
657 
658     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
659                           ExecutionContext *execution_context) override {
660       Status error;
661       const int short_option = m_getopt_table[option_idx].val;
662 
663       switch (short_option) {
664       case 'c':
665         m_condition = option_arg;
666         m_condition_passed = true;
667         break;
668       default:
669         error.SetErrorStringWithFormat("unrecognized option '%c'",
670                                        short_option);
671         break;
672       }
673 
674       return error;
675     }
676 
677     void OptionParsingStarting(ExecutionContext *execution_context) override {
678       m_condition.clear();
679       m_condition_passed = false;
680     }
681 
682     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
683       return llvm::makeArrayRef(g_watchpoint_modify_options);
684     }
685 
686     // Instance variables to hold the values for command options.
687 
688     std::string m_condition;
689     bool m_condition_passed;
690   };
691 
692 protected:
693   bool DoExecute(Args &command, CommandReturnObject &result) override {
694     Target *target = GetDebugger().GetSelectedTarget().get();
695     if (!CheckTargetForWatchpointOperations(target, result))
696       return false;
697 
698     std::unique_lock<std::recursive_mutex> lock;
699     target->GetWatchpointList().GetListMutex(lock);
700 
701     const WatchpointList &watchpoints = target->GetWatchpointList();
702 
703     size_t num_watchpoints = watchpoints.GetSize();
704 
705     if (num_watchpoints == 0) {
706       result.AppendError("No watchpoints exist to be modified.");
707       result.SetStatus(eReturnStatusFailed);
708       return false;
709     }
710 
711     if (command.GetArgumentCount() == 0) {
712       WatchpointSP wp_sp = target->GetLastCreatedWatchpoint();
713       wp_sp->SetCondition(m_options.m_condition.c_str());
714       result.SetStatus(eReturnStatusSuccessFinishNoResult);
715     } else {
716       // Particular watchpoints selected; set condition on them.
717       std::vector<uint32_t> wp_ids;
718       if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
719               target, command, wp_ids)) {
720         result.AppendError("Invalid watchpoints specification.");
721         result.SetStatus(eReturnStatusFailed);
722         return false;
723       }
724 
725       int count = 0;
726       const size_t size = wp_ids.size();
727       for (size_t i = 0; i < size; ++i) {
728         WatchpointSP wp_sp = watchpoints.FindByID(wp_ids[i]);
729         if (wp_sp) {
730           wp_sp->SetCondition(m_options.m_condition.c_str());
731           ++count;
732         }
733       }
734       result.AppendMessageWithFormat("%d watchpoints modified.\n", count);
735       result.SetStatus(eReturnStatusSuccessFinishNoResult);
736     }
737 
738     return result.Succeeded();
739   }
740 
741 private:
742   CommandOptions m_options;
743 };
744 
745 // CommandObjectWatchpointSetVariable
746 #pragma mark SetVariable
747 
748 class CommandObjectWatchpointSetVariable : public CommandObjectParsed {
749 public:
750   CommandObjectWatchpointSetVariable(CommandInterpreter &interpreter)
751       : CommandObjectParsed(
752             interpreter, "watchpoint set variable",
753             "Set a watchpoint on a variable. "
754             "Use the '-w' option to specify the type of watchpoint and "
755             "the '-s' option to specify the byte size to watch for. "
756             "If no '-w' option is specified, it defaults to write. "
757             "If no '-s' option is specified, it defaults to the variable's "
758             "byte size. "
759             "Note that there are limited hardware resources for watchpoints. "
760             "If watchpoint setting fails, consider disable/delete existing "
761             "ones "
762             "to free up resources.",
763             nullptr,
764             eCommandRequiresFrame | eCommandTryTargetAPILock |
765                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
766         m_option_group(), m_option_watchpoint() {
767     SetHelpLong(
768         R"(
769 Examples:
770 
771 (lldb) watchpoint set variable -w read_write my_global_var
772 
773 )"
774         "    Watches my_global_var for read/write access, with the region to watch \
775 corresponding to the byte size of the data type.");
776 
777     CommandArgumentEntry arg;
778     CommandArgumentData var_name_arg;
779 
780     // Define the only variant of this arg.
781     var_name_arg.arg_type = eArgTypeVarName;
782     var_name_arg.arg_repetition = eArgRepeatPlain;
783 
784     // Push the variant into the argument entry.
785     arg.push_back(var_name_arg);
786 
787     // Push the data for the only argument into the m_arguments vector.
788     m_arguments.push_back(arg);
789 
790     // Absorb the '-w' and '-s' options into our option group.
791     m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL,
792                           LLDB_OPT_SET_1);
793     m_option_group.Finalize();
794   }
795 
796   ~CommandObjectWatchpointSetVariable() override = default;
797 
798   Options *GetOptions() override { return &m_option_group; }
799 
800 protected:
801   static size_t GetVariableCallback(void *baton, const char *name,
802                                     VariableList &variable_list) {
803     Target *target = static_cast<Target *>(baton);
804     if (target) {
805       return target->GetImages().FindGlobalVariables(ConstString(name),
806                                                      UINT32_MAX, variable_list);
807     }
808     return 0;
809   }
810 
811   bool DoExecute(Args &command, CommandReturnObject &result) override {
812     Target *target = GetDebugger().GetSelectedTarget().get();
813     StackFrame *frame = m_exe_ctx.GetFramePtr();
814 
815     // If no argument is present, issue an error message.  There's no way to
816     // set a watchpoint.
817     if (command.GetArgumentCount() <= 0) {
818       result.GetErrorStream().Printf("error: required argument missing; "
819                                      "specify your program variable to watch "
820                                      "for\n");
821       result.SetStatus(eReturnStatusFailed);
822       return false;
823     }
824 
825     // If no '-w' is specified, default to '-w write'.
826     if (!m_option_watchpoint.watch_type_specified) {
827       m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite;
828     }
829 
830     // We passed the sanity check for the command. Proceed to set the
831     // watchpoint now.
832     lldb::addr_t addr = 0;
833     size_t size = 0;
834 
835     VariableSP var_sp;
836     ValueObjectSP valobj_sp;
837     Stream &output_stream = result.GetOutputStream();
838 
839     // A simple watch variable gesture allows only one argument.
840     if (command.GetArgumentCount() != 1) {
841       result.GetErrorStream().Printf(
842           "error: specify exactly one variable to watch for\n");
843       result.SetStatus(eReturnStatusFailed);
844       return false;
845     }
846 
847     // Things have checked out ok...
848     Status error;
849     uint32_t expr_path_options =
850         StackFrame::eExpressionPathOptionCheckPtrVsMember |
851         StackFrame::eExpressionPathOptionsAllowDirectIVarAccess;
852     valobj_sp = frame->GetValueForVariableExpressionPath(
853         command.GetArgumentAtIndex(0), eNoDynamicValues, expr_path_options,
854         var_sp, error);
855 
856     if (!valobj_sp) {
857       // Not in the frame; let's check the globals.
858 
859       VariableList variable_list;
860       ValueObjectList valobj_list;
861 
862       Status error(Variable::GetValuesForVariableExpressionPath(
863           command.GetArgumentAtIndex(0),
864           m_exe_ctx.GetBestExecutionContextScope(), GetVariableCallback, target,
865           variable_list, valobj_list));
866 
867       if (valobj_list.GetSize())
868         valobj_sp = valobj_list.GetValueObjectAtIndex(0);
869     }
870 
871     CompilerType compiler_type;
872 
873     if (valobj_sp) {
874       AddressType addr_type;
875       addr = valobj_sp->GetAddressOf(false, &addr_type);
876       if (addr_type == eAddressTypeLoad) {
877         // We're in business.
878         // Find out the size of this variable.
879         size = m_option_watchpoint.watch_size == 0
880                    ? valobj_sp->GetByteSize()
881                    : m_option_watchpoint.watch_size;
882       }
883       compiler_type = valobj_sp->GetCompilerType();
884     } else {
885       const char *error_cstr = error.AsCString(nullptr);
886       if (error_cstr)
887         result.GetErrorStream().Printf("error: %s\n", error_cstr);
888       else
889         result.GetErrorStream().Printf("error: unable to find any variable "
890                                        "expression path that matches '%s'\n",
891                                        command.GetArgumentAtIndex(0));
892       return false;
893     }
894 
895     // Now it's time to create the watchpoint.
896     uint32_t watch_type = m_option_watchpoint.watch_type;
897 
898     error.Clear();
899     Watchpoint *wp =
900         target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error)
901             .get();
902     if (wp) {
903       wp->SetWatchSpec(command.GetArgumentAtIndex(0));
904       wp->SetWatchVariable(true);
905       if (var_sp && var_sp->GetDeclaration().GetFile()) {
906         StreamString ss;
907         // True to show fullpath for declaration file.
908         var_sp->GetDeclaration().DumpStopContext(&ss, true);
909         wp->SetDeclInfo(ss.GetString());
910       }
911       output_stream.Printf("Watchpoint created: ");
912       wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull);
913       output_stream.EOL();
914       result.SetStatus(eReturnStatusSuccessFinishResult);
915     } else {
916       result.AppendErrorWithFormat(
917           "Watchpoint creation failed (addr=0x%" PRIx64 ", size=%" PRIu64
918           ", variable expression='%s').\n",
919           addr, (uint64_t)size, command.GetArgumentAtIndex(0));
920       if (error.AsCString(nullptr))
921         result.AppendError(error.AsCString());
922       result.SetStatus(eReturnStatusFailed);
923     }
924 
925     return result.Succeeded();
926   }
927 
928 private:
929   OptionGroupOptions m_option_group;
930   OptionGroupWatchpoint m_option_watchpoint;
931 };
932 
933 // CommandObjectWatchpointSetExpression
934 #pragma mark Set
935 
936 class CommandObjectWatchpointSetExpression : public CommandObjectRaw {
937 public:
938   CommandObjectWatchpointSetExpression(CommandInterpreter &interpreter)
939       : CommandObjectRaw(
940             interpreter, "watchpoint set expression",
941             "Set a watchpoint on an address by supplying an expression. "
942             "Use the '-w' option to specify the type of watchpoint and "
943             "the '-s' option to specify the byte size to watch for. "
944             "If no '-w' option is specified, it defaults to write. "
945             "If no '-s' option is specified, it defaults to the target's "
946             "pointer byte size. "
947             "Note that there are limited hardware resources for watchpoints. "
948             "If watchpoint setting fails, consider disable/delete existing "
949             "ones "
950             "to free up resources.",
951             "",
952             eCommandRequiresFrame | eCommandTryTargetAPILock |
953                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
954         m_option_group(), m_option_watchpoint() {
955     SetHelpLong(
956         R"(
957 Examples:
958 
959 (lldb) watchpoint set expression -w write -s 1 -- foo + 32
960 
961     Watches write access for the 1-byte region pointed to by the address 'foo + 32')");
962 
963     CommandArgumentEntry arg;
964     CommandArgumentData expression_arg;
965 
966     // Define the only variant of this arg.
967     expression_arg.arg_type = eArgTypeExpression;
968     expression_arg.arg_repetition = eArgRepeatPlain;
969 
970     // Push the only variant into the argument entry.
971     arg.push_back(expression_arg);
972 
973     // Push the data for the only argument into the m_arguments vector.
974     m_arguments.push_back(arg);
975 
976     // Absorb the '-w' and '-s' options into our option group.
977     m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL,
978                           LLDB_OPT_SET_1);
979     m_option_group.Finalize();
980   }
981 
982   ~CommandObjectWatchpointSetExpression() override = default;
983 
984   // Overrides base class's behavior where WantsCompletion =
985   // !WantsRawCommandString.
986   bool WantsCompletion() override { return true; }
987 
988   Options *GetOptions() override { return &m_option_group; }
989 
990 protected:
991   bool DoExecute(llvm::StringRef raw_command,
992                  CommandReturnObject &result) override {
993     auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
994     m_option_group.NotifyOptionParsingStarting(
995         &exe_ctx); // This is a raw command, so notify the option group
996 
997     Target *target = GetDebugger().GetSelectedTarget().get();
998     StackFrame *frame = m_exe_ctx.GetFramePtr();
999 
1000     OptionsWithRaw args(raw_command);
1001 
1002     llvm::StringRef expr = args.GetRawPart();
1003 
1004     if (args.HasArgs())
1005       if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
1006                                  exe_ctx))
1007         return false;
1008 
1009     // If no argument is present, issue an error message.  There's no way to
1010     // set a watchpoint.
1011     if (raw_command.trim().empty()) {
1012       result.GetErrorStream().Printf("error: required argument missing; "
1013                                      "specify an expression to evaulate into "
1014                                      "the address to watch for\n");
1015       result.SetStatus(eReturnStatusFailed);
1016       return false;
1017     }
1018 
1019     // If no '-w' is specified, default to '-w write'.
1020     if (!m_option_watchpoint.watch_type_specified) {
1021       m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite;
1022     }
1023 
1024     // We passed the sanity check for the command. Proceed to set the
1025     // watchpoint now.
1026     lldb::addr_t addr = 0;
1027     size_t size = 0;
1028 
1029     ValueObjectSP valobj_sp;
1030 
1031     // Use expression evaluation to arrive at the address to watch.
1032     EvaluateExpressionOptions options;
1033     options.SetCoerceToId(false);
1034     options.SetUnwindOnError(true);
1035     options.SetKeepInMemory(false);
1036     options.SetTryAllThreads(true);
1037     options.SetTimeout(llvm::None);
1038 
1039     ExpressionResults expr_result =
1040         target->EvaluateExpression(expr, frame, valobj_sp, options);
1041     if (expr_result != eExpressionCompleted) {
1042       result.GetErrorStream().Printf(
1043           "error: expression evaluation of address to watch failed\n");
1044       result.GetErrorStream() << "expression evaluated: \n" << expr << "\n";
1045       result.SetStatus(eReturnStatusFailed);
1046       return false;
1047     }
1048 
1049     // Get the address to watch.
1050     bool success = false;
1051     addr = valobj_sp->GetValueAsUnsigned(0, &success);
1052     if (!success) {
1053       result.GetErrorStream().Printf(
1054           "error: expression did not evaluate to an address\n");
1055       result.SetStatus(eReturnStatusFailed);
1056       return false;
1057     }
1058 
1059     if (m_option_watchpoint.watch_size != 0)
1060       size = m_option_watchpoint.watch_size;
1061     else
1062       size = target->GetArchitecture().GetAddressByteSize();
1063 
1064     // Now it's time to create the watchpoint.
1065     uint32_t watch_type = m_option_watchpoint.watch_type;
1066 
1067     // Fetch the type from the value object, the type of the watched object is
1068     // the pointee type
1069     /// of the expression, so convert to that if we  found a valid type.
1070     CompilerType compiler_type(valobj_sp->GetCompilerType());
1071 
1072     Status error;
1073     Watchpoint *wp =
1074         target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error)
1075             .get();
1076     if (wp) {
1077       Stream &output_stream = result.GetOutputStream();
1078       output_stream.Printf("Watchpoint created: ");
1079       wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull);
1080       output_stream.EOL();
1081       result.SetStatus(eReturnStatusSuccessFinishResult);
1082     } else {
1083       result.AppendErrorWithFormat("Watchpoint creation failed (addr=0x%" PRIx64
1084                                    ", size=%" PRIu64 ").\n",
1085                                    addr, (uint64_t)size);
1086       if (error.AsCString(nullptr))
1087         result.AppendError(error.AsCString());
1088       result.SetStatus(eReturnStatusFailed);
1089     }
1090 
1091     return result.Succeeded();
1092   }
1093 
1094 private:
1095   OptionGroupOptions m_option_group;
1096   OptionGroupWatchpoint m_option_watchpoint;
1097 };
1098 
1099 // CommandObjectWatchpointSet
1100 #pragma mark Set
1101 
1102 class CommandObjectWatchpointSet : public CommandObjectMultiword {
1103 public:
1104   CommandObjectWatchpointSet(CommandInterpreter &interpreter)
1105       : CommandObjectMultiword(
1106             interpreter, "watchpoint set", "Commands for setting a watchpoint.",
1107             "watchpoint set <subcommand> [<subcommand-options>]") {
1108 
1109     LoadSubCommand(
1110         "variable",
1111         CommandObjectSP(new CommandObjectWatchpointSetVariable(interpreter)));
1112     LoadSubCommand(
1113         "expression",
1114         CommandObjectSP(new CommandObjectWatchpointSetExpression(interpreter)));
1115   }
1116 
1117   ~CommandObjectWatchpointSet() override = default;
1118 };
1119 
1120 // CommandObjectMultiwordWatchpoint
1121 #pragma mark MultiwordWatchpoint
1122 
1123 CommandObjectMultiwordWatchpoint::CommandObjectMultiwordWatchpoint(
1124     CommandInterpreter &interpreter)
1125     : CommandObjectMultiword(interpreter, "watchpoint",
1126                              "Commands for operating on watchpoints.",
1127                              "watchpoint <subcommand> [<command-options>]") {
1128   CommandObjectSP list_command_object(
1129       new CommandObjectWatchpointList(interpreter));
1130   CommandObjectSP enable_command_object(
1131       new CommandObjectWatchpointEnable(interpreter));
1132   CommandObjectSP disable_command_object(
1133       new CommandObjectWatchpointDisable(interpreter));
1134   CommandObjectSP delete_command_object(
1135       new CommandObjectWatchpointDelete(interpreter));
1136   CommandObjectSP ignore_command_object(
1137       new CommandObjectWatchpointIgnore(interpreter));
1138   CommandObjectSP command_command_object(
1139       new CommandObjectWatchpointCommand(interpreter));
1140   CommandObjectSP modify_command_object(
1141       new CommandObjectWatchpointModify(interpreter));
1142   CommandObjectSP set_command_object(
1143       new CommandObjectWatchpointSet(interpreter));
1144 
1145   list_command_object->SetCommandName("watchpoint list");
1146   enable_command_object->SetCommandName("watchpoint enable");
1147   disable_command_object->SetCommandName("watchpoint disable");
1148   delete_command_object->SetCommandName("watchpoint delete");
1149   ignore_command_object->SetCommandName("watchpoint ignore");
1150   command_command_object->SetCommandName("watchpoint command");
1151   modify_command_object->SetCommandName("watchpoint modify");
1152   set_command_object->SetCommandName("watchpoint set");
1153 
1154   LoadSubCommand("list", list_command_object);
1155   LoadSubCommand("enable", enable_command_object);
1156   LoadSubCommand("disable", disable_command_object);
1157   LoadSubCommand("delete", delete_command_object);
1158   LoadSubCommand("ignore", ignore_command_object);
1159   LoadSubCommand("command", command_command_object);
1160   LoadSubCommand("modify", modify_command_object);
1161   LoadSubCommand("set", set_command_object);
1162 }
1163 
1164 CommandObjectMultiwordWatchpoint::~CommandObjectMultiwordWatchpoint() = default;
1165