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