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