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