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