1 //===-- CommandObjectWatchpoint.cpp -----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "CommandObjectWatchpoint.h"
10 #include "CommandObjectWatchpointCommand.h"
14 #include "llvm/ADT/StringRef.h"
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"
31 using namespace lldb_private;
33 static void AddWatchpointDescription(Stream *s, Watchpoint *wp,
34 lldb::DescriptionLevel level) {
36 wp->GetDescription(s, level);
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);
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);
55 // Target passes our checks, return true.
59 // Equivalent class: {"-", "to", "To", "TO"} of range specifier array.
60 static const char *RSA[4] = {"-", "to", "To", "TO"};
62 // Return the index to RSA if found; otherwise -1 is returned.
63 static int32_t WithRSAIndex(llvm::StringRef Arg) {
66 for (i = 0; i < 4; ++i)
67 if (Arg.find(RSA[i]) != llvm::StringRef::npos)
72 // Return true if wp_ids is successfully populated with the watch ids. False
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)
80 WatchpointSP watch_sp = target->GetLastCreatedWatchpoint();
82 wp_ids.push_back(watch_sp->GetID());
88 llvm::StringRef Minus("-");
89 std::vector<llvm::StringRef> StrRefArgs;
90 llvm::StringRef first;
91 llvm::StringRef second;
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);
101 // The Arg contains the range specifier, split it, then.
102 std::tie(first, second) = entry.ref.split(RSA[idx]);
104 StrRefArgs.push_back(first);
105 StrRefArgs.push_back(Minus);
107 StrRefArgs.push_back(second);
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];
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))
121 // Found a range! Now append the elements.
122 for (id = beg; id <= end; ++id)
123 wp_ids.push_back(id);
127 if (i < (size - 1) && StrRefArgs[i + 1] == Minus) {
128 if (Arg.getAsInteger(0, beg))
130 // Turn on the in_range flag, we are looking for end of range next.
135 // Otherwise, we have a simple ID. Just append it.
136 if (Arg.getAsInteger(0, beg))
138 wp_ids.push_back(beg);
141 // It is an error if after the loop, we're still in_range.
145 // CommandObjectWatchpointList
147 // CommandObjectWatchpointList::Options
148 #pragma mark List::CommandOptions
150 static constexpr OptionDefinition g_watchpoint_list_options[] = {
151 #define LLDB_OPTIONS_watchpoint_list
152 #include "CommandOptions.inc"
157 class CommandObjectWatchpointList : public CommandObjectParsed {
159 CommandObjectWatchpointList(CommandInterpreter &interpreter)
160 : CommandObjectParsed(
161 interpreter, "watchpoint list",
162 "List all watchpoints at configurable levels of detail.", nullptr),
164 CommandArgumentEntry arg;
165 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
166 eArgTypeWatchpointIDRange);
167 // Add the entry for the first argument for this command to the object's
169 m_arguments.push_back(arg);
172 ~CommandObjectWatchpointList() override = default;
174 Options *GetOptions() override { return &m_options; }
176 class CommandOptions : public Options {
180 m_level(lldb::eDescriptionLevelBrief) // Watchpoint List defaults to
181 // brief descriptions
184 ~CommandOptions() override = default;
186 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
187 ExecutionContext *execution_context) override {
189 const int short_option = m_getopt_table[option_idx].val;
191 switch (short_option) {
193 m_level = lldb::eDescriptionLevelBrief;
196 m_level = lldb::eDescriptionLevelFull;
199 m_level = lldb::eDescriptionLevelVerbose;
202 error.SetErrorStringWithFormat("unrecognized option '%c'",
210 void OptionParsingStarting(ExecutionContext *execution_context) override {
211 m_level = lldb::eDescriptionLevelFull;
214 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
215 return llvm::makeArrayRef(g_watchpoint_list_options);
218 // Instance variables to hold the values for command options.
220 lldb::DescriptionLevel m_level;
224 bool DoExecute(Args &command, CommandReturnObject &result) override {
225 Target *target = GetDebugger().GetSelectedTarget().get();
226 if (target == nullptr) {
227 result.AppendError("Invalid target. No current target or watchpoints.");
228 result.SetStatus(eReturnStatusSuccessFinishNoResult);
232 if (target->GetProcessSP() && target->GetProcessSP()->IsAlive()) {
233 uint32_t num_supported_hardware_watchpoints;
234 Status error = target->GetProcessSP()->GetWatchpointSupportInfo(
235 num_supported_hardware_watchpoints);
237 result.AppendMessageWithFormat(
238 "Number of supported hardware watchpoints: %u\n",
239 num_supported_hardware_watchpoints);
242 const WatchpointList &watchpoints = target->GetWatchpointList();
244 std::unique_lock<std::recursive_mutex> lock;
245 target->GetWatchpointList().GetListMutex(lock);
247 size_t num_watchpoints = watchpoints.GetSize();
249 if (num_watchpoints == 0) {
250 result.AppendMessage("No watchpoints currently set.");
251 result.SetStatus(eReturnStatusSuccessFinishNoResult);
255 Stream &output_stream = result.GetOutputStream();
257 if (command.GetArgumentCount() == 0) {
258 // No watchpoint selected; show info about all currently set watchpoints.
259 result.AppendMessage("Current watchpoints:");
260 for (size_t i = 0; i < num_watchpoints; ++i) {
261 Watchpoint *wp = watchpoints.GetByIndex(i).get();
262 AddWatchpointDescription(&output_stream, wp, m_options.m_level);
264 result.SetStatus(eReturnStatusSuccessFinishNoResult);
266 // Particular watchpoints selected; enable them.
267 std::vector<uint32_t> wp_ids;
268 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
269 target, command, wp_ids)) {
270 result.AppendError("Invalid watchpoints specification.");
271 result.SetStatus(eReturnStatusFailed);
275 const size_t size = wp_ids.size();
276 for (size_t i = 0; i < size; ++i) {
277 Watchpoint *wp = watchpoints.FindByID(wp_ids[i]).get();
279 AddWatchpointDescription(&output_stream, wp, m_options.m_level);
280 result.SetStatus(eReturnStatusSuccessFinishNoResult);
284 return result.Succeeded();
288 CommandOptions m_options;
291 // CommandObjectWatchpointEnable
294 class CommandObjectWatchpointEnable : public CommandObjectParsed {
296 CommandObjectWatchpointEnable(CommandInterpreter &interpreter)
297 : CommandObjectParsed(interpreter, "enable",
298 "Enable the specified disabled watchpoint(s). If "
299 "no watchpoints are specified, enable all of them.",
301 CommandArgumentEntry arg;
302 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
303 eArgTypeWatchpointIDRange);
304 // Add the entry for the first argument for this command to the object's
306 m_arguments.push_back(arg);
309 ~CommandObjectWatchpointEnable() override = default;
312 bool DoExecute(Args &command, CommandReturnObject &result) override {
313 Target *target = GetDebugger().GetSelectedTarget().get();
314 if (!CheckTargetForWatchpointOperations(target, result))
317 std::unique_lock<std::recursive_mutex> lock;
318 target->GetWatchpointList().GetListMutex(lock);
320 const WatchpointList &watchpoints = target->GetWatchpointList();
322 size_t num_watchpoints = watchpoints.GetSize();
324 if (num_watchpoints == 0) {
325 result.AppendError("No watchpoints exist to be enabled.");
326 result.SetStatus(eReturnStatusFailed);
330 if (command.GetArgumentCount() == 0) {
331 // No watchpoint selected; enable all currently set watchpoints.
332 target->EnableAllWatchpoints();
333 result.AppendMessageWithFormat("All watchpoints enabled. (%" PRIu64
335 (uint64_t)num_watchpoints);
336 result.SetStatus(eReturnStatusSuccessFinishNoResult);
338 // Particular watchpoints selected; enable them.
339 std::vector<uint32_t> wp_ids;
340 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
341 target, command, wp_ids)) {
342 result.AppendError("Invalid watchpoints specification.");
343 result.SetStatus(eReturnStatusFailed);
348 const size_t size = wp_ids.size();
349 for (size_t i = 0; i < size; ++i)
350 if (target->EnableWatchpointByID(wp_ids[i]))
352 result.AppendMessageWithFormat("%d watchpoints enabled.\n", count);
353 result.SetStatus(eReturnStatusSuccessFinishNoResult);
356 return result.Succeeded();
360 // CommandObjectWatchpointDisable
363 class CommandObjectWatchpointDisable : public CommandObjectParsed {
365 CommandObjectWatchpointDisable(CommandInterpreter &interpreter)
366 : CommandObjectParsed(interpreter, "watchpoint disable",
367 "Disable the specified watchpoint(s) without "
368 "removing it/them. If no watchpoints are "
369 "specified, disable them all.",
371 CommandArgumentEntry arg;
372 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
373 eArgTypeWatchpointIDRange);
374 // Add the entry for the first argument for this command to the object's
376 m_arguments.push_back(arg);
379 ~CommandObjectWatchpointDisable() override = default;
382 bool DoExecute(Args &command, CommandReturnObject &result) override {
383 Target *target = GetDebugger().GetSelectedTarget().get();
384 if (!CheckTargetForWatchpointOperations(target, result))
387 std::unique_lock<std::recursive_mutex> lock;
388 target->GetWatchpointList().GetListMutex(lock);
390 const WatchpointList &watchpoints = target->GetWatchpointList();
391 size_t num_watchpoints = watchpoints.GetSize();
393 if (num_watchpoints == 0) {
394 result.AppendError("No watchpoints exist to be disabled.");
395 result.SetStatus(eReturnStatusFailed);
399 if (command.GetArgumentCount() == 0) {
400 // No watchpoint selected; disable all currently set watchpoints.
401 if (target->DisableAllWatchpoints()) {
402 result.AppendMessageWithFormat("All watchpoints disabled. (%" PRIu64
404 (uint64_t)num_watchpoints);
405 result.SetStatus(eReturnStatusSuccessFinishNoResult);
407 result.AppendError("Disable all watchpoints failed\n");
408 result.SetStatus(eReturnStatusFailed);
411 // Particular watchpoints selected; disable them.
412 std::vector<uint32_t> wp_ids;
413 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
414 target, command, wp_ids)) {
415 result.AppendError("Invalid watchpoints specification.");
416 result.SetStatus(eReturnStatusFailed);
421 const size_t size = wp_ids.size();
422 for (size_t i = 0; i < size; ++i)
423 if (target->DisableWatchpointByID(wp_ids[i]))
425 result.AppendMessageWithFormat("%d watchpoints disabled.\n", count);
426 result.SetStatus(eReturnStatusSuccessFinishNoResult);
429 return result.Succeeded();
433 // CommandObjectWatchpointDelete
436 class CommandObjectWatchpointDelete : public CommandObjectParsed {
438 CommandObjectWatchpointDelete(CommandInterpreter &interpreter)
439 : CommandObjectParsed(interpreter, "watchpoint delete",
440 "Delete the specified watchpoint(s). If no "
441 "watchpoints are specified, delete them all.",
443 CommandArgumentEntry arg;
444 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
445 eArgTypeWatchpointIDRange);
446 // Add the entry for the first argument for this command to the object's
448 m_arguments.push_back(arg);
451 ~CommandObjectWatchpointDelete() override = default;
454 bool DoExecute(Args &command, CommandReturnObject &result) override {
455 Target *target = GetDebugger().GetSelectedTarget().get();
456 if (!CheckTargetForWatchpointOperations(target, result))
459 std::unique_lock<std::recursive_mutex> lock;
460 target->GetWatchpointList().GetListMutex(lock);
462 const WatchpointList &watchpoints = target->GetWatchpointList();
464 size_t num_watchpoints = watchpoints.GetSize();
466 if (num_watchpoints == 0) {
467 result.AppendError("No watchpoints exist to be deleted.");
468 result.SetStatus(eReturnStatusFailed);
472 if (command.GetArgumentCount() == 0) {
473 if (!m_interpreter.Confirm(
474 "About to delete all watchpoints, do you want to do that?",
476 result.AppendMessage("Operation cancelled...");
478 target->RemoveAllWatchpoints();
479 result.AppendMessageWithFormat("All watchpoints removed. (%" PRIu64
481 (uint64_t)num_watchpoints);
483 result.SetStatus(eReturnStatusSuccessFinishNoResult);
485 // Particular watchpoints selected; delete them.
486 std::vector<uint32_t> wp_ids;
487 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
488 target, command, wp_ids)) {
489 result.AppendError("Invalid watchpoints specification.");
490 result.SetStatus(eReturnStatusFailed);
495 const size_t size = wp_ids.size();
496 for (size_t i = 0; i < size; ++i)
497 if (target->RemoveWatchpointByID(wp_ids[i]))
499 result.AppendMessageWithFormat("%d watchpoints deleted.\n", count);
500 result.SetStatus(eReturnStatusSuccessFinishNoResult);
503 return result.Succeeded();
507 // CommandObjectWatchpointIgnore
509 #pragma mark Ignore::CommandOptions
510 static constexpr OptionDefinition g_watchpoint_ignore_options[] = {
511 #define LLDB_OPTIONS_watchpoint_ignore
512 #include "CommandOptions.inc"
515 class CommandObjectWatchpointIgnore : public CommandObjectParsed {
517 CommandObjectWatchpointIgnore(CommandInterpreter &interpreter)
518 : CommandObjectParsed(interpreter, "watchpoint ignore",
519 "Set ignore count on the specified watchpoint(s). "
520 "If no watchpoints are specified, set them all.",
523 CommandArgumentEntry arg;
524 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
525 eArgTypeWatchpointIDRange);
526 // Add the entry for the first argument for this command to the object's
528 m_arguments.push_back(arg);
531 ~CommandObjectWatchpointIgnore() override = default;
533 Options *GetOptions() override { return &m_options; }
535 class CommandOptions : public Options {
537 CommandOptions() : Options(), m_ignore_count(0) {}
539 ~CommandOptions() override = default;
541 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
542 ExecutionContext *execution_context) override {
544 const int short_option = m_getopt_table[option_idx].val;
546 switch (short_option) {
548 if (option_arg.getAsInteger(0, m_ignore_count))
549 error.SetErrorStringWithFormat("invalid ignore count '%s'",
550 option_arg.str().c_str());
553 error.SetErrorStringWithFormat("unrecognized option '%c'",
561 void OptionParsingStarting(ExecutionContext *execution_context) override {
565 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
566 return llvm::makeArrayRef(g_watchpoint_ignore_options);
569 // Instance variables to hold the values for command options.
571 uint32_t m_ignore_count;
575 bool DoExecute(Args &command, CommandReturnObject &result) override {
576 Target *target = GetDebugger().GetSelectedTarget().get();
577 if (!CheckTargetForWatchpointOperations(target, result))
580 std::unique_lock<std::recursive_mutex> lock;
581 target->GetWatchpointList().GetListMutex(lock);
583 const WatchpointList &watchpoints = target->GetWatchpointList();
585 size_t num_watchpoints = watchpoints.GetSize();
587 if (num_watchpoints == 0) {
588 result.AppendError("No watchpoints exist to be ignored.");
589 result.SetStatus(eReturnStatusFailed);
593 if (command.GetArgumentCount() == 0) {
594 target->IgnoreAllWatchpoints(m_options.m_ignore_count);
595 result.AppendMessageWithFormat("All watchpoints ignored. (%" PRIu64
597 (uint64_t)num_watchpoints);
598 result.SetStatus(eReturnStatusSuccessFinishNoResult);
600 // Particular watchpoints selected; ignore them.
601 std::vector<uint32_t> wp_ids;
602 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
603 target, command, wp_ids)) {
604 result.AppendError("Invalid watchpoints specification.");
605 result.SetStatus(eReturnStatusFailed);
610 const size_t size = wp_ids.size();
611 for (size_t i = 0; i < size; ++i)
612 if (target->IgnoreWatchpointByID(wp_ids[i], m_options.m_ignore_count))
614 result.AppendMessageWithFormat("%d watchpoints ignored.\n", count);
615 result.SetStatus(eReturnStatusSuccessFinishNoResult);
618 return result.Succeeded();
622 CommandOptions m_options;
625 // CommandObjectWatchpointModify
627 #pragma mark Modify::CommandOptions
629 static constexpr OptionDefinition g_watchpoint_modify_options[] = {
630 #define LLDB_OPTIONS_watchpoint_modify
631 #include "CommandOptions.inc"
636 class CommandObjectWatchpointModify : public CommandObjectParsed {
638 CommandObjectWatchpointModify(CommandInterpreter &interpreter)
639 : CommandObjectParsed(
640 interpreter, "watchpoint modify",
641 "Modify the options on a watchpoint or set of watchpoints in the "
643 "If no watchpoint is specified, act on the last created "
645 "Passing an empty argument clears the modification.",
648 CommandArgumentEntry arg;
649 CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID,
650 eArgTypeWatchpointIDRange);
651 // Add the entry for the first argument for this command to the object's
653 m_arguments.push_back(arg);
656 ~CommandObjectWatchpointModify() override = default;
658 Options *GetOptions() override { return &m_options; }
660 class CommandOptions : public Options {
662 CommandOptions() : Options(), m_condition(), m_condition_passed(false) {}
664 ~CommandOptions() override = default;
666 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
667 ExecutionContext *execution_context) override {
669 const int short_option = m_getopt_table[option_idx].val;
671 switch (short_option) {
673 m_condition = option_arg;
674 m_condition_passed = true;
677 error.SetErrorStringWithFormat("unrecognized option '%c'",
685 void OptionParsingStarting(ExecutionContext *execution_context) override {
687 m_condition_passed = false;
690 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
691 return llvm::makeArrayRef(g_watchpoint_modify_options);
694 // Instance variables to hold the values for command options.
696 std::string m_condition;
697 bool m_condition_passed;
701 bool DoExecute(Args &command, CommandReturnObject &result) override {
702 Target *target = GetDebugger().GetSelectedTarget().get();
703 if (!CheckTargetForWatchpointOperations(target, result))
706 std::unique_lock<std::recursive_mutex> lock;
707 target->GetWatchpointList().GetListMutex(lock);
709 const WatchpointList &watchpoints = target->GetWatchpointList();
711 size_t num_watchpoints = watchpoints.GetSize();
713 if (num_watchpoints == 0) {
714 result.AppendError("No watchpoints exist to be modified.");
715 result.SetStatus(eReturnStatusFailed);
719 if (command.GetArgumentCount() == 0) {
720 WatchpointSP wp_sp = target->GetLastCreatedWatchpoint();
721 wp_sp->SetCondition(m_options.m_condition.c_str());
722 result.SetStatus(eReturnStatusSuccessFinishNoResult);
724 // Particular watchpoints selected; set condition on them.
725 std::vector<uint32_t> wp_ids;
726 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(
727 target, command, wp_ids)) {
728 result.AppendError("Invalid watchpoints specification.");
729 result.SetStatus(eReturnStatusFailed);
734 const size_t size = wp_ids.size();
735 for (size_t i = 0; i < size; ++i) {
736 WatchpointSP wp_sp = watchpoints.FindByID(wp_ids[i]);
738 wp_sp->SetCondition(m_options.m_condition.c_str());
742 result.AppendMessageWithFormat("%d watchpoints modified.\n", count);
743 result.SetStatus(eReturnStatusSuccessFinishNoResult);
746 return result.Succeeded();
750 CommandOptions m_options;
753 // CommandObjectWatchpointSetVariable
754 #pragma mark SetVariable
756 class CommandObjectWatchpointSetVariable : public CommandObjectParsed {
758 CommandObjectWatchpointSetVariable(CommandInterpreter &interpreter)
759 : CommandObjectParsed(
760 interpreter, "watchpoint set variable",
761 "Set a watchpoint on a variable. "
762 "Use the '-w' option to specify the type of watchpoint and "
763 "the '-s' option to specify the byte size to watch for. "
764 "If no '-w' option is specified, it defaults to write. "
765 "If no '-s' option is specified, it defaults to the variable's "
767 "Note that there are limited hardware resources for watchpoints. "
768 "If watchpoint setting fails, consider disable/delete existing "
770 "to free up resources.",
772 eCommandRequiresFrame | eCommandTryTargetAPILock |
773 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
774 m_option_group(), m_option_watchpoint() {
779 (lldb) watchpoint set variable -w read_write my_global_var
782 " Watches my_global_var for read/write access, with the region to watch \
783 corresponding to the byte size of the data type.");
785 CommandArgumentEntry arg;
786 CommandArgumentData var_name_arg;
788 // Define the only variant of this arg.
789 var_name_arg.arg_type = eArgTypeVarName;
790 var_name_arg.arg_repetition = eArgRepeatPlain;
792 // Push the variant into the argument entry.
793 arg.push_back(var_name_arg);
795 // Push the data for the only argument into the m_arguments vector.
796 m_arguments.push_back(arg);
798 // Absorb the '-w' and '-s' options into our option group.
799 m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL,
801 m_option_group.Finalize();
804 ~CommandObjectWatchpointSetVariable() override = default;
806 Options *GetOptions() override { return &m_option_group; }
809 static size_t GetVariableCallback(void *baton, const char *name,
810 VariableList &variable_list) {
811 Target *target = static_cast<Target *>(baton);
813 return target->GetImages().FindGlobalVariables(ConstString(name),
814 UINT32_MAX, variable_list);
819 bool DoExecute(Args &command, CommandReturnObject &result) override {
820 Target *target = GetDebugger().GetSelectedTarget().get();
821 StackFrame *frame = m_exe_ctx.GetFramePtr();
823 // If no argument is present, issue an error message. There's no way to
825 if (command.GetArgumentCount() <= 0) {
826 result.GetErrorStream().Printf("error: required argument missing; "
827 "specify your program variable to watch "
829 result.SetStatus(eReturnStatusFailed);
833 // If no '-w' is specified, default to '-w write'.
834 if (!m_option_watchpoint.watch_type_specified) {
835 m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite;
838 // We passed the sanity check for the command. Proceed to set the
840 lldb::addr_t addr = 0;
844 ValueObjectSP valobj_sp;
845 Stream &output_stream = result.GetOutputStream();
847 // A simple watch variable gesture allows only one argument.
848 if (command.GetArgumentCount() != 1) {
849 result.GetErrorStream().Printf(
850 "error: specify exactly one variable to watch for\n");
851 result.SetStatus(eReturnStatusFailed);
855 // Things have checked out ok...
857 uint32_t expr_path_options =
858 StackFrame::eExpressionPathOptionCheckPtrVsMember |
859 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess;
860 valobj_sp = frame->GetValueForVariableExpressionPath(
861 command.GetArgumentAtIndex(0), eNoDynamicValues, expr_path_options,
865 // Not in the frame; let's check the globals.
867 VariableList variable_list;
868 ValueObjectList valobj_list;
870 Status error(Variable::GetValuesForVariableExpressionPath(
871 command.GetArgumentAtIndex(0),
872 m_exe_ctx.GetBestExecutionContextScope(), GetVariableCallback, target,
873 variable_list, valobj_list));
875 if (valobj_list.GetSize())
876 valobj_sp = valobj_list.GetValueObjectAtIndex(0);
879 CompilerType compiler_type;
882 AddressType addr_type;
883 addr = valobj_sp->GetAddressOf(false, &addr_type);
884 if (addr_type == eAddressTypeLoad) {
885 // We're in business.
886 // Find out the size of this variable.
887 size = m_option_watchpoint.watch_size == 0
888 ? valobj_sp->GetByteSize()
889 : m_option_watchpoint.watch_size;
891 compiler_type = valobj_sp->GetCompilerType();
893 const char *error_cstr = error.AsCString(nullptr);
895 result.GetErrorStream().Printf("error: %s\n", error_cstr);
897 result.GetErrorStream().Printf("error: unable to find any variable "
898 "expression path that matches '%s'\n",
899 command.GetArgumentAtIndex(0));
903 // Now it's time to create the watchpoint.
904 uint32_t watch_type = m_option_watchpoint.watch_type;
908 target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error)
911 wp->SetWatchSpec(command.GetArgumentAtIndex(0));
912 wp->SetWatchVariable(true);
913 if (var_sp && var_sp->GetDeclaration().GetFile()) {
915 // True to show fullpath for declaration file.
916 var_sp->GetDeclaration().DumpStopContext(&ss, true);
917 wp->SetDeclInfo(ss.GetString());
919 output_stream.Printf("Watchpoint created: ");
920 wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull);
922 result.SetStatus(eReturnStatusSuccessFinishResult);
924 result.AppendErrorWithFormat(
925 "Watchpoint creation failed (addr=0x%" PRIx64 ", size=%" PRIu64
926 ", variable expression='%s').\n",
927 addr, (uint64_t)size, command.GetArgumentAtIndex(0));
928 if (error.AsCString(nullptr))
929 result.AppendError(error.AsCString());
930 result.SetStatus(eReturnStatusFailed);
933 return result.Succeeded();
937 OptionGroupOptions m_option_group;
938 OptionGroupWatchpoint m_option_watchpoint;
941 // CommandObjectWatchpointSetExpression
944 class CommandObjectWatchpointSetExpression : public CommandObjectRaw {
946 CommandObjectWatchpointSetExpression(CommandInterpreter &interpreter)
948 interpreter, "watchpoint set expression",
949 "Set a watchpoint on an address by supplying an expression. "
950 "Use the '-w' option to specify the type of watchpoint and "
951 "the '-s' option to specify the byte size to watch for. "
952 "If no '-w' option is specified, it defaults to write. "
953 "If no '-s' option is specified, it defaults to the target's "
954 "pointer byte size. "
955 "Note that there are limited hardware resources for watchpoints. "
956 "If watchpoint setting fails, consider disable/delete existing "
958 "to free up resources.",
960 eCommandRequiresFrame | eCommandTryTargetAPILock |
961 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
962 m_option_group(), m_option_watchpoint() {
967 (lldb) watchpoint set expression -w write -s 1 -- foo + 32
969 Watches write access for the 1-byte region pointed to by the address 'foo + 32')");
971 CommandArgumentEntry arg;
972 CommandArgumentData expression_arg;
974 // Define the only variant of this arg.
975 expression_arg.arg_type = eArgTypeExpression;
976 expression_arg.arg_repetition = eArgRepeatPlain;
978 // Push the only variant into the argument entry.
979 arg.push_back(expression_arg);
981 // Push the data for the only argument into the m_arguments vector.
982 m_arguments.push_back(arg);
984 // Absorb the '-w' and '-s' options into our option group.
985 m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL,
987 m_option_group.Finalize();
990 ~CommandObjectWatchpointSetExpression() override = default;
992 // Overrides base class's behavior where WantsCompletion =
993 // !WantsRawCommandString.
994 bool WantsCompletion() override { return true; }
996 Options *GetOptions() override { return &m_option_group; }
999 bool DoExecute(llvm::StringRef raw_command,
1000 CommandReturnObject &result) override {
1001 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
1002 m_option_group.NotifyOptionParsingStarting(
1003 &exe_ctx); // This is a raw command, so notify the option group
1005 Target *target = GetDebugger().GetSelectedTarget().get();
1006 StackFrame *frame = m_exe_ctx.GetFramePtr();
1008 OptionsWithRaw args(raw_command);
1010 llvm::StringRef expr = args.GetRawPart();
1013 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
1017 // If no argument is present, issue an error message. There's no way to
1018 // set a watchpoint.
1019 if (raw_command.trim().empty()) {
1020 result.GetErrorStream().Printf("error: required argument missing; "
1021 "specify an expression to evaulate into "
1022 "the address to watch for\n");
1023 result.SetStatus(eReturnStatusFailed);
1027 // If no '-w' is specified, default to '-w write'.
1028 if (!m_option_watchpoint.watch_type_specified) {
1029 m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite;
1032 // We passed the sanity check for the command. Proceed to set the
1034 lldb::addr_t addr = 0;
1037 ValueObjectSP valobj_sp;
1039 // Use expression evaluation to arrive at the address to watch.
1040 EvaluateExpressionOptions options;
1041 options.SetCoerceToId(false);
1042 options.SetUnwindOnError(true);
1043 options.SetKeepInMemory(false);
1044 options.SetTryAllThreads(true);
1045 options.SetTimeout(llvm::None);
1047 ExpressionResults expr_result =
1048 target->EvaluateExpression(expr, frame, valobj_sp, options);
1049 if (expr_result != eExpressionCompleted) {
1050 result.GetErrorStream().Printf(
1051 "error: expression evaluation of address to watch failed\n");
1052 result.GetErrorStream() << "expression evaluated: \n" << expr << "\n";
1053 result.SetStatus(eReturnStatusFailed);
1057 // Get the address to watch.
1058 bool success = false;
1059 addr = valobj_sp->GetValueAsUnsigned(0, &success);
1061 result.GetErrorStream().Printf(
1062 "error: expression did not evaluate to an address\n");
1063 result.SetStatus(eReturnStatusFailed);
1067 if (m_option_watchpoint.watch_size != 0)
1068 size = m_option_watchpoint.watch_size;
1070 size = target->GetArchitecture().GetAddressByteSize();
1072 // Now it's time to create the watchpoint.
1073 uint32_t watch_type = m_option_watchpoint.watch_type;
1075 // Fetch the type from the value object, the type of the watched object is
1077 /// of the expression, so convert to that if we found a valid type.
1078 CompilerType compiler_type(valobj_sp->GetCompilerType());
1082 target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error)
1085 Stream &output_stream = result.GetOutputStream();
1086 output_stream.Printf("Watchpoint created: ");
1087 wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull);
1088 output_stream.EOL();
1089 result.SetStatus(eReturnStatusSuccessFinishResult);
1091 result.AppendErrorWithFormat("Watchpoint creation failed (addr=0x%" PRIx64
1092 ", size=%" PRIu64 ").\n",
1093 addr, (uint64_t)size);
1094 if (error.AsCString(nullptr))
1095 result.AppendError(error.AsCString());
1096 result.SetStatus(eReturnStatusFailed);
1099 return result.Succeeded();
1103 OptionGroupOptions m_option_group;
1104 OptionGroupWatchpoint m_option_watchpoint;
1107 // CommandObjectWatchpointSet
1110 class CommandObjectWatchpointSet : public CommandObjectMultiword {
1112 CommandObjectWatchpointSet(CommandInterpreter &interpreter)
1113 : CommandObjectMultiword(
1114 interpreter, "watchpoint set", "Commands for setting a watchpoint.",
1115 "watchpoint set <subcommand> [<subcommand-options>]") {
1119 CommandObjectSP(new CommandObjectWatchpointSetVariable(interpreter)));
1122 CommandObjectSP(new CommandObjectWatchpointSetExpression(interpreter)));
1125 ~CommandObjectWatchpointSet() override = default;
1128 // CommandObjectMultiwordWatchpoint
1129 #pragma mark MultiwordWatchpoint
1131 CommandObjectMultiwordWatchpoint::CommandObjectMultiwordWatchpoint(
1132 CommandInterpreter &interpreter)
1133 : CommandObjectMultiword(interpreter, "watchpoint",
1134 "Commands for operating on watchpoints.",
1135 "watchpoint <subcommand> [<command-options>]") {
1136 CommandObjectSP list_command_object(
1137 new CommandObjectWatchpointList(interpreter));
1138 CommandObjectSP enable_command_object(
1139 new CommandObjectWatchpointEnable(interpreter));
1140 CommandObjectSP disable_command_object(
1141 new CommandObjectWatchpointDisable(interpreter));
1142 CommandObjectSP delete_command_object(
1143 new CommandObjectWatchpointDelete(interpreter));
1144 CommandObjectSP ignore_command_object(
1145 new CommandObjectWatchpointIgnore(interpreter));
1146 CommandObjectSP command_command_object(
1147 new CommandObjectWatchpointCommand(interpreter));
1148 CommandObjectSP modify_command_object(
1149 new CommandObjectWatchpointModify(interpreter));
1150 CommandObjectSP set_command_object(
1151 new CommandObjectWatchpointSet(interpreter));
1153 list_command_object->SetCommandName("watchpoint list");
1154 enable_command_object->SetCommandName("watchpoint enable");
1155 disable_command_object->SetCommandName("watchpoint disable");
1156 delete_command_object->SetCommandName("watchpoint delete");
1157 ignore_command_object->SetCommandName("watchpoint ignore");
1158 command_command_object->SetCommandName("watchpoint command");
1159 modify_command_object->SetCommandName("watchpoint modify");
1160 set_command_object->SetCommandName("watchpoint set");
1162 LoadSubCommand("list", list_command_object);
1163 LoadSubCommand("enable", enable_command_object);
1164 LoadSubCommand("disable", disable_command_object);
1165 LoadSubCommand("delete", delete_command_object);
1166 LoadSubCommand("ignore", ignore_command_object);
1167 LoadSubCommand("command", command_command_object);
1168 LoadSubCommand("modify", modify_command_object);
1169 LoadSubCommand("set", set_command_object);
1172 CommandObjectMultiwordWatchpoint::~CommandObjectMultiwordWatchpoint() = default;