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