[mlir][int-range] Limit xor int range inference to i1 (#116968)
[llvm-project.git] / lldb / source / Commands / CommandObjectBreakpointCommand.cpp
blobac2db5973effa952857cb9895c68de03863d56c2
1 //===-- CommandObjectBreakpointCommand.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 //===----------------------------------------------------------------------===//
9 #include "CommandObjectBreakpointCommand.h"
10 #include "CommandObjectBreakpoint.h"
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Breakpoint/BreakpointIDList.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/IOHandler.h"
15 #include "lldb/Host/OptionParser.h"
16 #include "lldb/Interpreter/CommandInterpreter.h"
17 #include "lldb/Interpreter/CommandOptionArgumentTable.h"
18 #include "lldb/Interpreter/CommandReturnObject.h"
19 #include "lldb/Interpreter/OptionArgParser.h"
20 #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h"
21 #include "lldb/Target/Target.h"
23 using namespace lldb;
24 using namespace lldb_private;
26 #define LLDB_OPTIONS_breakpoint_command_add
27 #include "CommandOptions.inc"
29 class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
30 public IOHandlerDelegateMultiline {
31 public:
32 CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
33 : CommandObjectParsed(interpreter, "add",
34 "Add LLDB commands to a breakpoint, to be executed "
35 "whenever the breakpoint is hit. "
36 "The commands added to the breakpoint replace any "
37 "commands previously added to it."
38 " If no breakpoint is specified, adds the "
39 "commands to the last created breakpoint.",
40 nullptr),
41 IOHandlerDelegateMultiline("DONE",
42 IOHandlerDelegate::Completion::LLDBCommand),
43 m_func_options("breakpoint command", false, 'F') {
44 SetHelpLong(
45 R"(
46 General information about entering breakpoint commands
47 ------------------------------------------------------
50 "This command will prompt for commands to be executed when the specified \
51 breakpoint is hit. Each command is typed on its own line following the '> ' \
52 prompt until 'DONE' is entered."
53 R"(
56 "Syntactic errors may not be detected when initially entered, and many \
57 malformed commands can silently fail when executed. If your breakpoint commands \
58 do not appear to be executing, double-check the command syntax."
59 R"(
62 "Note: You may enter any debugger command exactly as you would at the debugger \
63 prompt. There is no limit to the number of commands supplied, but do NOT enter \
64 more than one command per line."
65 R"(
67 Special information about PYTHON breakpoint commands
68 ----------------------------------------------------
71 "You may enter either one or more lines of Python, including function \
72 definitions or calls to functions that will have been imported by the time \
73 the code executes. Single line breakpoint commands will be interpreted 'as is' \
74 when the breakpoint is hit. Multiple lines of Python will be wrapped in a \
75 generated function, and a call to the function will be attached to the breakpoint."
76 R"(
78 This auto-generated function is passed in three arguments:
80 frame: an lldb.SBFrame object for the frame which hit breakpoint.
82 bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
84 dict: the python session dictionary hit.
87 "When specifying a python function with the --python-function option, you need \
88 to supply the function name prepended by the module name:"
89 R"(
91 --python-function myutils.breakpoint_callback
93 The function itself must have either of the following prototypes:
95 def breakpoint_callback(frame, bp_loc, internal_dict):
96 # Your code goes here
98 or:
100 def breakpoint_callback(frame, bp_loc, extra_args, internal_dict):
101 # Your code goes here
104 "The arguments are the same as the arguments passed to generated functions as \
105 described above. In the second form, any -k and -v pairs provided to the command will \
106 be packaged into a SBDictionary in an SBStructuredData and passed as the extra_args parameter. \
107 \n\n\
108 Note that the global variable 'lldb.frame' will NOT be updated when \
109 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
110 can get you to the thread via frame.GetThread(), the thread can get you to the \
111 process via thread.GetProcess(), and the process can get you back to the target \
112 via process.GetTarget()."
116 "Important Note: As Python code gets collected into functions, access to global \
117 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
118 Python syntax, including indentation, when entering Python breakpoint commands."
121 Example Python one-line breakpoint command:
123 (lldb) breakpoint command add -s python 1
124 Enter your Python command(s). Type 'DONE' to end.
125 def function (frame, bp_loc, internal_dict):
126 """frame: the lldb.SBFrame for the location at which you stopped
127 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
128 internal_dict: an LLDB support object not to be used"""
129 print("Hit this breakpoint!")
130 DONE
132 As a convenience, this also works for a short Python one-liner:
134 (lldb) breakpoint command add -s python 1 -o 'import time; print(time.asctime())'
135 (lldb) run
136 Launching '.../a.out' (x86_64)
137 (lldb) Fri Sep 10 12:17:45 2010
138 Process 21778 Stopped
139 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
141 37 int c(int val)
142 38 {
143 39 -> return val + 3;
144 40 }
146 42 int main (int argc, char const *argv[])
148 Example multiple line Python breakpoint command:
150 (lldb) breakpoint command add -s p 1
151 Enter your Python command(s). Type 'DONE' to end.
152 def function (frame, bp_loc, internal_dict):
153 """frame: the lldb.SBFrame for the location at which you stopped
154 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
155 internal_dict: an LLDB support object not to be used"""
156 global bp_count
157 bp_count = bp_count + 1
158 print("Hit this breakpoint " + repr(bp_count) + " times!")
159 DONE
162 "In this case, since there is a reference to a global variable, \
163 'bp_count', you will also need to make sure 'bp_count' exists and is \
164 initialized:"
167 (lldb) script
168 >>> bp_count = 0
169 >>> quit()
172 "Your Python code, however organized, can optionally return a value. \
173 If the returned value is False, that tells LLDB not to stop at the breakpoint \
174 to which the code is associated. Returning anything other than False, or even \
175 returning None, or even omitting a return statement entirely, will cause \
176 LLDB to stop."
180 "Final Note: A warning that no breakpoint command was generated when there \
181 are no syntax errors may indicate that a function was declared but never called.");
183 m_all_options.Append(&m_options);
184 m_all_options.Append(&m_func_options, LLDB_OPT_SET_2 | LLDB_OPT_SET_3,
185 LLDB_OPT_SET_2);
186 m_all_options.Finalize();
188 AddSimpleArgumentList(eArgTypeBreakpointID, eArgRepeatOptional);
191 ~CommandObjectBreakpointCommandAdd() override = default;
193 Options *GetOptions() override { return &m_all_options; }
195 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
196 StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
197 if (output_sp && interactive) {
198 output_sp->PutCString(g_reader_instructions);
199 output_sp->Flush();
203 void IOHandlerInputComplete(IOHandler &io_handler,
204 std::string &line) override {
205 io_handler.SetIsDone(true);
207 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
208 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
209 io_handler.GetUserData();
210 for (BreakpointOptions &bp_options : *bp_options_vec) {
211 auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
212 cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
213 bp_options.SetCommandDataCallback(cmd_data);
217 void CollectDataForBreakpointCommandCallback(
218 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
219 CommandReturnObject &result) {
220 m_interpreter.GetLLDBCommandsFromIOHandler(
221 "> ", // Prompt
222 *this, // IOHandlerDelegate
223 &bp_options_vec); // Baton for the "io_handler" that will be passed back
224 // into our IOHandlerDelegate functions
227 /// Set a one-liner as the callback for the breakpoint.
228 void SetBreakpointCommandCallback(
229 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
230 const char *oneliner) {
231 for (BreakpointOptions &bp_options : bp_options_vec) {
232 auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
234 cmd_data->user_source.AppendString(oneliner);
235 cmd_data->stop_on_error = m_options.m_stop_on_error;
237 bp_options.SetCommandDataCallback(cmd_data);
241 class CommandOptions : public OptionGroup {
242 public:
243 CommandOptions() = default;
245 ~CommandOptions() override = default;
247 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
248 ExecutionContext *execution_context) override {
249 Status error;
250 const int short_option =
251 g_breakpoint_command_add_options[option_idx].short_option;
253 switch (short_option) {
254 case 'o':
255 m_use_one_liner = true;
256 m_one_liner = std::string(option_arg);
257 break;
259 case 's':
260 m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
261 option_arg,
262 g_breakpoint_command_add_options[option_idx].enum_values,
263 eScriptLanguageNone, error);
264 switch (m_script_language) {
265 case eScriptLanguagePython:
266 case eScriptLanguageLua:
267 m_use_script_language = true;
268 break;
269 case eScriptLanguageNone:
270 case eScriptLanguageUnknown:
271 m_use_script_language = false;
272 break;
274 break;
276 case 'e': {
277 bool success = false;
278 m_stop_on_error =
279 OptionArgParser::ToBoolean(option_arg, false, &success);
280 if (!success)
281 return Status::FromErrorStringWithFormatv(
282 "invalid value for stop-on-error: \"{0}\"", option_arg);
283 } break;
285 case 'D':
286 m_use_dummy = true;
287 break;
289 default:
290 llvm_unreachable("Unimplemented option");
292 return error;
295 void OptionParsingStarting(ExecutionContext *execution_context) override {
296 m_use_commands = true;
297 m_use_script_language = false;
298 m_script_language = eScriptLanguageNone;
300 m_use_one_liner = false;
301 m_stop_on_error = true;
302 m_one_liner.clear();
303 m_use_dummy = false;
306 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
307 return llvm::ArrayRef(g_breakpoint_command_add_options);
310 // Instance variables to hold the values for command options.
312 bool m_use_commands = false;
313 bool m_use_script_language = false;
314 lldb::ScriptLanguage m_script_language = eScriptLanguageNone;
316 // Instance variables to hold the values for one_liner options.
317 bool m_use_one_liner = false;
318 std::string m_one_liner;
319 bool m_stop_on_error;
320 bool m_use_dummy;
323 protected:
324 void DoExecute(Args &command, CommandReturnObject &result) override {
325 Target &target = m_options.m_use_dummy ? GetDummyTarget() : GetTarget();
327 const BreakpointList &breakpoints = target.GetBreakpointList();
328 size_t num_breakpoints = breakpoints.GetSize();
330 if (num_breakpoints == 0) {
331 result.AppendError("No breakpoints exist to have commands added");
332 return;
335 if (!m_func_options.GetName().empty()) {
336 m_options.m_use_one_liner = false;
337 if (!m_options.m_use_script_language) {
338 m_options.m_script_language = GetDebugger().GetScriptLanguage();
339 m_options.m_use_script_language = true;
343 BreakpointIDList valid_bp_ids;
344 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
345 command, target, result, &valid_bp_ids,
346 BreakpointName::Permissions::PermissionKinds::listPerm);
348 m_bp_options_vec.clear();
350 if (result.Succeeded()) {
351 const size_t count = valid_bp_ids.GetSize();
353 for (size_t i = 0; i < count; ++i) {
354 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
355 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
356 Breakpoint *bp =
357 target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
358 if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
359 // This breakpoint does not have an associated location.
360 m_bp_options_vec.push_back(bp->GetOptions());
361 } else {
362 BreakpointLocationSP bp_loc_sp(
363 bp->FindLocationByID(cur_bp_id.GetLocationID()));
364 // This breakpoint does have an associated location. Get its
365 // breakpoint options.
366 if (bp_loc_sp)
367 m_bp_options_vec.push_back(bp_loc_sp->GetLocationOptions());
372 // If we are using script language, get the script interpreter in order
373 // to set or collect command callback. Otherwise, call the methods
374 // associated with this object.
375 if (m_options.m_use_script_language) {
376 Status error;
377 ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(
378 /*can_create=*/true, m_options.m_script_language);
379 // Special handling for one-liner specified inline.
380 if (m_options.m_use_one_liner) {
381 error = script_interp->SetBreakpointCommandCallback(
382 m_bp_options_vec, m_options.m_one_liner.c_str());
383 } else if (!m_func_options.GetName().empty()) {
384 error = script_interp->SetBreakpointCommandCallbackFunction(
385 m_bp_options_vec, m_func_options.GetName().c_str(),
386 m_func_options.GetStructuredData());
387 } else {
388 script_interp->CollectDataForBreakpointCommandCallback(
389 m_bp_options_vec, result);
391 if (!error.Success())
392 result.SetError(std::move(error));
393 } else {
394 // Special handling for one-liner specified inline.
395 if (m_options.m_use_one_liner)
396 SetBreakpointCommandCallback(m_bp_options_vec,
397 m_options.m_one_liner.c_str());
398 else
399 CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
404 private:
405 CommandOptions m_options;
406 OptionGroupPythonClassWithDict m_func_options;
407 OptionGroupOptions m_all_options;
409 std::vector<std::reference_wrapper<BreakpointOptions>>
410 m_bp_options_vec; // This stores the
411 // breakpoint options that
412 // we are currently
413 // collecting commands for. In the CollectData... calls we need to hand this
414 // off to the IOHandler, which may run asynchronously. So we have to have
415 // some way to keep it alive, and not leak it. Making it an ivar of the
416 // command object, which never goes away achieves this. Note that if we were
417 // able to run the same command concurrently in one interpreter we'd have to
418 // make this "per invocation". But there are many more reasons why it is not
419 // in general safe to do that in lldb at present, so it isn't worthwhile to
420 // come up with a more complex mechanism to address this particular weakness
421 // right now.
422 static const char *g_reader_instructions;
425 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
426 "Enter your debugger command(s). Type 'DONE' to end.\n";
428 // CommandObjectBreakpointCommandDelete
430 #define LLDB_OPTIONS_breakpoint_command_delete
431 #include "CommandOptions.inc"
433 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
434 public:
435 CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
436 : CommandObjectParsed(interpreter, "delete",
437 "Delete the set of commands from a breakpoint.",
438 nullptr) {
439 AddSimpleArgumentList(eArgTypeBreakpointID);
442 ~CommandObjectBreakpointCommandDelete() override = default;
444 Options *GetOptions() override { return &m_options; }
446 class CommandOptions : public Options {
447 public:
448 CommandOptions() = default;
450 ~CommandOptions() override = default;
452 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
453 ExecutionContext *execution_context) override {
454 Status error;
455 const int short_option = m_getopt_table[option_idx].val;
457 switch (short_option) {
458 case 'D':
459 m_use_dummy = true;
460 break;
462 default:
463 llvm_unreachable("Unimplemented option");
466 return error;
469 void OptionParsingStarting(ExecutionContext *execution_context) override {
470 m_use_dummy = false;
473 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
474 return llvm::ArrayRef(g_breakpoint_command_delete_options);
477 // Instance variables to hold the values for command options.
478 bool m_use_dummy = false;
481 protected:
482 void DoExecute(Args &command, CommandReturnObject &result) override {
483 Target &target = m_options.m_use_dummy ? GetDummyTarget() : GetTarget();
485 const BreakpointList &breakpoints = target.GetBreakpointList();
486 size_t num_breakpoints = breakpoints.GetSize();
488 if (num_breakpoints == 0) {
489 result.AppendError("No breakpoints exist to have commands deleted");
490 return;
493 if (command.empty()) {
494 result.AppendError(
495 "No breakpoint specified from which to delete the commands");
496 return;
499 BreakpointIDList valid_bp_ids;
500 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
501 command, target, result, &valid_bp_ids,
502 BreakpointName::Permissions::PermissionKinds::listPerm);
504 if (result.Succeeded()) {
505 const size_t count = valid_bp_ids.GetSize();
506 for (size_t i = 0; i < count; ++i) {
507 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
508 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
509 Breakpoint *bp =
510 target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
511 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
512 BreakpointLocationSP bp_loc_sp(
513 bp->FindLocationByID(cur_bp_id.GetLocationID()));
514 if (bp_loc_sp)
515 bp_loc_sp->ClearCallback();
516 else {
517 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
518 cur_bp_id.GetBreakpointID(),
519 cur_bp_id.GetLocationID());
520 return;
522 } else {
523 bp->ClearCallback();
530 private:
531 CommandOptions m_options;
534 // CommandObjectBreakpointCommandList
536 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
537 public:
538 CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
539 : CommandObjectParsed(interpreter, "list",
540 "List the script or set of commands to be "
541 "executed when the breakpoint is hit.",
542 nullptr, eCommandRequiresTarget) {
543 AddSimpleArgumentList(eArgTypeBreakpointID);
546 ~CommandObjectBreakpointCommandList() override = default;
548 protected:
549 void DoExecute(Args &command, CommandReturnObject &result) override {
550 Target &target = GetTarget();
552 const BreakpointList &breakpoints = target.GetBreakpointList();
553 size_t num_breakpoints = breakpoints.GetSize();
555 if (num_breakpoints == 0) {
556 result.AppendError("No breakpoints exist for which to list commands");
557 return;
560 if (command.empty()) {
561 result.AppendError(
562 "No breakpoint specified for which to list the commands");
563 return;
566 BreakpointIDList valid_bp_ids;
567 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
568 command, target, result, &valid_bp_ids,
569 BreakpointName::Permissions::PermissionKinds::listPerm);
571 if (result.Succeeded()) {
572 const size_t count = valid_bp_ids.GetSize();
573 for (size_t i = 0; i < count; ++i) {
574 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
575 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
576 Breakpoint *bp =
577 target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
579 if (bp) {
580 BreakpointLocationSP bp_loc_sp;
581 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
582 bp_loc_sp = bp->FindLocationByID(cur_bp_id.GetLocationID());
583 if (!bp_loc_sp) {
584 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
585 cur_bp_id.GetBreakpointID(),
586 cur_bp_id.GetLocationID());
587 return;
591 StreamString id_str;
592 BreakpointID::GetCanonicalReference(&id_str,
593 cur_bp_id.GetBreakpointID(),
594 cur_bp_id.GetLocationID());
595 const Baton *baton = nullptr;
596 if (bp_loc_sp)
597 baton =
598 bp_loc_sp
599 ->GetOptionsSpecifyingKind(BreakpointOptions::eCallback)
600 .GetBaton();
601 else
602 baton = bp->GetOptions().GetBaton();
604 if (baton) {
605 result.GetOutputStream().Printf("Breakpoint %s:\n",
606 id_str.GetData());
607 baton->GetDescription(result.GetOutputStream().AsRawOstream(),
608 eDescriptionLevelFull,
609 result.GetOutputStream().GetIndentLevel() +
611 } else {
612 result.AppendMessageWithFormat(
613 "Breakpoint %s does not have an associated command.\n",
614 id_str.GetData());
617 result.SetStatus(eReturnStatusSuccessFinishResult);
618 } else {
619 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
620 cur_bp_id.GetBreakpointID());
627 // CommandObjectBreakpointCommand
629 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
630 CommandInterpreter &interpreter)
631 : CommandObjectMultiword(
632 interpreter, "command",
633 "Commands for adding, removing and listing "
634 "LLDB commands executed when a breakpoint is "
635 "hit.",
636 "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
637 CommandObjectSP add_command_object(
638 new CommandObjectBreakpointCommandAdd(interpreter));
639 CommandObjectSP delete_command_object(
640 new CommandObjectBreakpointCommandDelete(interpreter));
641 CommandObjectSP list_command_object(
642 new CommandObjectBreakpointCommandList(interpreter));
644 add_command_object->SetCommandName("breakpoint command add");
645 delete_command_object->SetCommandName("breakpoint command delete");
646 list_command_object->SetCommandName("breakpoint command list");
648 LoadSubCommand("add", add_command_object);
649 LoadSubCommand("delete", delete_command_object);
650 LoadSubCommand("list", list_command_object);
653 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;