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