180814287SRaphael Isemann //===-- CommandObjectBreakpointCommand.cpp --------------------------------===//
230fdc8d8SChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
630fdc8d8SChris Lattner //
730fdc8d8SChris Lattner //===----------------------------------------------------------------------===//
830fdc8d8SChris Lattner 
930fdc8d8SChris Lattner #include "CommandObjectBreakpointCommand.h"
1030fdc8d8SChris Lattner #include "CommandObjectBreakpoint.h"
11b9c1b51eSKate Stone #include "lldb/Breakpoint/Breakpoint.h"
12b9c1b51eSKate Stone #include "lldb/Breakpoint/BreakpointIDList.h"
13b9c1b51eSKate Stone #include "lldb/Breakpoint/BreakpointLocation.h"
1444d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
153eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
1630fdc8d8SChris Lattner #include "lldb/Interpreter/CommandInterpreter.h"
17*7ced9fffSJonas Devlieghere #include "lldb/Interpreter/CommandOptionArgumentTable.h"
1830fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h"
1947cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
20738af7a6SJim Ingham #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h"
2130fdc8d8SChris Lattner #include "lldb/Target/Target.h"
2230fdc8d8SChris Lattner 
2330fdc8d8SChris Lattner using namespace lldb;
2430fdc8d8SChris Lattner using namespace lldb_private;
2530fdc8d8SChris Lattner 
26f94668e3SRaphael Isemann #define LLDB_OPTIONS_breakpoint_command_add
27f94668e3SRaphael Isemann #include "CommandOptions.inc"
281f0f5b5bSZachary Turner 
29b9c1b51eSKate Stone class CommandObjectBreakpointCommandAdd : public CommandObjectParsed,
30b9c1b51eSKate Stone                                           public IOHandlerDelegateMultiline {
315a988416SJim Ingham public:
CommandObjectBreakpointCommandAdd(CommandInterpreter & interpreter)327428a18cSKate Stone   CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter)
337428a18cSKate Stone       : CommandObjectParsed(interpreter, "add",
34b9c1b51eSKate Stone                             "Add LLDB commands to a breakpoint, to be executed "
35b9c1b51eSKate Stone                             "whenever the breakpoint is hit.  "
3660ad0fd3SJim Ingham                             "The commands added to the breakpoint replace any "
3760ad0fd3SJim Ingham                             "commands previously added to it."
38b9c1b51eSKate Stone                             "  If no breakpoint is specified, adds the "
39b9c1b51eSKate Stone                             "commands to the last created breakpoint.",
40c8ecc2a9SEugene Zelenko                             nullptr),
41b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE",
42b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
43abb0ed44SKazu Hirata         m_func_options("breakpoint command", false, 'F') {
4430fdc8d8SChris Lattner     SetHelpLong(
45ea671fbdSKate Stone         R"(
46ea671fbdSKate Stone General information about entering breakpoint commands
47ea671fbdSKate Stone ------------------------------------------------------
48ea671fbdSKate Stone 
49b9c1b51eSKate Stone )"
50b9c1b51eSKate Stone         "This command will prompt for commands to be executed when the specified \
51ea671fbdSKate Stone breakpoint is hit.  Each command is typed on its own line following the '> ' \
52b9c1b51eSKate Stone prompt until 'DONE' is entered."
53b9c1b51eSKate Stone         R"(
54ea671fbdSKate Stone 
55b9c1b51eSKate Stone )"
56b9c1b51eSKate Stone         "Syntactic errors may not be detected when initially entered, and many \
57ea671fbdSKate Stone malformed commands can silently fail when executed.  If your breakpoint commands \
58b9c1b51eSKate Stone do not appear to be executing, double-check the command syntax."
59b9c1b51eSKate Stone         R"(
60ea671fbdSKate Stone 
61b9c1b51eSKate Stone )"
62b9c1b51eSKate Stone         "Note: You may enter any debugger command exactly as you would at the debugger \
63ea671fbdSKate Stone prompt.  There is no limit to the number of commands supplied, but do NOT enter \
64b9c1b51eSKate Stone more than one command per line."
65b9c1b51eSKate Stone         R"(
66ea671fbdSKate Stone 
67ea671fbdSKate Stone Special information about PYTHON breakpoint commands
68ea671fbdSKate Stone ----------------------------------------------------
69ea671fbdSKate Stone 
70b9c1b51eSKate Stone )"
71b9c1b51eSKate Stone         "You may enter either one or more lines of Python, including function \
72ea671fbdSKate Stone definitions or calls to functions that will have been imported by the time \
73ea671fbdSKate Stone the code executes.  Single line breakpoint commands will be interpreted 'as is' \
74ea671fbdSKate Stone when the breakpoint is hit.  Multiple lines of Python will be wrapped in a \
75b9c1b51eSKate Stone generated function, and a call to the function will be attached to the breakpoint."
76b9c1b51eSKate Stone         R"(
77ea671fbdSKate Stone 
78ea671fbdSKate Stone This auto-generated function is passed in three arguments:
79ea671fbdSKate Stone 
80ea671fbdSKate Stone     frame:  an lldb.SBFrame object for the frame which hit breakpoint.
81ea671fbdSKate Stone 
82ea671fbdSKate Stone     bp_loc: an lldb.SBBreakpointLocation object that represents the breakpoint location that was hit.
83ea671fbdSKate Stone 
84ea671fbdSKate Stone     dict:   the python session dictionary hit.
85ea671fbdSKate Stone 
86b9c1b51eSKate Stone )"
87b9c1b51eSKate Stone         "When specifying a python function with the --python-function option, you need \
88b9c1b51eSKate Stone to supply the function name prepended by the module name:"
89b9c1b51eSKate Stone         R"(
90ea671fbdSKate Stone 
91ea671fbdSKate Stone     --python-function myutils.breakpoint_callback
92ea671fbdSKate Stone 
93365b186cSJim Ingham The function itself must have either of the following prototypes:
94ea671fbdSKate Stone 
95483ec136SJim Ingham def breakpoint_callback(frame, bp_loc, internal_dict):
96ea671fbdSKate Stone   # Your code goes here
97ea671fbdSKate Stone 
98365b186cSJim Ingham or:
99365b186cSJim Ingham 
100483ec136SJim Ingham def breakpoint_callback(frame, bp_loc, extra_args, internal_dict):
101365b186cSJim Ingham   # Your code goes here
102365b186cSJim Ingham 
103b9c1b51eSKate Stone )"
104b9c1b51eSKate Stone         "The arguments are the same as the arguments passed to generated functions as \
105365b186cSJim Ingham described above.  In the second form, any -k and -v pairs provided to the command will \
106365b186cSJim Ingham be packaged into a SBDictionary in an SBStructuredData and passed as the extra_args parameter. \
107365b186cSJim Ingham \n\n\
108365b186cSJim Ingham Note that the global variable 'lldb.frame' will NOT be updated when \
109ea671fbdSKate Stone this function is called, so be sure to use the 'frame' argument. The 'frame' argument \
110ea671fbdSKate Stone can get you to the thread via frame.GetThread(), the thread can get you to the \
111ea671fbdSKate Stone process via thread.GetProcess(), and the process can get you back to the target \
112b9c1b51eSKate Stone via process.GetTarget()."
113b9c1b51eSKate Stone         R"(
114ea671fbdSKate Stone 
115b9c1b51eSKate Stone )"
116b9c1b51eSKate Stone         "Important Note: As Python code gets collected into functions, access to global \
117ea671fbdSKate Stone variables requires explicit scoping using the 'global' keyword.  Be sure to use correct \
118b9c1b51eSKate Stone Python syntax, including indentation, when entering Python breakpoint commands."
119b9c1b51eSKate Stone         R"(
120ea671fbdSKate Stone 
121ea671fbdSKate Stone Example Python one-line breakpoint command:
122ea671fbdSKate Stone 
123ea671fbdSKate Stone (lldb) breakpoint command add -s python 1
124ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
1253b3b9ba1SDave Lee def function (frame, bp_loc, internal_dict):
1263b3b9ba1SDave Lee     """frame: the lldb.SBFrame for the location at which you stopped
1273b3b9ba1SDave Lee        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
1283b3b9ba1SDave Lee        internal_dict: an LLDB support object not to be used"""
1293b3b9ba1SDave Lee     print("Hit this breakpoint!")
1303b3b9ba1SDave Lee     DONE
131ea671fbdSKate Stone 
132ea671fbdSKate Stone As a convenience, this also works for a short Python one-liner:
133ea671fbdSKate Stone 
1343b3b9ba1SDave Lee (lldb) breakpoint command add -s python 1 -o 'import time; print(time.asctime())'
135ea671fbdSKate Stone (lldb) run
136ea671fbdSKate Stone Launching '.../a.out'  (x86_64)
137ea671fbdSKate Stone (lldb) Fri Sep 10 12:17:45 2010
138ea671fbdSKate Stone Process 21778 Stopped
139ea671fbdSKate Stone * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = breakpoint 1.1, queue = com.apple.main-thread
140ea671fbdSKate Stone   36
141ea671fbdSKate Stone   37   	int c(int val)
142ea671fbdSKate Stone   38   	{
143ea671fbdSKate Stone   39 ->	    return val + 3;
144ea671fbdSKate Stone   40   	}
145ea671fbdSKate Stone   41
146ea671fbdSKate Stone   42   	int main (int argc, char const *argv[])
147ea671fbdSKate Stone 
148ea671fbdSKate Stone Example multiple line Python breakpoint command:
149ea671fbdSKate Stone 
150ea671fbdSKate Stone (lldb) breakpoint command add -s p 1
151ea671fbdSKate Stone Enter your Python command(s). Type 'DONE' to end.
1523b3b9ba1SDave Lee def function (frame, bp_loc, internal_dict):
1533b3b9ba1SDave Lee     """frame: the lldb.SBFrame for the location at which you stopped
1543b3b9ba1SDave Lee        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
1553b3b9ba1SDave Lee        internal_dict: an LLDB support object not to be used"""
1563b3b9ba1SDave Lee     global bp_count
1573b3b9ba1SDave Lee     bp_count = bp_count + 1
1583b3b9ba1SDave Lee     print("Hit this breakpoint " + repr(bp_count) + " times!")
1593b3b9ba1SDave Lee     DONE
160ea671fbdSKate Stone 
161b9c1b51eSKate Stone )"
162b9c1b51eSKate Stone         "In this case, since there is a reference to a global variable, \
163ea671fbdSKate Stone 'bp_count', you will also need to make sure 'bp_count' exists and is \
164b9c1b51eSKate Stone initialized:"
165b9c1b51eSKate Stone         R"(
166ea671fbdSKate Stone 
167ea671fbdSKate Stone (lldb) script
168ea671fbdSKate Stone >>> bp_count = 0
169ea671fbdSKate Stone >>> quit()
170ea671fbdSKate Stone 
171b9c1b51eSKate Stone )"
172b9c1b51eSKate Stone         "Your Python code, however organized, can optionally return a value.  \
173ea671fbdSKate Stone If the returned value is False, that tells LLDB not to stop at the breakpoint \
174ea671fbdSKate Stone to which the code is associated. Returning anything other than False, or even \
175ea671fbdSKate Stone returning None, or even omitting a return statement entirely, will cause \
176b9c1b51eSKate Stone LLDB to stop."
177b9c1b51eSKate Stone         R"(
178ea671fbdSKate Stone 
179b9c1b51eSKate Stone )"
180b9c1b51eSKate Stone         "Final Note: A warning that no breakpoint command was generated when there \
181b9c1b51eSKate Stone are no syntax errors may indicate that a function was declared but never called.");
182405fe67fSCaroline Tice 
183738af7a6SJim Ingham     m_all_options.Append(&m_options);
184738af7a6SJim Ingham     m_all_options.Append(&m_func_options, LLDB_OPT_SET_2 | LLDB_OPT_SET_3,
185738af7a6SJim Ingham                          LLDB_OPT_SET_2);
186738af7a6SJim Ingham     m_all_options.Finalize();
187738af7a6SJim Ingham 
188405fe67fSCaroline Tice     CommandArgumentEntry arg;
189405fe67fSCaroline Tice     CommandArgumentData bp_id_arg;
190405fe67fSCaroline Tice 
191405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
192405fe67fSCaroline Tice     bp_id_arg.arg_type = eArgTypeBreakpointID;
1931bb0750bSJim Ingham     bp_id_arg.arg_repetition = eArgRepeatOptional;
194405fe67fSCaroline Tice 
195b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
196b9c1b51eSKate Stone     // argument entry.
197405fe67fSCaroline Tice     arg.push_back(bp_id_arg);
198405fe67fSCaroline Tice 
199405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
200405fe67fSCaroline Tice     m_arguments.push_back(arg);
20130fdc8d8SChris Lattner   }
20230fdc8d8SChris Lattner 
203c8ecc2a9SEugene Zelenko   ~CommandObjectBreakpointCommandAdd() override = default;
2045a988416SJim Ingham 
GetOptions()205738af7a6SJim Ingham   Options *GetOptions() override { return &m_all_options; }
2065a988416SJim Ingham 
IOHandlerActivated(IOHandler & io_handler,bool interactive)2070affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
2087ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
2090affb582SDave Lee     if (output_sp && interactive) {
21044d93782SGreg Clayton       output_sp->PutCString(g_reader_instructions);
21144d93782SGreg Clayton       output_sp->Flush();
21244d93782SGreg Clayton     }
21344d93782SGreg Clayton   }
21444d93782SGreg Clayton 
IOHandlerInputComplete(IOHandler & io_handler,std::string & line)215b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
216b9c1b51eSKate Stone                               std::string &line) override {
21744d93782SGreg Clayton     io_handler.SetIsDone(true);
21844d93782SGreg Clayton 
219cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
220cfb96d84SJim Ingham         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
221cfb96d84SJim Ingham             io_handler.GetUserData();
222cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : *bp_options_vec) {
223a8f3ae7cSJonas Devlieghere       auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
224e14dc268SJim Ingham       cmd_data->user_source.SplitIntoLines(line.c_str(), line.size());
225cfb96d84SJim Ingham       bp_options.SetCommandDataCallback(cmd_data);
22644d93782SGreg Clayton     }
22744d93782SGreg Clayton   }
22844d93782SGreg Clayton 
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)229b9c1b51eSKate Stone   void CollectDataForBreakpointCommandCallback(
230cfb96d84SJim Ingham       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
231b9c1b51eSKate Stone       CommandReturnObject &result) {
232b9c1b51eSKate Stone     m_interpreter.GetLLDBCommandsFromIOHandler(
233b9c1b51eSKate Stone         "> ",             // Prompt
23444d93782SGreg Clayton         *this,            // IOHandlerDelegate
235b9c1b51eSKate Stone         &bp_options_vec); // Baton for the "io_handler" that will be passed back
236b9c1b51eSKate Stone                           // into our IOHandlerDelegate functions
2375a988416SJim Ingham   }
2385a988416SJim Ingham 
2395a988416SJim Ingham   /// Set a one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,const char * oneliner)240cfb96d84SJim Ingham   void SetBreakpointCommandCallback(
241cfb96d84SJim Ingham       std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
242b9c1b51eSKate Stone       const char *oneliner) {
243cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : bp_options_vec) {
244a8f3ae7cSJonas Devlieghere       auto cmd_data = std::make_unique<BreakpointOptions::CommandData>();
2455a988416SJim Ingham 
246e14dc268SJim Ingham       cmd_data->user_source.AppendString(oneliner);
247e14dc268SJim Ingham       cmd_data->stop_on_error = m_options.m_stop_on_error;
2485a988416SJim Ingham 
249cfb96d84SJim Ingham       bp_options.SetCommandDataCallback(cmd_data);
250b5796cb4SJim Ingham     }
2515a988416SJim Ingham   }
2525a988416SJim Ingham 
253738af7a6SJim Ingham   class CommandOptions : public OptionGroup {
2545a988416SJim Ingham   public:
25524f9a2f5SShafik Yaghmour     CommandOptions() = default;
25630fdc8d8SChris Lattner 
257c8ecc2a9SEugene Zelenko     ~CommandOptions() override = default;
2585a988416SJim Ingham 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)25997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
260b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
26197206d57SZachary Turner       Status error;
262a925974bSAdrian Prantl       const int short_option =
263a925974bSAdrian Prantl           g_breakpoint_command_add_options[option_idx].short_option;
2645a988416SJim Ingham 
265b9c1b51eSKate Stone       switch (short_option) {
2665a988416SJim Ingham       case 'o':
2675a988416SJim Ingham         m_use_one_liner = true;
268adcd0268SBenjamin Kramer         m_one_liner = std::string(option_arg);
2695a988416SJim Ingham         break;
2705a988416SJim Ingham 
2715a988416SJim Ingham       case 's':
27247cbf4a0SPavel Labath         m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum(
273bd68a052SRaphael Isemann             option_arg,
274bd68a052SRaphael Isemann             g_breakpoint_command_add_options[option_idx].enum_values,
275b9c1b51eSKate Stone             eScriptLanguageNone, error);
2768983d691SJonas Devlieghere         switch (m_script_language) {
2778983d691SJonas Devlieghere         case eScriptLanguagePython:
2788983d691SJonas Devlieghere         case eScriptLanguageLua:
2795a988416SJim Ingham           m_use_script_language = true;
2808983d691SJonas Devlieghere           break;
2818983d691SJonas Devlieghere         case eScriptLanguageNone:
282acdda134SJonas Devlieghere         case eScriptLanguageUnknown:
2835a988416SJim Ingham           m_use_script_language = false;
2848983d691SJonas Devlieghere           break;
2855a988416SJim Ingham         }
2865a988416SJim Ingham         break;
2875a988416SJim Ingham 
288b9c1b51eSKate Stone       case 'e': {
2895a988416SJim Ingham         bool success = false;
29047cbf4a0SPavel Labath         m_stop_on_error =
29147cbf4a0SPavel Labath             OptionArgParser::ToBoolean(option_arg, false, &success);
2925a988416SJim Ingham         if (!success)
293b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
294fe11483bSZachary Turner               "invalid value for stop-on-error: \"%s\"",
295fe11483bSZachary Turner               option_arg.str().c_str());
296b9c1b51eSKate Stone       } break;
2975a988416SJim Ingham 
29833df7cd3SJim Ingham       case 'D':
29933df7cd3SJim Ingham         m_use_dummy = true;
30033df7cd3SJim Ingham         break;
30133df7cd3SJim Ingham 
3025a988416SJim Ingham       default:
30336162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
3045a988416SJim Ingham       }
3055a988416SJim Ingham       return error;
3065a988416SJim Ingham     }
307c8ecc2a9SEugene Zelenko 
OptionParsingStarting(ExecutionContext * execution_context)308b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
3095a988416SJim Ingham       m_use_commands = true;
3105a988416SJim Ingham       m_use_script_language = false;
3115a988416SJim Ingham       m_script_language = eScriptLanguageNone;
3125a988416SJim Ingham 
3135a988416SJim Ingham       m_use_one_liner = false;
3145a988416SJim Ingham       m_stop_on_error = true;
3155a988416SJim Ingham       m_one_liner.clear();
31633df7cd3SJim Ingham       m_use_dummy = false;
3175a988416SJim Ingham     }
3185a988416SJim Ingham 
GetDefinitions()3191f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
320bd68a052SRaphael Isemann       return llvm::makeArrayRef(g_breakpoint_command_add_options);
3211f0f5b5bSZachary Turner     }
3225a988416SJim Ingham 
3235a988416SJim Ingham     // Instance variables to hold the values for command options.
3245a988416SJim Ingham 
3259494c510SJonas Devlieghere     bool m_use_commands = false;
3269494c510SJonas Devlieghere     bool m_use_script_language = false;
3279494c510SJonas Devlieghere     lldb::ScriptLanguage m_script_language = eScriptLanguageNone;
3285a988416SJim Ingham 
3295a988416SJim Ingham     // Instance variables to hold the values for one_liner options.
3309494c510SJonas Devlieghere     bool m_use_one_liner = false;
3315a988416SJim Ingham     std::string m_one_liner;
3325a988416SJim Ingham     bool m_stop_on_error;
33333df7cd3SJim Ingham     bool m_use_dummy;
3345a988416SJim Ingham   };
3355a988416SJim Ingham 
3365a988416SJim Ingham protected:
DoExecute(Args & command,CommandReturnObject & result)337b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
338cb2380c9SRaphael Isemann     Target &target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
33930fdc8d8SChris Lattner 
340cb2380c9SRaphael Isemann     const BreakpointList &breakpoints = target.GetBreakpointList();
34130fdc8d8SChris Lattner     size_t num_breakpoints = breakpoints.GetSize();
34230fdc8d8SChris Lattner 
343b9c1b51eSKate Stone     if (num_breakpoints == 0) {
34430fdc8d8SChris Lattner       result.AppendError("No breakpoints exist to have commands added");
34530fdc8d8SChris Lattner       return false;
34630fdc8d8SChris Lattner     }
34730fdc8d8SChris Lattner 
348738af7a6SJim Ingham     if (!m_func_options.GetName().empty()) {
349738af7a6SJim Ingham       m_options.m_use_one_liner = false;
3501ff01cfeSJonas Devlieghere       if (!m_options.m_use_script_language) {
3511ff01cfeSJonas Devlieghere         m_options.m_script_language = GetDebugger().GetScriptLanguage();
352738af7a6SJim Ingham         m_options.m_use_script_language = true;
3538d4a8010SEnrico Granata       }
3541ff01cfeSJonas Devlieghere     }
3558d4a8010SEnrico Granata 
35630fdc8d8SChris Lattner     BreakpointIDList valid_bp_ids;
357b9c1b51eSKate Stone     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
358cb2380c9SRaphael Isemann         command, &target, result, &valid_bp_ids,
359b842f2ecSJim Ingham         BreakpointName::Permissions::PermissionKinds::listPerm);
36030fdc8d8SChris Lattner 
361b5796cb4SJim Ingham     m_bp_options_vec.clear();
362b5796cb4SJim Ingham 
363b9c1b51eSKate Stone     if (result.Succeeded()) {
364c982c768SGreg Clayton       const size_t count = valid_bp_ids.GetSize();
365d9916eaeSJim Ingham 
366b9c1b51eSKate Stone       for (size_t i = 0; i < count; ++i) {
36730fdc8d8SChris Lattner         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
368b9c1b51eSKate Stone         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
369b9c1b51eSKate Stone           Breakpoint *bp =
370cb2380c9SRaphael Isemann               target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
371b9c1b51eSKate Stone           if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) {
37239d7d4f0SJohnny Chen             // This breakpoint does not have an associated location.
373cfb96d84SJim Ingham             m_bp_options_vec.push_back(bp->GetOptions());
374b9c1b51eSKate Stone           } else {
375b9c1b51eSKate Stone             BreakpointLocationSP bp_loc_sp(
376b9c1b51eSKate Stone                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
37705097246SAdrian Prantl             // This breakpoint does have an associated location. Get its
37805097246SAdrian Prantl             // breakpoint options.
37930fdc8d8SChris Lattner             if (bp_loc_sp)
380cfb96d84SJim Ingham               m_bp_options_vec.push_back(bp_loc_sp->GetLocationOptions());
38139d7d4f0SJohnny Chen           }
382b5796cb4SJim Ingham         }
383b5796cb4SJim Ingham       }
38439d7d4f0SJohnny Chen 
38505097246SAdrian Prantl       // If we are using script language, get the script interpreter in order
38605097246SAdrian Prantl       // to set or collect command callback.  Otherwise, call the methods
38705097246SAdrian Prantl       // associated with this object.
388b9c1b51eSKate Stone       if (m_options.m_use_script_language) {
389280ae107SPedro Tammela         Status error;
3905e32eb1cSJonas Devlieghere         ScriptInterpreter *script_interp = GetDebugger().GetScriptInterpreter(
3915e32eb1cSJonas Devlieghere             /*can_create=*/true, m_options.m_script_language);
39239d7d4f0SJohnny Chen         // Special handling for one-liner specified inline.
393b9c1b51eSKate Stone         if (m_options.m_use_one_liner) {
394280ae107SPedro Tammela           error = script_interp->SetBreakpointCommandCallback(
395b9c1b51eSKate Stone               m_bp_options_vec, m_options.m_one_liner.c_str());
396738af7a6SJim Ingham         } else if (!m_func_options.GetName().empty()) {
397280ae107SPedro Tammela           error = script_interp->SetBreakpointCommandCallbackFunction(
398738af7a6SJim Ingham               m_bp_options_vec, m_func_options.GetName().c_str(),
399738af7a6SJim Ingham               m_func_options.GetStructuredData());
400b9c1b51eSKate Stone         } else {
401b9c1b51eSKate Stone           script_interp->CollectDataForBreakpointCommandCallback(
402b9c1b51eSKate Stone               m_bp_options_vec, result);
4038d4a8010SEnrico Granata         }
404280ae107SPedro Tammela         if (!error.Success())
405280ae107SPedro Tammela           result.SetError(error);
406b9c1b51eSKate Stone       } else {
40739d7d4f0SJohnny Chen         // Special handling for one-liner specified inline.
40839d7d4f0SJohnny Chen         if (m_options.m_use_one_liner)
409b5796cb4SJim Ingham           SetBreakpointCommandCallback(m_bp_options_vec,
41039d7d4f0SJohnny Chen                                        m_options.m_one_liner.c_str());
41139d7d4f0SJohnny Chen         else
412b9c1b51eSKate Stone           CollectDataForBreakpointCommandCallback(m_bp_options_vec, result);
41330fdc8d8SChris Lattner       }
41430fdc8d8SChris Lattner     }
41530fdc8d8SChris Lattner 
41630fdc8d8SChris Lattner     return result.Succeeded();
41730fdc8d8SChris Lattner   }
41830fdc8d8SChris Lattner 
4195a988416SJim Ingham private:
4205a988416SJim Ingham   CommandOptions m_options;
421738af7a6SJim Ingham   OptionGroupPythonClassWithDict m_func_options;
422738af7a6SJim Ingham   OptionGroupOptions m_all_options;
423738af7a6SJim Ingham 
424cfb96d84SJim Ingham   std::vector<std::reference_wrapper<BreakpointOptions>>
425cfb96d84SJim Ingham       m_bp_options_vec; // This stores the
426b9c1b51eSKate Stone                         // breakpoint options that
427b9c1b51eSKate Stone                         // we are currently
42805097246SAdrian Prantl   // collecting commands for.  In the CollectData... calls we need to hand this
42905097246SAdrian Prantl   // off to the IOHandler, which may run asynchronously. So we have to have
43005097246SAdrian Prantl   // some way to keep it alive, and not leak it. Making it an ivar of the
43105097246SAdrian Prantl   // command object, which never goes away achieves this.  Note that if we were
43205097246SAdrian Prantl   // able to run the same command concurrently in one interpreter we'd have to
43305097246SAdrian Prantl   // make this "per invocation".  But there are many more reasons why it is not
43405097246SAdrian Prantl   // in general safe to do that in lldb at present, so it isn't worthwhile to
43505097246SAdrian Prantl   // come up with a more complex mechanism to address this particular weakness
43605097246SAdrian Prantl   // right now.
4375a988416SJim Ingham   static const char *g_reader_instructions;
4385a988416SJim Ingham };
4395a988416SJim Ingham 
440b9c1b51eSKate Stone const char *CommandObjectBreakpointCommandAdd::g_reader_instructions =
441b9c1b51eSKate Stone     "Enter your debugger command(s).  Type 'DONE' to end.\n";
4425a988416SJim Ingham 
44393e0f19fSCaroline Tice // CommandObjectBreakpointCommandDelete
44430fdc8d8SChris Lattner 
445f94668e3SRaphael Isemann #define LLDB_OPTIONS_breakpoint_command_delete
446f94668e3SRaphael Isemann #include "CommandOptions.inc"
4471f0f5b5bSZachary Turner 
448b9c1b51eSKate Stone class CommandObjectBreakpointCommandDelete : public CommandObjectParsed {
4495a988416SJim Ingham public:
CommandObjectBreakpointCommandDelete(CommandInterpreter & interpreter)450b9c1b51eSKate Stone   CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter)
451b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "delete",
45293e0f19fSCaroline Tice                             "Delete the set of commands from a breakpoint.",
453abb0ed44SKazu Hirata                             nullptr) {
454405fe67fSCaroline Tice     CommandArgumentEntry arg;
455405fe67fSCaroline Tice     CommandArgumentData bp_id_arg;
456405fe67fSCaroline Tice 
457405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
458405fe67fSCaroline Tice     bp_id_arg.arg_type = eArgTypeBreakpointID;
459405fe67fSCaroline Tice     bp_id_arg.arg_repetition = eArgRepeatPlain;
460405fe67fSCaroline Tice 
461b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
462b9c1b51eSKate Stone     // argument entry.
463405fe67fSCaroline Tice     arg.push_back(bp_id_arg);
464405fe67fSCaroline Tice 
465405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
466405fe67fSCaroline Tice     m_arguments.push_back(arg);
46730fdc8d8SChris Lattner   }
46830fdc8d8SChris Lattner 
469c8ecc2a9SEugene Zelenko   ~CommandObjectBreakpointCommandDelete() override = default;
4705a988416SJim Ingham 
GetOptions()471b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
47233df7cd3SJim Ingham 
473b9c1b51eSKate Stone   class CommandOptions : public Options {
47433df7cd3SJim Ingham   public:
47524f9a2f5SShafik Yaghmour     CommandOptions() = default;
47633df7cd3SJim Ingham 
477c8ecc2a9SEugene Zelenko     ~CommandOptions() override = default;
47833df7cd3SJim Ingham 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)47997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
480b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
48197206d57SZachary Turner       Status error;
48233df7cd3SJim Ingham       const int short_option = m_getopt_table[option_idx].val;
48333df7cd3SJim Ingham 
484b9c1b51eSKate Stone       switch (short_option) {
48533df7cd3SJim Ingham       case 'D':
48633df7cd3SJim Ingham         m_use_dummy = true;
48733df7cd3SJim Ingham         break;
48833df7cd3SJim Ingham 
48933df7cd3SJim Ingham       default:
49036162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
49133df7cd3SJim Ingham       }
49233df7cd3SJim Ingham 
49333df7cd3SJim Ingham       return error;
49433df7cd3SJim Ingham     }
49533df7cd3SJim Ingham 
OptionParsingStarting(ExecutionContext * execution_context)496b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
49733df7cd3SJim Ingham       m_use_dummy = false;
49833df7cd3SJim Ingham     }
49933df7cd3SJim Ingham 
GetDefinitions()5001f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
501bd68a052SRaphael Isemann       return llvm::makeArrayRef(g_breakpoint_command_delete_options);
5021f0f5b5bSZachary Turner     }
50333df7cd3SJim Ingham 
50433df7cd3SJim Ingham     // Instance variables to hold the values for command options.
5059494c510SJonas Devlieghere     bool m_use_dummy = false;
50633df7cd3SJim Ingham   };
50733df7cd3SJim Ingham 
5085a988416SJim Ingham protected:
DoExecute(Args & command,CommandReturnObject & result)509b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
510cb2380c9SRaphael Isemann     Target &target = GetSelectedOrDummyTarget(m_options.m_use_dummy);
51130fdc8d8SChris Lattner 
512cb2380c9SRaphael Isemann     const BreakpointList &breakpoints = target.GetBreakpointList();
51330fdc8d8SChris Lattner     size_t num_breakpoints = breakpoints.GetSize();
51430fdc8d8SChris Lattner 
515b9c1b51eSKate Stone     if (num_breakpoints == 0) {
51693e0f19fSCaroline Tice       result.AppendError("No breakpoints exist to have commands deleted");
51730fdc8d8SChris Lattner       return false;
51830fdc8d8SChris Lattner     }
51930fdc8d8SChris Lattner 
52011eb9c64SZachary Turner     if (command.empty()) {
521b9c1b51eSKate Stone       result.AppendError(
522b9c1b51eSKate Stone           "No breakpoint specified from which to delete the commands");
52330fdc8d8SChris Lattner       return false;
52430fdc8d8SChris Lattner     }
52530fdc8d8SChris Lattner 
52630fdc8d8SChris Lattner     BreakpointIDList valid_bp_ids;
527b9c1b51eSKate Stone     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
528cb2380c9SRaphael Isemann         command, &target, result, &valid_bp_ids,
529b842f2ecSJim Ingham         BreakpointName::Permissions::PermissionKinds::listPerm);
53030fdc8d8SChris Lattner 
531b9c1b51eSKate Stone     if (result.Succeeded()) {
532c982c768SGreg Clayton       const size_t count = valid_bp_ids.GetSize();
533b9c1b51eSKate Stone       for (size_t i = 0; i < count; ++i) {
53430fdc8d8SChris Lattner         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
535b9c1b51eSKate Stone         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
536b9c1b51eSKate Stone           Breakpoint *bp =
537cb2380c9SRaphael Isemann               target.GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
538b9c1b51eSKate Stone           if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
539b9c1b51eSKate Stone             BreakpointLocationSP bp_loc_sp(
540b9c1b51eSKate Stone                 bp->FindLocationByID(cur_bp_id.GetLocationID()));
54130fdc8d8SChris Lattner             if (bp_loc_sp)
54230fdc8d8SChris Lattner               bp_loc_sp->ClearCallback();
543b9c1b51eSKate Stone             else {
54430fdc8d8SChris Lattner               result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
54530fdc8d8SChris Lattner                                            cur_bp_id.GetBreakpointID(),
54630fdc8d8SChris Lattner                                            cur_bp_id.GetLocationID());
54730fdc8d8SChris Lattner               return false;
54830fdc8d8SChris Lattner             }
549b9c1b51eSKate Stone           } else {
55030fdc8d8SChris Lattner             bp->ClearCallback();
55130fdc8d8SChris Lattner           }
55230fdc8d8SChris Lattner         }
55330fdc8d8SChris Lattner       }
55430fdc8d8SChris Lattner     }
55530fdc8d8SChris Lattner     return result.Succeeded();
55630fdc8d8SChris Lattner   }
557c8ecc2a9SEugene Zelenko 
55833df7cd3SJim Ingham private:
55933df7cd3SJim Ingham   CommandOptions m_options;
5605a988416SJim Ingham };
56130fdc8d8SChris Lattner 
56230fdc8d8SChris Lattner // CommandObjectBreakpointCommandList
56330fdc8d8SChris Lattner 
564b9c1b51eSKate Stone class CommandObjectBreakpointCommandList : public CommandObjectParsed {
5655a988416SJim Ingham public:
CommandObjectBreakpointCommandList(CommandInterpreter & interpreter)566b9c1b51eSKate Stone   CommandObjectBreakpointCommandList(CommandInterpreter &interpreter)
56704a4c091SRaphael Isemann       : CommandObjectParsed(interpreter, "list",
56804a4c091SRaphael Isemann                             "List the script or set of commands to be "
56904a4c091SRaphael Isemann                             "executed when the breakpoint is hit.",
57004a4c091SRaphael Isemann                             nullptr, eCommandRequiresTarget) {
571405fe67fSCaroline Tice     CommandArgumentEntry arg;
572405fe67fSCaroline Tice     CommandArgumentData bp_id_arg;
573405fe67fSCaroline Tice 
574405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
575405fe67fSCaroline Tice     bp_id_arg.arg_type = eArgTypeBreakpointID;
576405fe67fSCaroline Tice     bp_id_arg.arg_repetition = eArgRepeatPlain;
577405fe67fSCaroline Tice 
578b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
579b9c1b51eSKate Stone     // argument entry.
580405fe67fSCaroline Tice     arg.push_back(bp_id_arg);
581405fe67fSCaroline Tice 
582405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
583405fe67fSCaroline Tice     m_arguments.push_back(arg);
58430fdc8d8SChris Lattner   }
58530fdc8d8SChris Lattner 
586c8ecc2a9SEugene Zelenko   ~CommandObjectBreakpointCommandList() override = default;
58730fdc8d8SChris Lattner 
5885a988416SJim Ingham protected:
DoExecute(Args & command,CommandReturnObject & result)589b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
59004a4c091SRaphael Isemann     Target *target = &GetSelectedTarget();
59130fdc8d8SChris Lattner 
59230fdc8d8SChris Lattner     const BreakpointList &breakpoints = target->GetBreakpointList();
59330fdc8d8SChris Lattner     size_t num_breakpoints = breakpoints.GetSize();
59430fdc8d8SChris Lattner 
595b9c1b51eSKate Stone     if (num_breakpoints == 0) {
59630fdc8d8SChris Lattner       result.AppendError("No breakpoints exist for which to list commands");
59730fdc8d8SChris Lattner       return false;
59830fdc8d8SChris Lattner     }
59930fdc8d8SChris Lattner 
60011eb9c64SZachary Turner     if (command.empty()) {
601b9c1b51eSKate Stone       result.AppendError(
602b9c1b51eSKate Stone           "No breakpoint specified for which to list the commands");
60330fdc8d8SChris Lattner       return false;
60430fdc8d8SChris Lattner     }
60530fdc8d8SChris Lattner 
60630fdc8d8SChris Lattner     BreakpointIDList valid_bp_ids;
607b9c1b51eSKate Stone     CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
608b842f2ecSJim Ingham         command, target, result, &valid_bp_ids,
609b842f2ecSJim Ingham         BreakpointName::Permissions::PermissionKinds::listPerm);
61030fdc8d8SChris Lattner 
611b9c1b51eSKate Stone     if (result.Succeeded()) {
612c982c768SGreg Clayton       const size_t count = valid_bp_ids.GetSize();
613b9c1b51eSKate Stone       for (size_t i = 0; i < count; ++i) {
61430fdc8d8SChris Lattner         BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i);
615b9c1b51eSKate Stone         if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
616b9c1b51eSKate Stone           Breakpoint *bp =
617b9c1b51eSKate Stone               target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get();
61830fdc8d8SChris Lattner 
619b9c1b51eSKate Stone           if (bp) {
620af26b22cSJim Ingham             BreakpointLocationSP bp_loc_sp;
621b9c1b51eSKate Stone             if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) {
622af26b22cSJim Ingham               bp_loc_sp = bp->FindLocationByID(cur_bp_id.GetLocationID());
623a925974bSAdrian Prantl               if (!bp_loc_sp) {
62430fdc8d8SChris Lattner                 result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n",
62530fdc8d8SChris Lattner                                              cur_bp_id.GetBreakpointID(),
62630fdc8d8SChris Lattner                                              cur_bp_id.GetLocationID());
62730fdc8d8SChris Lattner                 return false;
62830fdc8d8SChris Lattner               }
62930fdc8d8SChris Lattner             }
63030fdc8d8SChris Lattner 
63130fdc8d8SChris Lattner             StreamString id_str;
632e16c50a1SJim Ingham             BreakpointID::GetCanonicalReference(&id_str,
633e16c50a1SJim Ingham                                                 cur_bp_id.GetBreakpointID(),
634e16c50a1SJim Ingham                                                 cur_bp_id.GetLocationID());
635af26b22cSJim Ingham             const Baton *baton = nullptr;
636af26b22cSJim Ingham             if (bp_loc_sp)
637a925974bSAdrian Prantl               baton =
638a925974bSAdrian Prantl                   bp_loc_sp
639af26b22cSJim Ingham                       ->GetOptionsSpecifyingKind(BreakpointOptions::eCallback)
640cfb96d84SJim Ingham                       .GetBaton();
641af26b22cSJim Ingham             else
642cfb96d84SJim Ingham               baton = bp->GetOptions().GetBaton();
643af26b22cSJim Ingham 
644b9c1b51eSKate Stone             if (baton) {
645b9c1b51eSKate Stone               result.GetOutputStream().Printf("Breakpoint %s:\n",
646b9c1b51eSKate Stone                                               id_str.GetData());
6474f728bfcSRaphael Isemann               baton->GetDescription(result.GetOutputStream().AsRawOstream(),
6484f728bfcSRaphael Isemann                                     eDescriptionLevelFull,
6494f728bfcSRaphael Isemann                                     result.GetOutputStream().GetIndentLevel() +
6504f728bfcSRaphael Isemann                                         2);
651b9c1b51eSKate Stone             } else {
652b9c1b51eSKate Stone               result.AppendMessageWithFormat(
653b9c1b51eSKate Stone                   "Breakpoint %s does not have an associated command.\n",
654e16c50a1SJim Ingham                   id_str.GetData());
65530fdc8d8SChris Lattner             }
65630fdc8d8SChris Lattner           }
65730fdc8d8SChris Lattner           result.SetStatus(eReturnStatusSuccessFinishResult);
658b9c1b51eSKate Stone         } else {
659b9c1b51eSKate Stone           result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n",
660b9c1b51eSKate Stone                                        cur_bp_id.GetBreakpointID());
66130fdc8d8SChris Lattner         }
66230fdc8d8SChris Lattner       }
66330fdc8d8SChris Lattner     }
66430fdc8d8SChris Lattner 
66530fdc8d8SChris Lattner     return result.Succeeded();
66630fdc8d8SChris Lattner   }
6675a988416SJim Ingham };
66830fdc8d8SChris Lattner 
66930fdc8d8SChris Lattner // CommandObjectBreakpointCommand
67030fdc8d8SChris Lattner 
CommandObjectBreakpointCommand(CommandInterpreter & interpreter)671b9c1b51eSKate Stone CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(
672b9c1b51eSKate Stone     CommandInterpreter &interpreter)
6737428a18cSKate Stone     : CommandObjectMultiword(
674a925974bSAdrian Prantl           interpreter, "command",
675a925974bSAdrian Prantl           "Commands for adding, removing and listing "
676b9c1b51eSKate Stone           "LLDB commands executed when a breakpoint is "
677b9c1b51eSKate Stone           "hit.",
678b9c1b51eSKate Stone           "command <sub-command> [<sub-command-options>] <breakpoint-id>") {
679b9c1b51eSKate Stone   CommandObjectSP add_command_object(
680b9c1b51eSKate Stone       new CommandObjectBreakpointCommandAdd(interpreter));
681b9c1b51eSKate Stone   CommandObjectSP delete_command_object(
682b9c1b51eSKate Stone       new CommandObjectBreakpointCommandDelete(interpreter));
683b9c1b51eSKate Stone   CommandObjectSP list_command_object(
684b9c1b51eSKate Stone       new CommandObjectBreakpointCommandList(interpreter));
68530fdc8d8SChris Lattner 
68630fdc8d8SChris Lattner   add_command_object->SetCommandName("breakpoint command add");
68793e0f19fSCaroline Tice   delete_command_object->SetCommandName("breakpoint command delete");
68830fdc8d8SChris Lattner   list_command_object->SetCommandName("breakpoint command list");
68930fdc8d8SChris Lattner 
69023f59509SGreg Clayton   LoadSubCommand("add", add_command_object);
69123f59509SGreg Clayton   LoadSubCommand("delete", delete_command_object);
69223f59509SGreg Clayton   LoadSubCommand("list", list_command_object);
69330fdc8d8SChris Lattner }
69430fdc8d8SChris Lattner 
695c8ecc2a9SEugene Zelenko CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default;
696