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