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