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             llvm::StringRef::withNullAsEmpty(option_arg),
305             g_breakpoint_add_options[option_idx].enum_values,
306             eScriptLanguageNone, error);
307 
308         if (m_script_language == eScriptLanguagePython ||
309             m_script_language == eScriptLanguageDefault) {
310           m_use_script_language = true;
311         } else {
312           m_use_script_language = false;
313         }
314         break;
315 
316       case 'e': {
317         bool success = false;
318         m_stop_on_error = Args::StringToBoolean(option_strref, false, &success);
319         if (!success)
320           error.SetErrorStringWithFormat(
321               "invalid value for stop-on-error: \"%s\"", option_arg);
322       } break;
323 
324       case 'F':
325         m_use_one_liner = false;
326         m_use_script_language = true;
327         m_function_name.assign(option_arg);
328         break;
329 
330       case 'D':
331         m_use_dummy = true;
332         break;
333 
334       default:
335         break;
336       }
337       return error;
338     }
339 
340     void OptionParsingStarting(ExecutionContext *execution_context) override {
341       m_use_commands = true;
342       m_use_script_language = false;
343       m_script_language = eScriptLanguageNone;
344 
345       m_use_one_liner = false;
346       m_stop_on_error = true;
347       m_one_liner.clear();
348       m_function_name.clear();
349       m_use_dummy = false;
350     }
351 
352     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
353       return llvm::makeArrayRef(g_breakpoint_add_options);
354     }
355 
356     // Instance variables to hold the values for command options.
357 
358     bool m_use_commands;
359     bool m_use_script_language;
360     lldb::ScriptLanguage m_script_language;
361 
362     // Instance variables to hold the values for one_liner options.
363     bool m_use_one_liner;
364     std::string m_one_liner;
365     bool m_stop_on_error;
366     std::string m_function_name;
367     bool m_use_dummy;
368   };
369 
370 protected:
371   bool DoExecute(Args &command, CommandReturnObject &result) override {
372     Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
373 
374     if (target == nullptr) {
375       result.AppendError("There is not a current executable; there are no "
376                          "breakpoints to which to add commands");
377       result.SetStatus(eReturnStatusFailed);
378       return false;
379     }
380 
381     const BreakpointList &breakpoints = target->GetBreakpointList();
382     size_t num_breakpoints = breakpoints.GetSize();
383 
384     if (num_breakpoints == 0) {
385       result.AppendError("No breakpoints exist to have commands added");
386       result.SetStatus(eReturnStatusFailed);
387       return false;
388     }
389 
390     if (!m_options.m_use_script_language &&
391         !m_options.m_function_name.empty()) {
392       result.AppendError("need to enable scripting to have a function run as a "
393                          "breakpoint command");
394       result.SetStatus(eReturnStatusFailed);
395       return false;
396     }
397 
398     BreakpointIDList valid_bp_ids;
399     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
400         command, target, result, &valid_bp_ids);
401 
402     m_bp_options_vec.clear();
403 
404     if (result.Succeeded()) {
405       const size_t count = valid_bp_ids.GetSize();
406 
407       for (size_t i = 0; i < count; ++i) {
408         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
409         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
410           Breakpoint *bp =
411               target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
412           BreakpointOptions *bp_options = nullptr;
413           if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
414             // This breakpoint does not have an associated location.
415             bp_options = bp->GetOptions();
416           } else {
417             BreakpointLocationSP bp_loc_sp(
418                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
419             // This breakpoint does have an associated location.
420             // Get its breakpoint options.
421             if (bp_loc_sp)
422               bp_options = bp_loc_sp->GetLocationOptions();
423           }
424           if (bp_options)
425             m_bp_options_vec.push_back(bp_options);
426         }
427       }
428 
429       // If we are using script language, get the script interpreter
430       // in order to set or collect command callback.  Otherwise, call
431       // the methods associated with this object.
432       if (m_options.m_use_script_language) {
433         ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter();
434         // Special handling for one-liner specified inline.
435         if (m_options.m_use_one_liner) {
436           script_interp->SetBreakpointCommandCallback(
437               m_bp_options_vec, m_options.m_one_liner.c_str());
438         } else if (!m_options.m_function_name.empty()) {
439           script_interp->SetBreakpointCommandCallbackFunction(
440               m_bp_options_vec, m_options.m_function_name.c_str());
441         } else {
442           script_interp->CollectDataForBreakpointCommandCallback(
443               m_bp_options_vec, result);
444         }
445       } else {
446         // Special handling for one-liner specified inline.
447         if (m_options.m_use_one_liner)
448           SetBreakpointCommandCallback(m_bp_options_vec,
449                                        m_options.m_one_liner.c_str());
450         else
451           CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
452       }
453     }
454 
455     return result.Succeeded();
456   }
457 
458 private:
459   CommandOptions m_options;
460   std::vector<BreakpointOptions *> m_bp_options_vec; // This stores the
461                                                      // breakpoint options that
462                                                      // we are currently
463   // collecting commands for.  In the CollectData... calls we need
464   // to hand this off to the IOHandler, which may run asynchronously.
465   // So we have to have some way to keep it alive, and not leak it.
466   // Making it an ivar of the command object, which never goes away
467   // achieves this.  Note that if we were able to run
468   // the same command concurrently in one interpreter we'd have to
469   // make this "per invocation".  But there are many more reasons
470   // why it is not in general safe to do that in lldb at present,
471   // so it isn't worthwhile to come up with a more complex mechanism
472   // to address this particular weakness right now.
473   static const char *g_reader_instructions;
474 };
475 
476 const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
477     "Enter your debugger command(s).  Type 'DONE' to end.\n";
478 
479 //-------------------------------------------------------------------------
480 // CommandObjectBreakpointCommandDelete
481 //-------------------------------------------------------------------------
482 
483 static OptionDefinition g_breakpoint_delete_options[] = {
484     // clang-format off
485   { 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." },
486     // clang-format on
487 };
488 
489 class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
490 public:
491   CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
492       : CommandObjectParsed(interpreter, "delete",
493                             "Delete the set of commands from a breakpoint.",
494                             nullptr),
495         m_options() {
496     CommandArgumentEntry arg;
497     CommandArgumentData bp_id_arg;
498 
499     // Define the first (and only) variant of this arg.
500     bp_id_arg.arg_type = eArgTypeBreakpointID;
501     bp_id_arg.arg_repetition = eArgRepeatPlain;
502 
503     // There is only one variant this argument could be; put it into the
504     // argument entry.
505     arg.push_back(bp_id_arg);
506 
507     // Push the data for the first argument into the m_arguments vector.
508     m_arguments.push_back(arg);
509   }
510 
511   ~CommandObjectBreakpointCommandDelete() override = default;
512 
513   Options *GetOptions() override { return &m_options; }
514 
515   class CommandOptions : public Options {
516   public:
517     CommandOptions() : Options(), m_use_dummy(false) {}
518 
519     ~CommandOptions() override = default;
520 
521     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
522                          ExecutionContext *execution_context) override {
523       Error error;
524       const int short_option = m_getopt_table[option_idx].val;
525 
526       switch (short_option) {
527       case 'D':
528         m_use_dummy = true;
529         break;
530 
531       default:
532         error.SetErrorStringWithFormat("unrecognized option '%c'",
533                                        short_option);
534         break;
535       }
536 
537       return error;
538     }
539 
540     void OptionParsingStarting(ExecutionContext *execution_context) override {
541       m_use_dummy = false;
542     }
543 
544     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
545       return llvm::makeArrayRef(g_breakpoint_delete_options);
546     }
547 
548     // Instance variables to hold the values for command options.
549     bool m_use_dummy;
550   };
551 
552 protected:
553   bool DoExecute(Args &command, CommandReturnObject &result) override {
554     Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
555 
556     if (target == nullptr) {
557       result.AppendError("There is not a current executable; there are no "
558                          "breakpoints from which to delete commands");
559       result.SetStatus(eReturnStatusFailed);
560       return false;
561     }
562 
563     const BreakpointList &breakpoints = target->GetBreakpointList();
564     size_t num_breakpoints = breakpoints.GetSize();
565 
566     if (num_breakpoints == 0) {
567       result.AppendError("No breakpoints exist to have commands deleted");
568       result.SetStatus(eReturnStatusFailed);
569       return false;
570     }
571 
572     if (command.GetArgumentCount() == 0) {
573       result.AppendError(
574           "No breakpoint specified from which to delete the commands");
575       result.SetStatus(eReturnStatusFailed);
576       return false;
577     }
578 
579     BreakpointIDList valid_bp_ids;
580     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
581         command, target, result, &valid_bp_ids);
582 
583     if (result.Succeeded()) {
584       const size_t count = valid_bp_ids.GetSize();
585       for (size_t i = 0; i < count; ++i) {
586         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
587         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
588           Breakpoint *bp =
589               target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
590           if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
591             BreakpointLocationSP bp_loc_sp(
592                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
593             if (bp_loc_sp)
594               bp_loc_sp->ClearCallback();
595             else {
596               result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
597                                            cur_bp_id.GetBreakpointID(),
598                                            cur_bp_id.GetLocationID());
599               result.SetStatus(eReturnStatusFailed);
600               return false;
601             }
602           } else {
603             bp->ClearCallback();
604           }
605         }
606       }
607     }
608     return result.Succeeded();
609   }
610 
611 private:
612   CommandOptions m_options;
613 };
614 
615 //-------------------------------------------------------------------------
616 // CommandObjectBreakpointCommandList
617 //-------------------------------------------------------------------------
618 
619 class CommandObjectBreakpointCommandList : public CommandObjectParsed {
620 public:
621   CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
622       : CommandObjectParsed(interpreter, "list", "List the script or set of "
623                                                  "commands to be executed when "
624                                                  "the breakpoint is hit.",
625                             nullptr) {
626     CommandArgumentEntry arg;
627     CommandArgumentData bp_id_arg;
628 
629     // Define the first (and only) variant of this arg.
630     bp_id_arg.arg_type = eArgTypeBreakpointID;
631     bp_id_arg.arg_repetition = eArgRepeatPlain;
632 
633     // There is only one variant this argument could be; put it into the
634     // argument entry.
635     arg.push_back(bp_id_arg);
636 
637     // Push the data for the first argument into the m_arguments vector.
638     m_arguments.push_back(arg);
639   }
640 
641   ~CommandObjectBreakpointCommandList() override = default;
642 
643 protected:
644   bool DoExecute(Args &command, CommandReturnObject &result) override {
645     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
646 
647     if (target == nullptr) {
648       result.AppendError("There is not a current executable; there are no "
649                          "breakpoints for which to list commands");
650       result.SetStatus(eReturnStatusFailed);
651       return false;
652     }
653 
654     const BreakpointList &breakpoints = target->GetBreakpointList();
655     size_t num_breakpoints = breakpoints.GetSize();
656 
657     if (num_breakpoints == 0) {
658       result.AppendError("No breakpoints exist for which to list commands");
659       result.SetStatus(eReturnStatusFailed);
660       return false;
661     }
662 
663     if (command.GetArgumentCount() == 0) {
664       result.AppendError(
665           "No breakpoint specified for which to list the commands");
666       result.SetStatus(eReturnStatusFailed);
667       return false;
668     }
669 
670     BreakpointIDList valid_bp_ids;
671     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
672         command, target, result, &valid_bp_ids);
673 
674     if (result.Succeeded()) {
675       const size_t count = valid_bp_ids.GetSize();
676       for (size_t i = 0; i < count; ++i) {
677         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
678         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
679           Breakpoint *bp =
680               target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
681 
682           if (bp) {
683             const BreakpointOptions *bp_options = nullptr;
684             if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
685               BreakpointLocationSP bp_loc_sp(
686                   bp->FindLocationByID(cur_bp_id.GetLocationID()));
687               if (bp_loc_sp)
688                 bp_options = bp_loc_sp->GetOptionsNoCreate();
689               else {
690                 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
691                                              cur_bp_id.GetBreakpointID(),
692                                              cur_bp_id.GetLocationID());
693                 result.SetStatus(eReturnStatusFailed);
694                 return false;
695               }
696             } else {
697               bp_options = bp->GetOptions();
698             }
699 
700             if (bp_options) {
701               StreamString id_str;
702               BreakpointID::GetCanonicalReference(&id_str,
703                                                   cur_bp_id.GetBreakpointID(),
704                                                   cur_bp_id.GetLocationID());
705               const Baton *baton = bp_options->GetBaton();
706               if (baton) {
707                 result.GetOutputStream().Printf("Breakpoint %s:\n",
708                                                 id_str.GetData());
709                 result.GetOutputStream().IndentMore();
710                 baton->GetDescription(&result.GetOutputStream(),
711                                       eDescriptionLevelFull);
712                 result.GetOutputStream().IndentLess();
713               } else {
714                 result.AppendMessageWithFormat(
715                     "Breakpoint %s does not have an associated command.\n",
716                     id_str.GetData());
717               }
718             }
719             result.SetStatus(eReturnStatusSuccessFinishResult);
720           } else {
721             result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
722                                          cur_bp_id.GetBreakpointID());
723             result.SetStatus(eReturnStatusFailed);
724           }
725         }
726       }
727     }
728 
729     return result.Succeeded();
730   }
731 };
732 
733 //-------------------------------------------------------------------------
734 // CommandObjectBreakpointCommand
735 //-------------------------------------------------------------------------
736 
737 CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
738     CommandInterpreter &interpreter)
739     : CommandObjectMultiword(
740           interpreter, "command", "Commands for adding, removing and listing "
741                                   "LLDB commands executed when a breakpoint is "
742                                   "hit.",
743           "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
744   CommandObjectSP add_command_object(
745       new CommandObjectBreakpointCommandAdd(interpreter));
746   CommandObjectSP delete_command_object(
747       new CommandObjectBreakpointCommandDelete(interpreter));
748   CommandObjectSP list_command_object(
749       new CommandObjectBreakpointCommandList(interpreter));
750 
751   add_command_object->SetCommandName("breakpoint command add");
752   delete_command_object->SetCommandName("breakpoint command delete");
753   list_command_object->SetCommandName("breakpoint command list");
754 
755   LoadSubCommand("add", add_command_object);
756   LoadSubCommand("delete", delete_command_object);
757   LoadSubCommand("list", list_command_object);
758 }
759 
760 CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;
761