1 //===-- CommandObjectBreakpointCommand.cpp ----------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "CommandObjectBreakpointCommand.h"
11 #include "CommandObjectBreakpoint.h"
12 #include "lldb/Breakpoint/Breakpoint.h"
13 #include "lldb/Breakpoint/BreakpointIDList.h"
14 #include "lldb/Breakpoint/BreakpointLocation.h"
15 #include "lldb/Breakpoint/StoppointCallbackContext.h"
16 #include "lldb/Core/IOHandler.h"
17 #include "lldb/Host/OptionParser.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandReturnObject.h"
20 #include "lldb/Interpreter/OptionArgParser.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Utility/State.h"
24
25 #include "llvm/ADT/STLExtras.h"
26
27 using namespace lldb;
28 using namespace lldb_private;
29
30 //-------------------------------------------------------------------------
31 // CommandObjectBreakpointCommandAdd
32 //-------------------------------------------------------------------------
33
34 // FIXME: "script-type" needs to have its contents determined dynamically, so
35 // somebody can add a new scripting
36 // language to lldb and have it pickable here without having to change this
37 // enumeration by hand and rebuild lldb proper.
38
39 static constexpr OptionEnumValueElement g_script_option_enumeration[] = {
40 {eScriptLanguageNone, "command",
41 "Commands are in the lldb command interpreter language"},
42 {eScriptLanguagePython, "python", "Commands are in the Python language."},
43 {eSortOrderByName, "default-script",
44 "Commands are in the default scripting language."} };
45
ScriptOptionEnum()46 static constexpr OptionEnumValues ScriptOptionEnum() {
47 return OptionEnumValues(g_script_option_enumeration);
48 }
49
50 static constexpr OptionDefinition g_breakpoint_add_options[] = {
51 // clang-format off
52 { LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
53 { LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Specify whether breakpoint command execution should terminate on error." },
54 { LLDB_OPT_SET_ALL, false, "script-type", 's', OptionParser::eRequiredArgument, nullptr, ScriptOptionEnum(), 0, eArgTypeNone, "Specify the language for the commands - if none is specified, the lldb command interpreter will be used." },
55 { LLDB_OPT_SET_2, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePythonFunction, "Give the name of a Python function to run as command for this breakpoint. Be sure to give a module name if appropriate." },
56 { LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Sets Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets." },
57 // clang-format on
58 };
59
60 class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
61 public IOHandlerDelegateMultiline {
62 public:
CommandObjectBreakpointCommandAdd(CommandInterpreter & interpreter)63 CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
64 : CommandObjectParsed(interpreter, "add",
65 "Add LLDB commands to a breakpoint, to be executed "
66 "whenever the breakpoint is hit."
67 " If no breakpoint is specified, adds the "
68 "commands to the last created breakpoint.",
69 nullptr),
70 IOHandlerDelegateMultiline("DONE",
71 IOHandlerDelegate::Completion::LLDBCommand),
72 m_options() {
73 SetHelpLong(
74 R"(
75 General information about entering breakpoint commands
76 ------------------------------------------------------
77
78 )"
79 "This command will prompt for commands to be executed when the specified \
80 breakpoint is hit. Each command is typed on its own line following the '> ' \
81 prompt until 'DONE' is entered."
82 R"(
83
84 )"
85 "Syntactic errors may not be detected when initially entered, and many \
86 malformed commands can silently fail when executed. If your breakpoint commands \
87 do not appear to be executing, double-check the command syntax."
88 R"(
89
90 )"
91 "Note: You may enter any debugger command exactly as you would at the debugger \
92 prompt. There is no limit to the number of commands supplied, but do NOT enter \
93 more than one command per line."
94 R"(
95
96 Special information about PYTHON breakpoint commands
97 ----------------------------------------------------
98
99 )"
100 "You may enter either one or more lines of Python, including function \
101 definitions or calls to functions that will have been imported by the time \
102 the code executes. Single line breakpoint commands will be interpreted 'as is' \
103 when the breakpoint is hit. Multiple lines of Python will be wrapped in a \
104 generated function, and a call to the function will be attached to the breakpoint."
105 R"(
106
107 This auto-generated function is passed in three arguments:
108
109 frame: an lldb.SBFrame object for the frame which hit breakpoint.
110
111 bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
112
113 dict: the python session dictionary hit.
114
115 )"
116 "When specifying a python function with the --python-function option, you need \
117 to supply the function name prepended by the module name:"
118 R"(
119
120 --python-function myutils.breakpoint_callback
121
122 The function itself must have the following prototype:
123
124 def breakpoint_callback(frame, bp_loc, dict):
125 # Your code goes here
126
127 )"
128 "The arguments are the same as the arguments passed to generated functions as \
129 described above. Note that the global variable 'lldb.frame' will NOT be updated when \
130 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
131 can get you to the thread via frame.GetThread(), the thread can get you to the \
132 process via thread.GetProcess(), and the process can get you back to the target \
133 via process.GetTarget()."
134 R"(
135
136 )"
137 "Important Note: As Python code gets collected into functions, access to global \
138 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \
139 Python syntax, including indentation, when entering Python breakpoint commands."
140 R"(
141
142 Example Python one-line breakpoint command:
143
144 (lldb) breakpoint command add -s python 1
145 Enter your Python command(s). Type 'DONE' to end.
146 > print "Hit this breakpoint!"
147 > DONE
148
149 As a convenience, this also works for a short Python one-liner:
150
151 (lldb) breakpoint command add -s python 1 -o 'import time; print time.asctime()'
152 (lldb) run
153 Launching '.../a.out' (x86_64)
154 (lldb) Fri Sep 10 12:17:45 2010
155 Process 21778 Stopped
156 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
157 36
158 37 int c(int val)
159 38 {
160 39 -> return val + 3;
161 40 }
162 41
163 42 int main (int argc, char const *argv[])
164
165 Example multiple line Python breakpoint command:
166
167 (lldb) breakpoint command add -s p 1
168 Enter your Python command(s). Type 'DONE' to end.
169 > global bp_count
170 > bp_count = bp_count + 1
171 > print "Hit this breakpoint " + repr(bp_count) + " times!"
172 > DONE
173
174 Example multiple line Python breakpoint command, using function definition:
175
176 (lldb) breakpoint command add -s python 1
177 Enter your Python command(s). Type 'DONE' to end.
178 > def breakpoint_output (bp_no):
179 > out_string = "Hit breakpoint number " + repr (bp_no)
180 > print out_string
181 > return True
182 > breakpoint_output (1)
183 > DONE
184
185 )"
186 "In this case, since there is a reference to a global variable, \
187 'bp_count', you will also need to make sure 'bp_count' exists and is \
188 initialized:"
189 R"(
190
191 (lldb) script
192 >>> bp_count = 0
193 >>> quit()
194
195 )"
196 "Your Python code, however organized, can optionally return a value. \
197 If the returned value is False, that tells LLDB not to stop at the breakpoint \
198 to which the code is associated. Returning anything other than False, or even \
199 returning None, or even omitting a return statement entirely, will cause \
200 LLDB to stop."
201 R"(
202
203 )"
204 "Final Note: A warning that no breakpoint command was generated when there \
205 are no syntax errors may indicate that a function was declared but never called.");
206
207 CommandArgumentEntry arg;
208 CommandArgumentData bp_id_arg;
209
210 // Define the first (and only) variant of this arg.
211 bp_id_arg.arg_type = eArgTypeBreakpointID;
212 bp_id_arg.arg_repetition = eArgRepeatOptional;
213
214 // There is only one variant this argument could be; put it into the
215 // argument entry.
216 arg.push_back(bp_id_arg);
217
218 // Push the data for the first argument into the m_arguments vector.
219 m_arguments.push_back(arg);
220 }
221
222 ~CommandObjectBreakpointCommandAdd() override = default;
223
GetOptions()224 Options *GetOptions() override { return &m_options; }
225
IOHandlerActivated(IOHandler & io_handler)226 void IOHandlerActivated(IOHandler &io_handler) override {
227 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
228 if (output_sp) {
229 output_sp->PutCString(g_reader_instructions);
230 output_sp->Flush();
231 }
232 }
233
IOHandlerInputComplete(IOHandler & io_handler,std::string & line)234 void IOHandlerInputComplete(IOHandler &io_handler,
235 std::string &line) override {
236 io_handler.SetIsDone(true);
237
238 std::vector<BreakpointOptions *> *bp_options_vec =
239 (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
240 for (BreakpointOptions *bp_options : *bp_options_vec) {
241 if (!bp_options)
242 continue;
243
244 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
245 cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
246 bp_options->SetCommandDataCallback(cmd_data);
247 }
248 }
249
CollectDataForBreakpointCommandCallback(std::vector<BreakpointOptions * > & bp_options_vec,CommandReturnObject & result)250 void CollectDataForBreakpointCommandCallback(
251 std::vector<BreakpointOptions *> &bp_options_vec,
252 CommandReturnObject &result) {
253 m_interpreter.GetLLDBCommandsFromIOHandler(
254 "> ", // Prompt
255 *this, // IOHandlerDelegate
256 true, // Run IOHandler in async mode
257 &bp_options_vec); // Baton for the "io_handler" that will be passed back
258 // into our IOHandlerDelegate functions
259 }
260
261 /// Set a one-liner as the callback for the breakpoint.
262 void
SetBreakpointCommandCallback(std::vector<BreakpointOptions * > & bp_options_vec,const char * oneliner)263 SetBreakpointCommandCallback(std::vector<BreakpointOptions *> &bp_options_vec,
264 const char *oneliner) {
265 for (auto bp_options : bp_options_vec) {
266 auto cmd_data = llvm::make_unique<BreakpointOptions::CommandData>();
267
268 cmd_data->user_source.AppendString(oneliner);
269 cmd_data->stop_on_error = m_options.m_stop_on_error;
270
271 bp_options->SetCommandDataCallback(cmd_data);
272 }
273 }
274
275 class CommandOptions : public Options {
276 public:
CommandOptions()277 CommandOptions()
278 : Options(), m_use_commands(false), m_use_script_language(false),
279 m_script_language(eScriptLanguageNone), m_use_one_liner(false),
280 m_one_liner(), m_function_name() {}
281
282 ~CommandOptions() override = default;
283
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)284 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
285 ExecutionContext *execution_context) override {
286 Status error;
287 const int short_option = m_getopt_table[option_idx].val;
288
289 switch (short_option) {
290 case 'o':
291 m_use_one_liner = true;
292 m_one_liner = option_arg;
293 break;
294
295 case 's':
296 m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
297 option_arg, g_breakpoint_add_options[option_idx].enum_values,
298 eScriptLanguageNone, error);
299
300 if (m_script_language == eScriptLanguagePython ||
301 m_script_language == eScriptLanguageDefault) {
302 m_use_script_language = true;
303 } else {
304 m_use_script_language = false;
305 }
306 break;
307
308 case 'e': {
309 bool success = false;
310 m_stop_on_error =
311 OptionArgParser::ToBoolean(option_arg, false, &success);
312 if (!success)
313 error.SetErrorStringWithFormat(
314 "invalid value for stop-on-error: \"%s\"",
315 option_arg.str().c_str());
316 } break;
317
318 case 'F':
319 m_use_one_liner = false;
320 m_use_script_language = true;
321 m_function_name.assign(option_arg);
322 break;
323
324 case 'D':
325 m_use_dummy = true;
326 break;
327
328 default:
329 break;
330 }
331 return error;
332 }
333
OptionParsingStarting(ExecutionContext * execution_context)334 void OptionParsingStarting(ExecutionContext *execution_context) override {
335 m_use_commands = true;
336 m_use_script_language = false;
337 m_script_language = eScriptLanguageNone;
338
339 m_use_one_liner = false;
340 m_stop_on_error = true;
341 m_one_liner.clear();
342 m_function_name.clear();
343 m_use_dummy = false;
344 }
345
GetDefinitions()346 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
347 return llvm::makeArrayRef(g_breakpoint_add_options);
348 }
349
350 // Instance variables to hold the values for command options.
351
352 bool m_use_commands;
353 bool m_use_script_language;
354 lldb::ScriptLanguage m_script_language;
355
356 // Instance variables to hold the values for one_liner options.
357 bool m_use_one_liner;
358 std::string m_one_liner;
359 bool m_stop_on_error;
360 std::string m_function_name;
361 bool m_use_dummy;
362 };
363
364 protected:
DoExecute(Args & command,CommandReturnObject & result)365 bool DoExecute(Args &command, CommandReturnObject &result) override {
366 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
367
368 if (target == nullptr) {
369 result.AppendError("There is not a current executable; there are no "
370 "breakpoints to which to add commands");
371 result.SetStatus(eReturnStatusFailed);
372 return false;
373 }
374
375 const BreakpointList &breakpoints = target->GetBreakpointList();
376 size_t num_breakpoints = breakpoints.GetSize();
377
378 if (num_breakpoints == 0) {
379 result.AppendError("No breakpoints exist to have commands added");
380 result.SetStatus(eReturnStatusFailed);
381 return false;
382 }
383
384 if (!m_options.m_use_script_language &&
385 !m_options.m_function_name.empty()) {
386 result.AppendError("need to enable scripting to have a function run as a "
387 "breakpoint command");
388 result.SetStatus(eReturnStatusFailed);
389 return false;
390 }
391
392 BreakpointIDList valid_bp_ids;
393 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
394 command, target, result, &valid_bp_ids,
395 BreakpointName::Permissions::PermissionKinds::listPerm);
396
397 m_bp_options_vec.clear();
398
399 if (result.Succeeded()) {
400 const size_t count = valid_bp_ids.GetSize();
401
402 for (size_t i = 0; i < count; ++i) {
403 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
404 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
405 Breakpoint *bp =
406 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
407 BreakpointOptions *bp_options = nullptr;
408 if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
409 // This breakpoint does not have an associated location.
410 bp_options = bp->GetOptions();
411 } else {
412 BreakpointLocationSP bp_loc_sp(
413 bp->FindLocationByID(cur_bp_id.GetLocationID()));
414 // This breakpoint does have an associated location. Get its
415 // breakpoint options.
416 if (bp_loc_sp)
417 bp_options = bp_loc_sp->GetLocationOptions();
418 }
419 if (bp_options)
420 m_bp_options_vec.push_back(bp_options);
421 }
422 }
423
424 // If we are using script language, get the script interpreter in order
425 // to set or collect command callback. Otherwise, call the methods
426 // associated with this object.
427 if (m_options.m_use_script_language) {
428 ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter();
429 // Special handling for one-liner specified inline.
430 if (m_options.m_use_one_liner) {
431 script_interp->SetBreakpointCommandCallback(
432 m_bp_options_vec, m_options.m_one_liner.c_str());
433 } else if (!m_options.m_function_name.empty()) {
434 script_interp->SetBreakpointCommandCallbackFunction(
435 m_bp_options_vec, m_options.m_function_name.c_str());
436 } else {
437 script_interp->CollectDataForBreakpointCommandCallback(
438 m_bp_options_vec, result);
439 }
440 } else {
441 // Special handling for one-liner specified inline.
442 if (m_options.m_use_one_liner)
443 SetBreakpointCommandCallback(m_bp_options_vec,
444 m_options.m_one_liner.c_str());
445 else
446 CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
447 }
448 }
449
450 return result.Succeeded();
451 }
452
453 private:
454 CommandOptions m_options;
455 std::vector<BreakpointOptions *> m_bp_options_vec; // This stores the
456 // breakpoint options that
457 // we are currently
458 // collecting commands for. In the CollectData... calls we need to hand this
459 // off to the IOHandler, which may run asynchronously. So we have to have
460 // some way to keep it alive, and not leak it. Making it an ivar of the
461 // command object, which never goes away achieves this. Note that if we were
462 // able to run the same command concurrently in one interpreter we'd have to
463 // make this "per invocation". But there are many more reasons why it is not
464 // in general safe to do that in lldb at present, so it isn't worthwhile to
465 // come up with a more complex mechanism to address this particular weakness
466 // right now.
467 static const char *g_reader_instructions;
468 };
469
470 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
471 "Enter your debugger command(s). Type 'DONE' to end.\n";
472
473 //-------------------------------------------------------------------------
474 // CommandObjectBreakpointCommandDelete
475 //-------------------------------------------------------------------------
476
477 static constexpr OptionDefinition g_breakpoint_delete_options[] = {
478 // clang-format off
479 { LLDB_OPT_SET_1, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Delete commands from Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets." },
480 // clang-format on
481 };
482
483 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
484 public:
CommandObjectBreakpointCommandDelete(CommandInterpreter & interpreter)485 CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
486 : CommandObjectParsed(interpreter, "delete",
487 "Delete the set of commands from a breakpoint.",
488 nullptr),
489 m_options() {
490 CommandArgumentEntry arg;
491 CommandArgumentData bp_id_arg;
492
493 // Define the first (and only) variant of this arg.
494 bp_id_arg.arg_type = eArgTypeBreakpointID;
495 bp_id_arg.arg_repetition = eArgRepeatPlain;
496
497 // There is only one variant this argument could be; put it into the
498 // argument entry.
499 arg.push_back(bp_id_arg);
500
501 // Push the data for the first argument into the m_arguments vector.
502 m_arguments.push_back(arg);
503 }
504
505 ~CommandObjectBreakpointCommandDelete() override = default;
506
GetOptions()507 Options *GetOptions() override { return &m_options; }
508
509 class CommandOptions : public Options {
510 public:
CommandOptions()511 CommandOptions() : Options(), m_use_dummy(false) {}
512
513 ~CommandOptions() override = default;
514
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)515 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
516 ExecutionContext *execution_context) override {
517 Status error;
518 const int short_option = m_getopt_table[option_idx].val;
519
520 switch (short_option) {
521 case 'D':
522 m_use_dummy = true;
523 break;
524
525 default:
526 error.SetErrorStringWithFormat("unrecognized option '%c'",
527 short_option);
528 break;
529 }
530
531 return error;
532 }
533
OptionParsingStarting(ExecutionContext * execution_context)534 void OptionParsingStarting(ExecutionContext *execution_context) override {
535 m_use_dummy = false;
536 }
537
GetDefinitions()538 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
539 return llvm::makeArrayRef(g_breakpoint_delete_options);
540 }
541
542 // Instance variables to hold the values for command options.
543 bool m_use_dummy;
544 };
545
546 protected:
DoExecute(Args & command,CommandReturnObject & result)547 bool DoExecute(Args &command, CommandReturnObject &result) override {
548 Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
549
550 if (target == nullptr) {
551 result.AppendError("There is not a current executable; there are no "
552 "breakpoints from which to delete commands");
553 result.SetStatus(eReturnStatusFailed);
554 return false;
555 }
556
557 const BreakpointList &breakpoints = target->GetBreakpointList();
558 size_t num_breakpoints = breakpoints.GetSize();
559
560 if (num_breakpoints == 0) {
561 result.AppendError("No breakpoints exist to have commands deleted");
562 result.SetStatus(eReturnStatusFailed);
563 return false;
564 }
565
566 if (command.empty()) {
567 result.AppendError(
568 "No breakpoint specified from which to delete the commands");
569 result.SetStatus(eReturnStatusFailed);
570 return false;
571 }
572
573 BreakpointIDList valid_bp_ids;
574 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
575 command, target, result, &valid_bp_ids,
576 BreakpointName::Permissions::PermissionKinds::listPerm);
577
578 if (result.Succeeded()) {
579 const size_t count = valid_bp_ids.GetSize();
580 for (size_t i = 0; i < count; ++i) {
581 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
582 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
583 Breakpoint *bp =
584 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
585 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
586 BreakpointLocationSP bp_loc_sp(
587 bp->FindLocationByID(cur_bp_id.GetLocationID()));
588 if (bp_loc_sp)
589 bp_loc_sp->ClearCallback();
590 else {
591 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
592 cur_bp_id.GetBreakpointID(),
593 cur_bp_id.GetLocationID());
594 result.SetStatus(eReturnStatusFailed);
595 return false;
596 }
597 } else {
598 bp->ClearCallback();
599 }
600 }
601 }
602 }
603 return result.Succeeded();
604 }
605
606 private:
607 CommandOptions m_options;
608 };
609
610 //-------------------------------------------------------------------------
611 // CommandObjectBreakpointCommandList
612 //-------------------------------------------------------------------------
613
614 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
615 public:
CommandObjectBreakpointCommandList(CommandInterpreter & interpreter)616 CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
617 : CommandObjectParsed(interpreter, "list", "List the script or set of "
618 "commands to be executed when "
619 "the breakpoint is hit.",
620 nullptr) {
621 CommandArgumentEntry arg;
622 CommandArgumentData bp_id_arg;
623
624 // Define the first (and only) variant of this arg.
625 bp_id_arg.arg_type = eArgTypeBreakpointID;
626 bp_id_arg.arg_repetition = eArgRepeatPlain;
627
628 // There is only one variant this argument could be; put it into the
629 // argument entry.
630 arg.push_back(bp_id_arg);
631
632 // Push the data for the first argument into the m_arguments vector.
633 m_arguments.push_back(arg);
634 }
635
636 ~CommandObjectBreakpointCommandList() override = default;
637
638 protected:
DoExecute(Args & command,CommandReturnObject & result)639 bool DoExecute(Args &command, CommandReturnObject &result) override {
640 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
641
642 if (target == nullptr) {
643 result.AppendError("There is not a current executable; there are no "
644 "breakpoints for which to list commands");
645 result.SetStatus(eReturnStatusFailed);
646 return false;
647 }
648
649 const BreakpointList &breakpoints = target->GetBreakpointList();
650 size_t num_breakpoints = breakpoints.GetSize();
651
652 if (num_breakpoints == 0) {
653 result.AppendError("No breakpoints exist for which to list commands");
654 result.SetStatus(eReturnStatusFailed);
655 return false;
656 }
657
658 if (command.empty()) {
659 result.AppendError(
660 "No breakpoint specified for which to list the commands");
661 result.SetStatus(eReturnStatusFailed);
662 return false;
663 }
664
665 BreakpointIDList valid_bp_ids;
666 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
667 command, target, result, &valid_bp_ids,
668 BreakpointName::Permissions::PermissionKinds::listPerm);
669
670 if (result.Succeeded()) {
671 const size_t count = valid_bp_ids.GetSize();
672 for (size_t i = 0; i < count; ++i) {
673 BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
674 if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
675 Breakpoint *bp =
676 target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
677
678 if (bp) {
679 BreakpointLocationSP bp_loc_sp;
680 if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
681 bp_loc_sp = bp->FindLocationByID(cur_bp_id.GetLocationID());
682 if (!bp_loc_sp)
683 {
684 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
685 cur_bp_id.GetBreakpointID(),
686 cur_bp_id.GetLocationID());
687 result.SetStatus(eReturnStatusFailed);
688 return false;
689 }
690 }
691
692 StreamString id_str;
693 BreakpointID::GetCanonicalReference(&id_str,
694 cur_bp_id.GetBreakpointID(),
695 cur_bp_id.GetLocationID());
696 const Baton *baton = nullptr;
697 if (bp_loc_sp)
698 baton = bp_loc_sp
699 ->GetOptionsSpecifyingKind(BreakpointOptions::eCallback)
700 ->GetBaton();
701 else
702 baton = bp->GetOptions()->GetBaton();
703
704 if (baton) {
705 result.GetOutputStream().Printf("Breakpoint %s:\n",
706 id_str.GetData());
707 result.GetOutputStream().IndentMore();
708 baton->GetDescription(&result.GetOutputStream(),
709 eDescriptionLevelFull);
710 result.GetOutputStream().IndentLess();
711 } else {
712 result.AppendMessageWithFormat(
713 "Breakpoint %s does not have an associated command.\n",
714 id_str.GetData());
715 }
716 }
717 result.SetStatus(eReturnStatusSuccessFinishResult);
718 } else {
719 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
720 cur_bp_id.GetBreakpointID());
721 result.SetStatus(eReturnStatusFailed);
722 }
723 }
724 }
725
726 return result.Succeeded();
727 }
728 };
729
730 //-------------------------------------------------------------------------
731 // CommandObjectBreakpointCommand
732 //-------------------------------------------------------------------------
733
CommandObjectBreakpointCommand(CommandInterpreter & interpreter)734 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
735 CommandInterpreter &interpreter)
736 : CommandObjectMultiword(
737 interpreter, "command", "Commands for adding, removing and listing "
738 "LLDB commands executed when a breakpoint is "
739 "hit.",
740 "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
741 CommandObjectSP add_command_object(
742 new CommandObjectBreakpointCommandAdd(interpreter));
743 CommandObjectSP delete_command_object(
744 new CommandObjectBreakpointCommandDelete(interpreter));
745 CommandObjectSP list_command_object(
746 new CommandObjectBreakpointCommandList(interpreter));
747
748 add_command_object->SetCommandName("breakpoint command add");
749 delete_command_object->SetCommandName("breakpoint command delete");
750 list_command_object->SetCommandName("breakpoint command list");
751
752 LoadSubCommand("add", add_command_object);
753 LoadSubCommand("delete", delete_command_object);
754 LoadSubCommand("list", list_command_object);
755 }
756
757 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;
758