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