LLDB mainline
ScriptInterpreterLua.cpp
Go to the documentation of this file.
1//===-- ScriptInterpreterLua.cpp ------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "LuaState.h"
12#include "lldb/Core/Debugger.h"
17#include "lldb/Utility/Stream.h"
19#include "lldb/Utility/Timer.h"
20#include "lldb/lldb-forward.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/FormatAdapters.h"
23#include <memory>
24#include <vector>
25
26using namespace lldb;
27using namespace lldb_private;
28
30
36
38 public IOHandlerEditline {
39public:
41 ScriptInterpreterLua &script_interpreter,
42 ActiveIOHandler active_io_handler = eIOHandlerNone)
44 llvm::StringRef(">>> "), llvm::StringRef("..> "),
45 true, debugger.GetUseColor(), 0, *this),
46 m_script_interpreter(script_interpreter),
47 m_active_io_handler(active_io_handler) {
48 llvm::cantFail(m_script_interpreter.GetLuaState().ChangeIO(
49 debugger.GetOutputFileSP()->GetStream(),
50 debugger.GetErrorFileSP()->GetStream()));
51 llvm::cantFail(m_script_interpreter.EnterSession(debugger.GetID()));
52 }
53
55 llvm::cantFail(m_script_interpreter.LeaveSession());
56 }
57
58 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
59 const char *instructions = nullptr;
60 switch (m_active_io_handler) {
61 case eIOHandlerNone:
62 break;
64 instructions = "Enter your Lua command(s). Type 'quit' to end.\n"
65 "The commands are compiled as the body of the following "
66 "Lua function\n"
67 "function (frame, wp) end\n";
68 SetPrompt(llvm::StringRef("..> "));
69 break;
71 instructions = "Enter your Lua command(s). Type 'quit' to end.\n"
72 "The commands are compiled as the body of the following "
73 "Lua function\n"
74 "function (frame, bp_loc, ...) end\n";
75 SetPrompt(llvm::StringRef("..> "));
76 break;
77 }
78 if (instructions == nullptr)
79 return;
80 if (interactive) {
81 if (lldb::LockableStreamFileSP output_sp =
82 io_handler.GetOutputStreamFileSP()) {
83 LockedStreamFile locked_stream = output_sp->Lock();
84 locked_stream << instructions;
85 }
86 }
87 }
88
90 StringList &lines) override {
91 size_t last = lines.GetSize() - 1;
92 if (IsQuitCommand(lines.GetStringAtIndex(last))) {
95 lines.DeleteStringAtIndex(last);
96 return true;
97 }
98 StreamString str;
99 lines.Join("\n", str);
100 if (llvm::Error E =
101 m_script_interpreter.GetLuaState().CheckSyntax(str.GetString())) {
102 std::string error_str = toString(std::move(E));
103 // Lua always errors out to incomplete code with '<eof>'
104 return error_str.find("<eof>") == std::string::npos;
105 }
106 // The breakpoint and watchpoint handler only exits with a explicit 'quit'
109 }
110
112 std::string &data) override {
113 switch (m_active_io_handler) {
115 auto *bp_options_vec =
116 static_cast<std::vector<std::reference_wrapper<BreakpointOptions>> *>(
117 io_handler.GetUserData());
118 for (BreakpointOptions &bp_options : *bp_options_vec) {
119 if (llvm::Error error =
120 m_script_interpreter.SetBreakpointCommandCallback(
121 bp_options, data.c_str(), /*is_callback=*/false)) {
122 LockedStreamFile locked_stream =
123 io_handler.GetErrorStreamFileSP()->Lock();
124 locked_stream << llvm::toString(std::move(error)) << '\n';
125 }
126 }
127 io_handler.SetIsDone(true);
128 } break;
130 auto *wp_options =
131 static_cast<WatchpointOptions *>(io_handler.GetUserData());
132 if (llvm::Error error = m_script_interpreter.SetWatchpointCommandCallback(
133 wp_options, data.c_str(), /*is_callback=*/false)) {
134 LockedStreamFile locked_stream =
135 io_handler.GetErrorStreamFileSP()->Lock();
136 locked_stream << llvm::toString(std::move(error)) << '\n';
137 }
138 io_handler.SetIsDone(true);
139 } break;
140 case eIOHandlerNone:
141 if (IsQuitCommand(data)) {
142 io_handler.SetIsDone(true);
143 return;
144 }
145 if (llvm::Error error = m_script_interpreter.GetLuaState().Run(data)) {
146 LockedStreamFile locked_stream =
147 io_handler.GetErrorStreamFileSP()->Lock();
148 locked_stream << toString(std::move(error));
149 }
150 break;
151 }
152 }
153
154private:
157
158 bool IsQuitCommand(llvm::StringRef cmd) { return cmd.rtrim() == "quit"; }
159};
160
164
166
168 auto info = std::make_shared<StructuredData::Dictionary>();
169 info->AddStringItem("language", "lua");
170 return info;
171}
172
173bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command,
174 CommandReturnObject *result,
175 const ExecuteScriptOptions &options) {
176 if (command.empty()) {
177 if (result)
178 result->AppendError("empty command passed to lua\n");
179 return false;
180 }
181
182 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
183 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
184 options.GetEnableIO(), m_debugger, result);
185 if (!io_redirect_or_error) {
186 if (result)
188 "failed to redirect I/O: {0}\n",
189 llvm::fmt_consume(io_redirect_or_error.takeError()));
190 else
191 llvm::consumeError(io_redirect_or_error.takeError());
192 return false;
193 }
194
195 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
196
197 if (llvm::Error e =
198 m_lua_state->ChangeIO(io_redirect.GetOutputFile()->GetStream(),
199 io_redirect.GetErrorFile()->GetStream())) {
200 result->AppendErrorWithFormatv("lua failed to redirect I/O: {0}\n",
201 llvm::toString(std::move(e)));
202 return false;
203 }
204
205 if (llvm::Error e = m_lua_state->Run(command)) {
207 "lua failed attempting to evaluate '{0}': {1}\n", command,
208 llvm::toString(std::move(e)));
209 return false;
210 }
211
212 io_redirect.Flush();
213 return true;
214}
215
218
219 // At the moment, the only time the debugger does not have an input file
220 // handle is when this is called directly from lua, in which case it is
221 // both dangerous and unnecessary (not to mention confusing) to try to embed
222 // a running interpreter loop inside the already running lua interpreter
223 // loop, so we won't do it.
224 if (!m_debugger.GetInputFile().IsValid())
225 return llvm::Error::success();
226
227 IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(m_debugger, *this));
228 m_debugger.RunIOHandlerAsync(io_handler_sp);
229 return llvm::Error::success();
230}
231
233 const char *filename, const LoadScriptOptions &options,
235 FileSpec extra_search_dir, lldb::TargetSP loaded_into_target_sp) {
236
237 if (llvm::Error e = m_lua_state->LoadModule(filename)) {
239 "lua failed to import '{0}': {1}\n", filename,
240 llvm::toString(std::move(e)));
241 return false;
242 }
243 return true;
244}
245
251
255
258 return llvm::Error::success();
259
260 const char *fmt_str =
261 "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); "
262 "lldb.target = lldb.debugger:GetSelectedTarget(); "
263 "lldb.process = lldb.target:GetProcess(); "
264 "lldb.thread = lldb.process:GetSelectedThread(); "
265 "lldb.frame = lldb.thread:GetSelectedFrame()";
266 return m_lua_state->Run(llvm::formatv(fmt_str, debugger_id).str());
267}
268
271 return llvm::Error::success();
272
273 m_session_is_active = false;
274
275 llvm::StringRef str = "lldb.debugger = nil; "
276 "lldb.target = nil; "
277 "lldb.process = nil; "
278 "lldb.thread = nil; "
279 "lldb.frame = nil";
280 return m_lua_state->Run(str);
281}
282
284 void *baton, StoppointCallbackContext *context, user_id_t break_id,
285 user_id_t break_loc_id) {
286 assert(context);
287
288 ExecutionContext exe_ctx(context->exe_ctx_ref);
289 Target *target = exe_ctx.GetTargetPtr();
290 if (target == nullptr)
291 return true;
292
293 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
294 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
295 BreakpointLocationSP bp_loc_sp(breakpoint_sp->FindLocationByID(break_loc_id));
296
297 Debugger &debugger = target->GetDebugger();
298 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
300 LuaState &lua_state = lua_interpreter->GetLuaState();
301
302 CommandDataLua *bp_option_data = static_cast<CommandDataLua *>(baton);
303 llvm::Expected<bool> BoolOrErr = lua_state.CallBreakpointCallback(
304 baton, stop_frame_sp, bp_loc_sp, bp_option_data->m_extra_args_sp);
305 if (llvm::Error E = BoolOrErr.takeError()) {
306 *debugger.GetAsyncErrorStream() << toString(std::move(E));
307 return true;
308 }
309
310 return *BoolOrErr;
311}
312
314 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
315 assert(context);
316
317 ExecutionContext exe_ctx(context->exe_ctx_ref);
318 Target *target = exe_ctx.GetTargetPtr();
319 if (target == nullptr)
320 return true;
321
322 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
323 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
324
325 Debugger &debugger = target->GetDebugger();
326 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
328 LuaState &lua_state = lua_interpreter->GetLuaState();
329
330 llvm::Expected<bool> BoolOrErr =
331 lua_state.CallWatchpointCallback(baton, stop_frame_sp, wp_sp);
332 if (llvm::Error E = BoolOrErr.takeError()) {
333 *debugger.GetAsyncErrorStream() << toString(std::move(E));
334 return true;
335 }
336
337 return *BoolOrErr;
338}
339
341 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
342 CommandReturnObject &result) {
343 IOHandlerSP io_handler_sp(
345 io_handler_sp->SetUserData(&bp_options_vec);
346 m_debugger.RunIOHandlerAsync(io_handler_sp);
347}
348
350 WatchpointOptions *wp_options, CommandReturnObject &result) {
351 IOHandlerSP io_handler_sp(
353 io_handler_sp->SetUserData(wp_options);
354 m_debugger.RunIOHandlerAsync(io_handler_sp);
355}
356
358 BreakpointOptions &bp_options, const char *function_name,
359 StructuredData::ObjectSP extra_args_sp) {
360 const char *fmt_str = "return {0}(frame, bp_loc, ...)";
361 std::string oneliner = llvm::formatv(fmt_str, function_name).str();
362 return RegisterBreakpointCallback(bp_options, oneliner.c_str(),
363 extra_args_sp);
364}
365
367 BreakpointOptions &bp_options, const char *command_body_text,
368 bool is_callback) {
369 return RegisterBreakpointCallback(bp_options, command_body_text, {});
370}
371
373 BreakpointOptions &bp_options, const char *command_body_text,
374 StructuredData::ObjectSP extra_args_sp) {
375 auto data_up = std::make_unique<CommandDataLua>(extra_args_sp);
376 if (llvm::Error err = m_lua_state->RegisterBreakpointCallback(
377 data_up.get(), command_body_text))
378 return err;
379 auto baton_sp =
380 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
382 baton_sp);
383 return llvm::Error::success();
384}
385
387 WatchpointOptions *wp_options, const char *command_body_text,
388 bool is_callback) {
389 return RegisterWatchpointCallback(wp_options, command_body_text, {})
390 .takeError();
391}
392
394 WatchpointOptions *wp_options, const char *command_body_text,
395 StructuredData::ObjectSP extra_args_sp) {
396 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
397 llvm::Error err =
398 m_lua_state->RegisterWatchpointCallback(data_up.get(), command_body_text);
399 if (err)
400 return Status::FromError(std::move(err));
401 auto baton_sp =
402 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
404 baton_sp);
405 return {};
406}
407
410 return std::make_shared<ScriptInterpreterLua>(debugger);
411}
412
414 return "Lua script interpreter";
415}
416
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_PLUGIN_DEFINE(PluginName)
@ eIOHandlerWatchpoint
@ eIOHandlerBreakpoint
#define LLDB_SCOPED_TIMER()
Definition Timer.h:88
IOHandlerLuaInterpreter(Debugger &debugger, ScriptInterpreterLua &script_interpreter, ActiveIOHandler active_io_handler=eIOHandlerNone)
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
ScriptInterpreterLua & m_script_interpreter
bool IOHandlerIsInputComplete(IOHandler &io_handler, StringList &lines) override
Called to determine whether typing enter after the last line in lines should end input.
bool IsQuitCommand(llvm::StringRef cmd)
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void SetCallback(BreakpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the breakpoint option set.
void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormatv(const char *format, Args &&...args)
A class to manage flag bits.
Definition Debugger.h:103
lldb::StreamUP GetAsyncErrorStream()
lldb::FileSP GetErrorFileSP()
Definition Debugger.h:165
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:161
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
A file utility class.
Definition FileSpec.h:56
IOHandlerDelegate(Completion completion=Completion::None)
Definition IOHandler.h:188
bool SetPrompt(llvm::StringRef prompt) override
IOHandlerEditline(Debugger &debugger, IOHandler::Type type, const char *editline_name, llvm::StringRef prompt, llvm::StringRef continuation_prompt, bool multi_line, bool color, uint32_t line_number_start, IOHandlerDelegate &delegate)
lldb::LockableStreamFileSP GetErrorStreamFileSP()
Definition IOHandler.cpp:95
lldb::LockableStreamFileSP GetOutputStreamFileSP()
Definition IOHandler.cpp:93
void SetIsDone(bool b)
Definition IOHandler.h:81
llvm::Expected< bool > CallBreakpointCallback(void *baton, lldb::StackFrameSP stop_frame_sp, lldb::BreakpointLocationSP bp_loc_sp, StructuredData::ObjectSP extra_args_sp)
Definition LuaState.cpp:79
llvm::Expected< bool > CallWatchpointCallback(void *baton, lldb::StackFrameSP stop_frame_sp, lldb::WatchpointSP wp_sp)
Definition LuaState.cpp:107
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
void Flush()
Flush our output and error file handles.
static llvm::Expected< std::unique_ptr< ScriptInterpreterIORedirect > > Create(bool enable_io, Debugger &debugger, CommandReturnObject *result)
Create an IO redirect.
llvm::Error EnterSession(lldb::user_id_t debugger_id)
llvm::Error SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *command_body_text, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
llvm::Error RegisterBreakpointCallback(BreakpointOptions &bp_options, const char *command_body_text, StructuredData::ObjectSP extra_args_sp)
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger, lldb::ScriptLanguage)
std::unique_ptr< LuaState > m_lua_state
llvm::Error SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *command_body_text, bool is_callback) override
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={}) override
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
llvm::Error SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
static llvm::StringRef GetPluginNameStatic()
void CollectDataForBreakpointCommandCallback(std::vector< std::reference_wrapper< BreakpointOptions > > &bp_options_vec, CommandReturnObject &result) override
StructuredData::DictionarySP GetInterpreterInfo() override
static llvm::StringRef GetPluginDescriptionStatic()
Status RegisterWatchpointCallback(WatchpointOptions *wp_options, const char *command_body_text, StructuredData::ObjectSP extra_args_sp)
ScriptInterpreter(Debugger &debugger, lldb::ScriptLanguage script_lang)
An error handling class.
Definition Status.h:118
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
llvm::StringRef GetString() const
const char * GetStringAtIndex(size_t idx) const
void DeleteStringAtIndex(size_t id)
void Join(const char *separator, Stream &strm)
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:457
Debugger & GetDebugger() const
Definition Target.h:1366
WatchpointList & GetWatchpointList()
Definition Target.h:988
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
"lldb/Breakpoint/WatchpointOptions.h" Class that manages the options on a watchpoint.
void SetCallback(WatchpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the watchpoint option set.
A class that represents a running process on the host machine.
std::string toString(FormatterBytecode::OpCodes op)
ScriptLanguage
Script interpreter types.
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::ScriptInterpreter > ScriptInterpreterSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
std::shared_ptr< lldb_private::Target > TargetSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47