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