xref: /openbsd-src/gnu/llvm/lldb/source/Commands/CommandObjectBreakpointCommand.cpp (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1dda28197Spatrick //===-- CommandObjectBreakpointCommand.cpp --------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9061da546Spatrick #include "CommandObjectBreakpointCommand.h"
10061da546Spatrick #include "CommandObjectBreakpoint.h"
11061da546Spatrick #include "lldb/Breakpoint/Breakpoint.h"
12061da546Spatrick #include "lldb/Breakpoint/BreakpointIDList.h"
13061da546Spatrick #include "lldb/Breakpoint/BreakpointLocation.h"
14061da546Spatrick #include "lldb/Core/IOHandler.h"
15061da546Spatrick #include "lldb/Host/OptionParser.h"
16061da546Spatrick #include "lldb/Interpreter/CommandInterpreter.h"
17*f6aab3d8Srobert #include "lldb/Interpreter/CommandOptionArgumentTable.h"
18061da546Spatrick #include "lldb/Interpreter/CommandReturnObject.h"
19061da546Spatrick #include "lldb/Interpreter/OptionArgParser.h"
20061da546Spatrick #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h"
21061da546Spatrick #include "lldb/Target/Target.h"
22061da546Spatrick 
23061da546Spatrick using namespace lldb;
24061da546Spatrick using namespace lldb_private;
25061da546Spatrick 
26061da546Spatrick #define LLDB_OPTIONS_breakpoint_command_add
27061da546Spatrick #include "CommandOptions.inc"
28061da546Spatrick 
29061da546Spatrick class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
30061da546Spatrick                                           public IOHandlerDelegateMultiline {
31061da546Spatrick public:
CommandObjectBreakpointCommandAdd(CommandInterpreter & interpreter)32061da546Spatrick   CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
33061da546Spatrick       : CommandObjectParsed(interpreter, "add",
34061da546Spatrick                             "Add LLDB commands to a breakpoint, to be executed "
35061da546Spatrick                             "whenever the breakpoint is hit.  "
36be691f3bSpatrick                             "The commands added to the breakpoint replace any "
37be691f3bSpatrick                             "commands previously added to it."
38061da546Spatrick                             "  If no breakpoint is specified, adds the "
39061da546Spatrick                             "commands to the last created breakpoint.",
40061da546Spatrick                             nullptr),
41061da546Spatrick         IOHandlerDelegateMultiline("DONE",
42061da546Spatrick                                    IOHandlerDelegate::Completion::LLDBCommand),
43*f6aab3d8Srobert         m_func_options("breakpoint command", false, 'F') {
44061da546Spatrick     SetHelpLong(
45061da546Spatrick         R"(
46061da546Spatrick General information about entering breakpoint commands
47061da546Spatrick ------------------------------------------------------
48061da546Spatrick 
49061da546Spatrick )"
50061da546Spatrick         "This command will prompt for commands to be executed when the specified \
51061da546Spatrick breakpoint is hit.  Each command is typed on its own line following the '> ' \
52061da546Spatrick prompt until 'DONE' is entered."
53061da546Spatrick         R"(
54061da546Spatrick 
55061da546Spatrick )"
56061da546Spatrick         "Syntactic errors may not be detected when initially entered, and many \
57061da546Spatrick malformed commands can silently fail when executed.  If your breakpoint commands \
58061da546Spatrick do not appear to be executing, double-check the command syntax."
59061da546Spatrick         R"(
60061da546Spatrick 
61061da546Spatrick )"
62061da546Spatrick         "Note: You may enter any debugger command exactly as you would at the debugger \
63061da546Spatrick prompt.  There is no limit to the number of commands supplied, but do NOT enter \
64061da546Spatrick more than one command per line."
65061da546Spatrick         R"(
66061da546Spatrick 
67061da546Spatrick Special information about PYTHON breakpoint commands
68061da546Spatrick ----------------------------------------------------
69061da546Spatrick 
70061da546Spatrick )"
71061da546Spatrick         "You may enter either one or more lines of Python, including function \
72061da546Spatrick definitions or calls to functions that will have been imported by the time \
73061da546Spatrick the code executes.  Single line breakpoint commands will be interpreted 'as is' \
74061da546Spatrick when the breakpoint is hit.  Multiple lines of Python will be wrapped in a \
75061da546Spatrick generated function, and a call to the function will be attached to the breakpoint."
76061da546Spatrick         R"(
77061da546Spatrick 
78061da546Spatrick This auto-generated function is passed in three arguments:
79061da546Spatrick 
80061da546Spatrick     frame:  an lldb.SBFrame object for the frame which hit breakpoint.
81061da546Spatrick 
82061da546Spatrick     bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
83061da546Spatrick 
84061da546Spatrick     dict:   the python session dictionary hit.
85061da546Spatrick 
86061da546Spatrick )"
87061da546Spatrick         "When specifying a python function with the --python-function option, you need \
88061da546Spatrick to supply the function name prepended by the module name:"
89061da546Spatrick         R"(
90061da546Spatrick 
91061da546Spatrick     --python-function myutils.breakpoint_callback
92061da546Spatrick 
93be691f3bSpatrick The function itself must have either of the following prototypes:
94061da546Spatrick 
95be691f3bSpatrick def breakpoint_callback(frame, bp_loc, internal_dict):
96be691f3bSpatrick   # Your code goes here
97be691f3bSpatrick 
98be691f3bSpatrick or:
99be691f3bSpatrick 
100be691f3bSpatrick def breakpoint_callback(frame, bp_loc, extra_args, internal_dict):
101061da546Spatrick   # Your code goes here
102061da546Spatrick 
103061da546Spatrick )"
104061da546Spatrick         "The arguments are the same as the arguments passed to generated functions as \
105be691f3bSpatrick described above.  In the second form, any -k and -v pairs provided to the command will \
106be691f3bSpatrick be packaged into a SBDictionary in an SBStructuredData and passed as the extra_args parameter. \
107be691f3bSpatrick \n\n\
108be691f3bSpatrick Note that the global variable 'lldb.frame' will NOT be updated when \
109061da546Spatrick this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
110061da546Spatrick can get you to the thread via frame.GetThread(), the thread can get you to the \
111061da546Spatrick process via thread.GetProcess(), and the process can get you back to the target \
112061da546Spatrick via process.GetTarget()."
113061da546Spatrick         R"(
114061da546Spatrick 
115061da546Spatrick )"
116061da546Spatrick         "Important Note: As Python code gets collected into functions, access to global \
117061da546Spatrick variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
118061da546Spatrick Python syntax, including indentation, when entering Python breakpoint commands."
119061da546Spatrick         R"(
120061da546Spatrick 
121061da546Spatrick Example Python one-line breakpoint command:
122061da546Spatrick 
123061da546Spatrick (lldb) breakpoint command add -s python 1
124061da546Spatrick Enter your Python command(s). Type 'DONE' to end.
125be691f3bSpatrick def function (frame, bp_loc, internal_dict):
126be691f3bSpatrick     """frame: the lldb.SBFrame for the location at which you stopped
127be691f3bSpatrick        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
128be691f3bSpatrick        internal_dict: an LLDB support object not to be used"""
129be691f3bSpatrick     print("Hit this breakpoint!")
130be691f3bSpatrick     DONE
131061da546Spatrick 
132061da546Spatrick As a convenience, this also works for a short Python one-liner:
133061da546Spatrick 
134be691f3bSpatrick (lldb) breakpoint command add -s python 1 -o 'import time; print(time.asctime())'
135061da546Spatrick (lldb) run
136061da546Spatrick Launching '.../a.out'  (x86_64)
137061da546Spatrick (lldb) Fri Sep 10 12:17:45 2010
138061da546Spatrick Process 21778 Stopped
139061da546Spatrick * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
140061da546Spatrick   36
141061da546Spatrick   37   	int c(int val)
142061da546Spatrick   38   	{
143061da546Spatrick   39 ->	    return val + 3;
144061da546Spatrick   40   	}
145061da546Spatrick   41
146061da546Spatrick   42   	int main (int argc, char const *argv[])
147061da546Spatrick 
148061da546Spatrick Example multiple line Python breakpoint command:
149061da546Spatrick 
150061da546Spatrick (lldb) breakpoint command add -s p 1
151061da546Spatrick Enter your Python command(s). Type 'DONE' to end.
152be691f3bSpatrick def function (frame, bp_loc, internal_dict):
153be691f3bSpatrick     """frame: the lldb.SBFrame for the location at which you stopped
154be691f3bSpatrick        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
155be691f3bSpatrick        internal_dict: an LLDB support object not to be used"""
156be691f3bSpatrick     global bp_count
157be691f3bSpatrick     bp_count = bp_count + 1
158be691f3bSpatrick     print("Hit this breakpoint " + repr(bp_count) + " times!")
159be691f3bSpatrick     DONE
160061da546Spatrick 
161061da546Spatrick )"
162061da546Spatrick         "In this case, since there is a reference to a global variable, \
163061da546Spatrick 'bp_count', you will also need to make sure 'bp_count' exists and is \
164061da546Spatrick initialized:"
165061da546Spatrick         R"(
166061da546Spatrick 
167061da546Spatrick (lldb) script
168061da546Spatrick >>> bp_count = 0
169061da546Spatrick >>> quit()
170061da546Spatrick 
171061da546Spatrick )"
172061da546Spatrick         "Your Python code, however organized, can optionally return a value.  \
173061da546Spatrick If the returned value is False, that tells LLDB not to stop at the breakpoint \
174061da546Spatrick to which the code is associated. Returning anything other than False, or even \
175061da546Spatrick returning None, or even omitting a return statement entirely, will cause \
176061da546Spatrick LLDB to stop."
177061da546Spatrick         R"(
178061da546Spatrick 
179061da546Spatrick )"
180061da546Spatrick         "Final Note: A warning that no breakpoint command was generated when there \
181061da546Spatrick are no syntax errors may indicate that a function was declared but never called.");
182061da546Spatrick 
183061da546Spatrick     m_all_options.Append(&m_options);
184061da546Spatrick     m_all_options.Append(&m_func_options, LLDB_OPT_SET_2 | LLDB_OPT_SET_3,
185061da546Spatrick                          LLDB_OPT_SET_2);
186061da546Spatrick     m_all_options.Finalize();
187061da546Spatrick 
188061da546Spatrick     CommandArgumentEntry arg;
189061da546Spatrick     CommandArgumentData bp_id_arg;
190061da546Spatrick 
191061da546Spatrick     // Define the first (and only) variant of this arg.
192061da546Spatrick     bp_id_arg.arg_type = eArgTypeBreakpointID;
193061da546Spatrick     bp_id_arg.arg_repetition = eArgRepeatOptional;
194061da546Spatrick 
195061da546Spatrick     // There is only one variant this argument could be; put it into the
196061da546Spatrick     // argument entry.
197061da546Spatrick     arg.push_back(bp_id_arg);
198061da546Spatrick 
199061da546Spatrick     // Push the data for the first argument into the m_arguments vector.
200061da546Spatrick     m_arguments.push_back(arg);
201061da546Spatrick   }
202061da546Spatrick 
203061da546Spatrick   ~CommandObjectBreakpointCommandAdd() override = default;
204061da546Spatrick 
GetOptions()205061da546Spatrick   Options *GetOptions() override { return &m_all_options; }
206061da546Spatrick 
IOHandlerActivated(IOHandler & io_handler,bool interactive)207061da546Spatrick   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
208061da546Spatrick     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
209061da546Spatrick     if (output_sp && interactive) {
210061da546Spatrick       output_sp->PutCString(g_reader_instructions);
211061da546Spatrick       output_sp->Flush();
212061da546Spatrick     }
213061da546Spatrick   }
214061da546Spatrick 
IOHandlerInputComplete(IOHandler & io_handler,std::string & line)215061da546Spatrick   void IOHandlerInputComplete(IOHandler &io_handler,
216061da546Spatrick                               std::string &line) override {
217061da546Spatrick     io_handler.SetIsDone(true);
218061da546Spatrick 
219be691f3bSpatrick     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
220be691f3bSpatrick         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
221be691f3bSpatrick             io_handler.GetUserData();
222be691f3bSpatrick     for (BreakpointOptions &bp_options : *bp_options_vec) {
223061da546Spatrick       auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
224061da546Spatrick       cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
225be691f3bSpatrick       bp_options.SetCommandDataCallback(cmd_data);
226061da546Spatrick     }
227061da546Spatrick   }
228061da546Spatrick 
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)229061da546Spatrick   void CollectDataForBreakpointCommandCallback(
230be691f3bSpatrick       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
231061da546Spatrick       CommandReturnObject &result) {
232061da546Spatrick     m_interpreter.GetLLDBCommandsFromIOHandler(
233061da546Spatrick         "> ",             // Prompt
234061da546Spatrick         *this,            // IOHandlerDelegate
235061da546Spatrick         &bp_options_vec); // Baton for the "io_handler" that will be passed back
236061da546Spatrick                           // into our IOHandlerDelegate functions
237061da546Spatrick   }
238061da546Spatrick 
239061da546Spatrick   /// Set a one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,const char * oneliner)240be691f3bSpatrick   void SetBreakpointCommandCallback(
241be691f3bSpatrick       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
242061da546Spatrick       const char *oneliner) {
243be691f3bSpatrick     for (BreakpointOptions &bp_options : bp_options_vec) {
244061da546Spatrick       auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
245061da546Spatrick 
246061da546Spatrick       cmd_data->user_source.AppendString(oneliner);
247061da546Spatrick       cmd_data->stop_on_error = m_options.m_stop_on_error;
248061da546Spatrick 
249be691f3bSpatrick       bp_options.SetCommandDataCallback(cmd_data);
250061da546Spatrick     }
251061da546Spatrick   }
252061da546Spatrick 
253061da546Spatrick   class CommandOptions : public OptionGroup {
254061da546Spatrick   public:
255*f6aab3d8Srobert     CommandOptions() = default;
256061da546Spatrick 
257061da546Spatrick     ~CommandOptions() override = default;
258061da546Spatrick 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)259061da546Spatrick     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
260061da546Spatrick                           ExecutionContext *execution_context) override {
261061da546Spatrick       Status error;
262061da546Spatrick       const int short_option =
263061da546Spatrick           g_breakpoint_command_add_options[option_idx].short_option;
264061da546Spatrick 
265061da546Spatrick       switch (short_option) {
266061da546Spatrick       case 'o':
267061da546Spatrick         m_use_one_liner = true;
268dda28197Spatrick         m_one_liner = std::string(option_arg);
269061da546Spatrick         break;
270061da546Spatrick 
271061da546Spatrick       case 's':
272061da546Spatrick         m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
273061da546Spatrick             option_arg,
274061da546Spatrick             g_breakpoint_command_add_options[option_idx].enum_values,
275061da546Spatrick             eScriptLanguageNone, error);
276061da546Spatrick         switch (m_script_language) {
277061da546Spatrick         case eScriptLanguagePython:
278061da546Spatrick         case eScriptLanguageLua:
279061da546Spatrick           m_use_script_language = true;
280061da546Spatrick           break;
281061da546Spatrick         case eScriptLanguageNone:
282061da546Spatrick         case eScriptLanguageUnknown:
283061da546Spatrick           m_use_script_language = false;
284061da546Spatrick           break;
285061da546Spatrick         }
286061da546Spatrick         break;
287061da546Spatrick 
288061da546Spatrick       case 'e': {
289061da546Spatrick         bool success = false;
290061da546Spatrick         m_stop_on_error =
291061da546Spatrick             OptionArgParser::ToBoolean(option_arg, false, &success);
292061da546Spatrick         if (!success)
293061da546Spatrick           error.SetErrorStringWithFormat(
294061da546Spatrick               "invalid value for stop-on-error: \"%s\"",
295061da546Spatrick               option_arg.str().c_str());
296061da546Spatrick       } break;
297061da546Spatrick 
298061da546Spatrick       case 'D':
299061da546Spatrick         m_use_dummy = true;
300061da546Spatrick         break;
301061da546Spatrick 
302061da546Spatrick       default:
303061da546Spatrick         llvm_unreachable("Unimplemented option");
304061da546Spatrick       }
305061da546Spatrick       return error;
306061da546Spatrick     }
307061da546Spatrick 
OptionParsingStarting(ExecutionContext * execution_context)308061da546Spatrick     void OptionParsingStarting(ExecutionContext *execution_context) override {
309061da546Spatrick       m_use_commands = true;
310061da546Spatrick       m_use_script_language = false;
311061da546Spatrick       m_script_language = eScriptLanguageNone;
312061da546Spatrick 
313061da546Spatrick       m_use_one_liner = false;
314061da546Spatrick       m_stop_on_error = true;
315061da546Spatrick       m_one_liner.clear();
316061da546Spatrick       m_use_dummy = false;
317061da546Spatrick     }
318061da546Spatrick 
GetDefinitions()319061da546Spatrick     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
320*f6aab3d8Srobert       return llvm::ArrayRef(g_breakpoint_command_add_options);
321061da546Spatrick     }
322061da546Spatrick 
323061da546Spatrick     // Instance variables to hold the values for command options.
324061da546Spatrick 
325be691f3bSpatrick     bool m_use_commands = false;
326be691f3bSpatrick     bool m_use_script_language = false;
327be691f3bSpatrick     lldb::ScriptLanguage m_script_language = eScriptLanguageNone;
328061da546Spatrick 
329061da546Spatrick     // Instance variables to hold the values for one_liner options.
330be691f3bSpatrick     bool m_use_one_liner = false;
331061da546Spatrick     std::string m_one_liner;
332061da546Spatrick     bool m_stop_on_error;
333061da546Spatrick     bool m_use_dummy;
334061da546Spatrick   };
335061da546Spatrick 
336061da546Spatrick protected:
DoExecute(Args & command,CommandReturnObject & result)337061da546Spatrick   bool DoExecute(Args &command, CommandReturnObject &result) override {
338061da546Spatrick     Target &target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
339061da546Spatrick 
340061da546Spatrick     const BreakpointList &breakpoints = target.GetBreakpointList();
341061da546Spatrick     size_t num_breakpoints = breakpoints.GetSize();
342061da546Spatrick 
343061da546Spatrick     if (num_breakpoints == 0) {
344061da546Spatrick       result.AppendError("No breakpoints exist to have commands added");
345061da546Spatrick       return false;
346061da546Spatrick     }
347061da546Spatrick 
348061da546Spatrick     if (!m_func_options.GetName().empty()) {
349061da546Spatrick       m_options.m_use_one_liner = false;
350061da546Spatrick       if (!m_options.m_use_script_language) {
351061da546Spatrick         m_options.m_script_language = GetDebugger().GetScriptLanguage();
352061da546Spatrick         m_options.m_use_script_language = true;
353061da546Spatrick       }
354061da546Spatrick     }
355061da546Spatrick 
356061da546Spatrick     BreakpointIDList valid_bp_ids;
357061da546Spatrick     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
358061da546Spatrick         command, &target, result, &valid_bp_ids,
359061da546Spatrick         BreakpointName::Permissions::PermissionKinds::listPerm);
360061da546Spatrick 
361061da546Spatrick     m_bp_options_vec.clear();
362061da546Spatrick 
363061da546Spatrick     if (result.Succeeded()) {
364061da546Spatrick       const size_t count = valid_bp_ids.GetSize();
365061da546Spatrick 
366061da546Spatrick       for (size_t i = 0; i < count; ++i) {
367061da546Spatrick         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
368061da546Spatrick         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
369061da546Spatrick           Breakpoint *bp =
370061da546Spatrick               target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
371061da546Spatrick           if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
372061da546Spatrick             // This breakpoint does not have an associated location.
373be691f3bSpatrick             m_bp_options_vec.push_back(bp->GetOptions());
374061da546Spatrick           } else {
375061da546Spatrick             BreakpointLocationSP bp_loc_sp(
376061da546Spatrick                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
377061da546Spatrick             // This breakpoint does have an associated location. Get its
378061da546Spatrick             // breakpoint options.
379061da546Spatrick             if (bp_loc_sp)
380be691f3bSpatrick               m_bp_options_vec.push_back(bp_loc_sp->GetLocationOptions());
381061da546Spatrick           }
382061da546Spatrick         }
383061da546Spatrick       }
384061da546Spatrick 
385061da546Spatrick       // If we are using script language, get the script interpreter in order
386061da546Spatrick       // to set or collect command callback.  Otherwise, call the methods
387061da546Spatrick       // associated with this object.
388061da546Spatrick       if (m_options.m_use_script_language) {
389be691f3bSpatrick         Status error;
390061da546Spatrick         ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(
391061da546Spatrick             /*can_create=*/true, m_options.m_script_language);
392061da546Spatrick         // Special handling for one-liner specified inline.
393061da546Spatrick         if (m_options.m_use_one_liner) {
394be691f3bSpatrick           error = script_interp->SetBreakpointCommandCallback(
395061da546Spatrick               m_bp_options_vec, m_options.m_one_liner.c_str());
396061da546Spatrick         } else if (!m_func_options.GetName().empty()) {
397be691f3bSpatrick           error = script_interp->SetBreakpointCommandCallbackFunction(
398061da546Spatrick               m_bp_options_vec, m_func_options.GetName().c_str(),
399061da546Spatrick               m_func_options.GetStructuredData());
400061da546Spatrick         } else {
401061da546Spatrick           script_interp->CollectDataForBreakpointCommandCallback(
402061da546Spatrick               m_bp_options_vec, result);
403061da546Spatrick         }
404be691f3bSpatrick         if (!error.Success())
405be691f3bSpatrick           result.SetError(error);
406061da546Spatrick       } else {
407061da546Spatrick         // Special handling for one-liner specified inline.
408061da546Spatrick         if (m_options.m_use_one_liner)
409061da546Spatrick           SetBreakpointCommandCallback(m_bp_options_vec,
410061da546Spatrick                                        m_options.m_one_liner.c_str());
411061da546Spatrick         else
412061da546Spatrick           CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
413061da546Spatrick       }
414061da546Spatrick     }
415061da546Spatrick 
416061da546Spatrick     return result.Succeeded();
417061da546Spatrick   }
418061da546Spatrick 
419061da546Spatrick private:
420061da546Spatrick   CommandOptions m_options;
421061da546Spatrick   OptionGroupPythonClassWithDict m_func_options;
422061da546Spatrick   OptionGroupOptions m_all_options;
423061da546Spatrick 
424be691f3bSpatrick   std::vector<std::reference_wrapper<BreakpointOptions>>
425be691f3bSpatrick       m_bp_options_vec; // This stores the
426061da546Spatrick                         // breakpoint options that
427061da546Spatrick                         // we are currently
428061da546Spatrick   // collecting commands for.  In the CollectData... calls we need to hand this
429061da546Spatrick   // off to the IOHandler, which may run asynchronously. So we have to have
430061da546Spatrick   // some way to keep it alive, and not leak it. Making it an ivar of the
431061da546Spatrick   // command object, which never goes away achieves this.  Note that if we were
432061da546Spatrick   // able to run the same command concurrently in one interpreter we'd have to
433061da546Spatrick   // make this "per invocation".  But there are many more reasons why it is not
434061da546Spatrick   // in general safe to do that in lldb at present, so it isn't worthwhile to
435061da546Spatrick   // come up with a more complex mechanism to address this particular weakness
436061da546Spatrick   // right now.
437061da546Spatrick   static const char *g_reader_instructions;
438061da546Spatrick };
439061da546Spatrick 
440061da546Spatrick const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
441061da546Spatrick     "Enter your debugger command(s).  Type 'DONE' to end.\n";
442061da546Spatrick 
443061da546Spatrick // CommandObjectBreakpointCommandDelete
444061da546Spatrick 
445061da546Spatrick #define LLDB_OPTIONS_breakpoint_command_delete
446061da546Spatrick #include "CommandOptions.inc"
447061da546Spatrick 
448061da546Spatrick class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
449061da546Spatrick public:
CommandObjectBreakpointCommandDelete(CommandInterpreter & interpreter)450061da546Spatrick   CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
451061da546Spatrick       : CommandObjectParsed(interpreter, "delete",
452061da546Spatrick                             "Delete the set of commands from a breakpoint.",
453*f6aab3d8Srobert                             nullptr) {
454061da546Spatrick     CommandArgumentEntry arg;
455061da546Spatrick     CommandArgumentData bp_id_arg;
456061da546Spatrick 
457061da546Spatrick     // Define the first (and only) variant of this arg.
458061da546Spatrick     bp_id_arg.arg_type = eArgTypeBreakpointID;
459061da546Spatrick     bp_id_arg.arg_repetition = eArgRepeatPlain;
460061da546Spatrick 
461061da546Spatrick     // There is only one variant this argument could be; put it into the
462061da546Spatrick     // argument entry.
463061da546Spatrick     arg.push_back(bp_id_arg);
464061da546Spatrick 
465061da546Spatrick     // Push the data for the first argument into the m_arguments vector.
466061da546Spatrick     m_arguments.push_back(arg);
467061da546Spatrick   }
468061da546Spatrick 
469061da546Spatrick   ~CommandObjectBreakpointCommandDelete() override = default;
470061da546Spatrick 
GetOptions()471061da546Spatrick   Options *GetOptions() override { return &m_options; }
472061da546Spatrick 
473061da546Spatrick   class CommandOptions : public Options {
474061da546Spatrick   public:
475*f6aab3d8Srobert     CommandOptions() = default;
476061da546Spatrick 
477061da546Spatrick     ~CommandOptions() override = default;
478061da546Spatrick 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)479061da546Spatrick     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
480061da546Spatrick                           ExecutionContext *execution_context) override {
481061da546Spatrick       Status error;
482061da546Spatrick       const int short_option = m_getopt_table[option_idx].val;
483061da546Spatrick 
484061da546Spatrick       switch (short_option) {
485061da546Spatrick       case 'D':
486061da546Spatrick         m_use_dummy = true;
487061da546Spatrick         break;
488061da546Spatrick 
489061da546Spatrick       default:
490061da546Spatrick         llvm_unreachable("Unimplemented option");
491061da546Spatrick       }
492061da546Spatrick 
493061da546Spatrick       return error;
494061da546Spatrick     }
495061da546Spatrick 
OptionParsingStarting(ExecutionContext * execution_context)496061da546Spatrick     void OptionParsingStarting(ExecutionContext *execution_context) override {
497061da546Spatrick       m_use_dummy = false;
498061da546Spatrick     }
499061da546Spatrick 
GetDefinitions()500061da546Spatrick     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
501*f6aab3d8Srobert       return llvm::ArrayRef(g_breakpoint_command_delete_options);
502061da546Spatrick     }
503061da546Spatrick 
504061da546Spatrick     // Instance variables to hold the values for command options.
505be691f3bSpatrick     bool m_use_dummy = false;
506061da546Spatrick   };
507061da546Spatrick 
508061da546Spatrick protected:
DoExecute(Args & command,CommandReturnObject & result)509061da546Spatrick   bool DoExecute(Args &command, CommandReturnObject &result) override {
510061da546Spatrick     Target &target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
511061da546Spatrick 
512061da546Spatrick     const BreakpointList &breakpoints = target.GetBreakpointList();
513061da546Spatrick     size_t num_breakpoints = breakpoints.GetSize();
514061da546Spatrick 
515061da546Spatrick     if (num_breakpoints == 0) {
516061da546Spatrick       result.AppendError("No breakpoints exist to have commands deleted");
517061da546Spatrick       return false;
518061da546Spatrick     }
519061da546Spatrick 
520061da546Spatrick     if (command.empty()) {
521061da546Spatrick       result.AppendError(
522061da546Spatrick           "No breakpoint specified from which to delete the commands");
523061da546Spatrick       return false;
524061da546Spatrick     }
525061da546Spatrick 
526061da546Spatrick     BreakpointIDList valid_bp_ids;
527061da546Spatrick     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
528061da546Spatrick         command, &target, result, &valid_bp_ids,
529061da546Spatrick         BreakpointName::Permissions::PermissionKinds::listPerm);
530061da546Spatrick 
531061da546Spatrick     if (result.Succeeded()) {
532061da546Spatrick       const size_t count = valid_bp_ids.GetSize();
533061da546Spatrick       for (size_t i = 0; i < count; ++i) {
534061da546Spatrick         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
535061da546Spatrick         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
536061da546Spatrick           Breakpoint *bp =
537061da546Spatrick               target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
538061da546Spatrick           if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
539061da546Spatrick             BreakpointLocationSP bp_loc_sp(
540061da546Spatrick                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
541061da546Spatrick             if (bp_loc_sp)
542061da546Spatrick               bp_loc_sp->ClearCallback();
543061da546Spatrick             else {
544061da546Spatrick               result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
545061da546Spatrick                                            cur_bp_id.GetBreakpointID(),
546061da546Spatrick                                            cur_bp_id.GetLocationID());
547061da546Spatrick               return false;
548061da546Spatrick             }
549061da546Spatrick           } else {
550061da546Spatrick             bp->ClearCallback();
551061da546Spatrick           }
552061da546Spatrick         }
553061da546Spatrick       }
554061da546Spatrick     }
555061da546Spatrick     return result.Succeeded();
556061da546Spatrick   }
557061da546Spatrick 
558061da546Spatrick private:
559061da546Spatrick   CommandOptions m_options;
560061da546Spatrick };
561061da546Spatrick 
562061da546Spatrick // CommandObjectBreakpointCommandList
563061da546Spatrick 
564061da546Spatrick class CommandObjectBreakpointCommandList : public CommandObjectParsed {
565061da546Spatrick public:
CommandObjectBreakpointCommandList(CommandInterpreter & interpreter)566061da546Spatrick   CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
567061da546Spatrick       : CommandObjectParsed(interpreter, "list",
568061da546Spatrick                             "List the script or set of commands to be "
569061da546Spatrick                             "executed when the breakpoint is hit.",
570061da546Spatrick                             nullptr, eCommandRequiresTarget) {
571061da546Spatrick     CommandArgumentEntry arg;
572061da546Spatrick     CommandArgumentData bp_id_arg;
573061da546Spatrick 
574061da546Spatrick     // Define the first (and only) variant of this arg.
575061da546Spatrick     bp_id_arg.arg_type = eArgTypeBreakpointID;
576061da546Spatrick     bp_id_arg.arg_repetition = eArgRepeatPlain;
577061da546Spatrick 
578061da546Spatrick     // There is only one variant this argument could be; put it into the
579061da546Spatrick     // argument entry.
580061da546Spatrick     arg.push_back(bp_id_arg);
581061da546Spatrick 
582061da546Spatrick     // Push the data for the first argument into the m_arguments vector.
583061da546Spatrick     m_arguments.push_back(arg);
584061da546Spatrick   }
585061da546Spatrick 
586061da546Spatrick   ~CommandObjectBreakpointCommandList() override = default;
587061da546Spatrick 
588061da546Spatrick protected:
DoExecute(Args & command,CommandReturnObject & result)589061da546Spatrick   bool DoExecute(Args &command, CommandReturnObject &result) override {
590061da546Spatrick     Target *target = &GetSelectedTarget();
591061da546Spatrick 
592061da546Spatrick     const BreakpointList &breakpoints = target->GetBreakpointList();
593061da546Spatrick     size_t num_breakpoints = breakpoints.GetSize();
594061da546Spatrick 
595061da546Spatrick     if (num_breakpoints == 0) {
596061da546Spatrick       result.AppendError("No breakpoints exist for which to list commands");
597061da546Spatrick       return false;
598061da546Spatrick     }
599061da546Spatrick 
600061da546Spatrick     if (command.empty()) {
601061da546Spatrick       result.AppendError(
602061da546Spatrick           "No breakpoint specified for which to list the commands");
603061da546Spatrick       return false;
604061da546Spatrick     }
605061da546Spatrick 
606061da546Spatrick     BreakpointIDList valid_bp_ids;
607061da546Spatrick     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
608061da546Spatrick         command, target, result, &valid_bp_ids,
609061da546Spatrick         BreakpointName::Permissions::PermissionKinds::listPerm);
610061da546Spatrick 
611061da546Spatrick     if (result.Succeeded()) {
612061da546Spatrick       const size_t count = valid_bp_ids.GetSize();
613061da546Spatrick       for (size_t i = 0; i < count; ++i) {
614061da546Spatrick         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
615061da546Spatrick         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
616061da546Spatrick           Breakpoint *bp =
617061da546Spatrick               target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
618061da546Spatrick 
619061da546Spatrick           if (bp) {
620061da546Spatrick             BreakpointLocationSP bp_loc_sp;
621061da546Spatrick             if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
622061da546Spatrick               bp_loc_sp = bp->FindLocationByID(cur_bp_id.GetLocationID());
623061da546Spatrick               if (!bp_loc_sp) {
624061da546Spatrick                 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
625061da546Spatrick                                              cur_bp_id.GetBreakpointID(),
626061da546Spatrick                                              cur_bp_id.GetLocationID());
627061da546Spatrick                 return false;
628061da546Spatrick               }
629061da546Spatrick             }
630061da546Spatrick 
631061da546Spatrick             StreamString id_str;
632061da546Spatrick             BreakpointID::GetCanonicalReference(&id_str,
633061da546Spatrick                                                 cur_bp_id.GetBreakpointID(),
634061da546Spatrick                                                 cur_bp_id.GetLocationID());
635061da546Spatrick             const Baton *baton = nullptr;
636061da546Spatrick             if (bp_loc_sp)
637061da546Spatrick               baton =
638061da546Spatrick                   bp_loc_sp
639061da546Spatrick                       ->GetOptionsSpecifyingKind(BreakpointOptions::eCallback)
640be691f3bSpatrick                       .GetBaton();
641061da546Spatrick             else
642be691f3bSpatrick               baton = bp->GetOptions().GetBaton();
643061da546Spatrick 
644061da546Spatrick             if (baton) {
645061da546Spatrick               result.GetOutputStream().Printf("Breakpoint %s:\n",
646061da546Spatrick                                               id_str.GetData());
647061da546Spatrick               baton->GetDescription(result.GetOutputStream().AsRawOstream(),
648061da546Spatrick                                     eDescriptionLevelFull,
649061da546Spatrick                                     result.GetOutputStream().GetIndentLevel() +
650061da546Spatrick                                         2);
651061da546Spatrick             } else {
652061da546Spatrick               result.AppendMessageWithFormat(
653061da546Spatrick                   "Breakpoint %s does not have an associated command.\n",
654061da546Spatrick                   id_str.GetData());
655061da546Spatrick             }
656061da546Spatrick           }
657061da546Spatrick           result.SetStatus(eReturnStatusSuccessFinishResult);
658061da546Spatrick         } else {
659061da546Spatrick           result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
660061da546Spatrick                                        cur_bp_id.GetBreakpointID());
661061da546Spatrick         }
662061da546Spatrick       }
663061da546Spatrick     }
664061da546Spatrick 
665061da546Spatrick     return result.Succeeded();
666061da546Spatrick   }
667061da546Spatrick };
668061da546Spatrick 
669061da546Spatrick // CommandObjectBreakpointCommand
670061da546Spatrick 
CommandObjectBreakpointCommand(CommandInterpreter & interpreter)671061da546Spatrick CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
672061da546Spatrick     CommandInterpreter &interpreter)
673061da546Spatrick     : CommandObjectMultiword(
674061da546Spatrick           interpreter, "command",
675061da546Spatrick           "Commands for adding, removing and listing "
676061da546Spatrick           "LLDB commands executed when a breakpoint is "
677061da546Spatrick           "hit.",
678061da546Spatrick           "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
679061da546Spatrick   CommandObjectSP add_command_object(
680061da546Spatrick       new CommandObjectBreakpointCommandAdd(interpreter));
681061da546Spatrick   CommandObjectSP delete_command_object(
682061da546Spatrick       new CommandObjectBreakpointCommandDelete(interpreter));
683061da546Spatrick   CommandObjectSP list_command_object(
684061da546Spatrick       new CommandObjectBreakpointCommandList(interpreter));
685061da546Spatrick 
686061da546Spatrick   add_command_object->SetCommandName("breakpoint command add");
687061da546Spatrick   delete_command_object->SetCommandName("breakpoint command delete");
688061da546Spatrick   list_command_object->SetCommandName("breakpoint command list");
689061da546Spatrick 
690061da546Spatrick   LoadSubCommand("add", add_command_object);
691061da546Spatrick   LoadSubCommand("delete", delete_command_object);
692061da546Spatrick   LoadSubCommand("list", list_command_object);
693061da546Spatrick }
694061da546Spatrick 
695061da546Spatrick CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;
696