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