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