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
9 #include "ScriptInterpreterLua.h"
10 #include "Lua.h"
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Core/StreamFile.h"
15 #include "lldb/Interpreter/CommandReturnObject.h"
16 #include "lldb/Target/ExecutionContext.h"
17 #include "lldb/Utility/Stream.h"
18 #include "lldb/Utility/StringList.h"
19 #include "lldb/Utility/Timer.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/FormatAdapters.h"
22 #include <memory>
23 #include <vector>
24
25 using namespace lldb;
26 using namespace lldb_private;
27
28 LLDB_PLUGIN_DEFINE(ScriptInterpreterLua)
29
30 enum ActiveIOHandler {
31 eIOHandlerNone,
32 eIOHandlerBreakpoint,
33 eIOHandlerWatchpoint
34 };
35
36 class IOHandlerLuaInterpreter : public IOHandlerDelegate,
37 public IOHandlerEditline {
38 public:
IOHandlerLuaInterpreter(Debugger & debugger,ScriptInterpreterLua & script_interpreter,ActiveIOHandler active_io_handler=eIOHandlerNone)39 IOHandlerLuaInterpreter(Debugger &debugger,
40 ScriptInterpreterLua &script_interpreter,
41 ActiveIOHandler active_io_handler = eIOHandlerNone)
42 : IOHandlerEditline(debugger, IOHandler::Type::LuaInterpreter, "lua",
43 ">>> ", "..> ", true, debugger.GetUseColor(), 0,
44 *this, nullptr),
45 m_script_interpreter(script_interpreter),
46 m_active_io_handler(active_io_handler) {
47 llvm::cantFail(m_script_interpreter.GetLua().ChangeIO(
48 debugger.GetOutputFile().GetStream(),
49 debugger.GetErrorFile().GetStream()));
50 llvm::cantFail(m_script_interpreter.EnterSession(debugger.GetID()));
51 }
52
~IOHandlerLuaInterpreter()53 ~IOHandlerLuaInterpreter() override {
54 llvm::cantFail(m_script_interpreter.LeaveSession());
55 }
56
IOHandlerActivated(IOHandler & io_handler,bool interactive)57 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
58 const char *instructions = nullptr;
59 switch (m_active_io_handler) {
60 case eIOHandlerNone:
61 case eIOHandlerWatchpoint:
62 break;
63 case eIOHandlerBreakpoint:
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, bp_loc, ...) end\n";
68 SetPrompt(llvm::StringRef("..> "));
69 break;
70 }
71 if (instructions == nullptr)
72 return;
73 if (interactive)
74 *io_handler.GetOutputStreamFileSP() << instructions;
75 }
76
IOHandlerIsInputComplete(IOHandler & io_handler,StringList & lines)77 bool IOHandlerIsInputComplete(IOHandler &io_handler,
78 StringList &lines) override {
79 size_t last = lines.GetSize() - 1;
80 if (IsQuitCommand(lines.GetStringAtIndex(last))) {
81 if (m_active_io_handler == eIOHandlerBreakpoint)
82 lines.DeleteStringAtIndex(last);
83 return true;
84 }
85 StreamString str;
86 lines.Join("\n", str);
87 if (llvm::Error E =
88 m_script_interpreter.GetLua().CheckSyntax(str.GetString())) {
89 std::string error_str = toString(std::move(E));
90 // Lua always errors out to incomplete code with '<eof>'
91 return error_str.find("<eof>") == std::string::npos;
92 }
93 // The breakpoint handler only exits with a explicit 'quit'
94 return m_active_io_handler != eIOHandlerBreakpoint;
95 }
96
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)97 void IOHandlerInputComplete(IOHandler &io_handler,
98 std::string &data) override {
99 switch (m_active_io_handler) {
100 case eIOHandlerBreakpoint: {
101 auto *bp_options_vec = static_cast<std::vector<BreakpointOptions *> *>(
102 io_handler.GetUserData());
103 for (auto *bp_options : *bp_options_vec) {
104 Status error = m_script_interpreter.SetBreakpointCommandCallback(
105 bp_options, data.c_str());
106 if (error.Fail())
107 *io_handler.GetErrorStreamFileSP() << error.AsCString() << '\n';
108 }
109 io_handler.SetIsDone(true);
110 } break;
111 case eIOHandlerWatchpoint:
112 io_handler.SetIsDone(true);
113 break;
114 case eIOHandlerNone:
115 if (IsQuitCommand(data)) {
116 io_handler.SetIsDone(true);
117 return;
118 }
119 if (llvm::Error error = m_script_interpreter.GetLua().Run(data))
120 *io_handler.GetErrorStreamFileSP() << toString(std::move(error));
121 break;
122 }
123 }
124
125 private:
126 ScriptInterpreterLua &m_script_interpreter;
127 ActiveIOHandler m_active_io_handler;
128
IsQuitCommand(llvm::StringRef cmd)129 bool IsQuitCommand(llvm::StringRef cmd) { return cmd.rtrim() == "quit"; }
130 };
131
ScriptInterpreterLua(Debugger & debugger)132 ScriptInterpreterLua::ScriptInterpreterLua(Debugger &debugger)
133 : ScriptInterpreter(debugger, eScriptLanguageLua),
134 m_lua(std::make_unique<Lua>()) {}
135
~ScriptInterpreterLua()136 ScriptInterpreterLua::~ScriptInterpreterLua() {}
137
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)138 bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command,
139 CommandReturnObject *result,
140 const ExecuteScriptOptions &options) {
141 if (command.empty()) {
142 if (result)
143 result->AppendError("empty command passed to lua\n");
144 return false;
145 }
146
147 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
148 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
149 options.GetEnableIO(), m_debugger, result);
150 if (!io_redirect_or_error) {
151 if (result)
152 result->AppendErrorWithFormatv(
153 "failed to redirect I/O: {0}\n",
154 llvm::fmt_consume(io_redirect_or_error.takeError()));
155 else
156 llvm::consumeError(io_redirect_or_error.takeError());
157 return false;
158 }
159
160 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
161
162 if (llvm::Error e =
163 m_lua->ChangeIO(io_redirect.GetOutputFile()->GetStream(),
164 io_redirect.GetErrorFile()->GetStream())) {
165 result->AppendErrorWithFormatv("lua failed to redirect I/O: {0}\n",
166 llvm::toString(std::move(e)));
167 return false;
168 }
169
170 if (llvm::Error e = m_lua->Run(command)) {
171 result->AppendErrorWithFormatv(
172 "lua failed attempting to evaluate '{0}': {1}\n", command,
173 llvm::toString(std::move(e)));
174 return false;
175 }
176
177 io_redirect.Flush();
178 return true;
179 }
180
ExecuteInterpreterLoop()181 void ScriptInterpreterLua::ExecuteInterpreterLoop() {
182 LLDB_SCOPED_TIMER();
183
184 // At the moment, the only time the debugger does not have an input file
185 // handle is when this is called directly from lua, in which case it is
186 // both dangerous and unnecessary (not to mention confusing) to try to embed
187 // a running interpreter loop inside the already running lua interpreter
188 // loop, so we won't do it.
189 if (!m_debugger.GetInputFile().IsValid())
190 return;
191
192 IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(m_debugger, *this));
193 m_debugger.RunIOHandlerAsync(io_handler_sp);
194 }
195
LoadScriptingModule(const char * filename,bool init_session,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)196 bool ScriptInterpreterLua::LoadScriptingModule(
197 const char *filename, bool init_session, lldb_private::Status &error,
198 StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) {
199
200 FileSystem::Instance().Collect(filename);
201 if (llvm::Error e = m_lua->LoadModule(filename)) {
202 error.SetErrorStringWithFormatv("lua failed to import '{0}': {1}\n",
203 filename, llvm::toString(std::move(e)));
204 return false;
205 }
206 return true;
207 }
208
Initialize()209 void ScriptInterpreterLua::Initialize() {
210 static llvm::once_flag g_once_flag;
211
212 llvm::call_once(g_once_flag, []() {
213 PluginManager::RegisterPlugin(GetPluginNameStatic(),
214 GetPluginDescriptionStatic(),
215 lldb::eScriptLanguageLua, CreateInstance);
216 });
217 }
218
Terminate()219 void ScriptInterpreterLua::Terminate() {}
220
EnterSession(user_id_t debugger_id)221 llvm::Error ScriptInterpreterLua::EnterSession(user_id_t debugger_id) {
222 if (m_session_is_active)
223 return llvm::Error::success();
224
225 const char *fmt_str =
226 "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); "
227 "lldb.target = lldb.debugger:GetSelectedTarget(); "
228 "lldb.process = lldb.target:GetProcess(); "
229 "lldb.thread = lldb.process:GetSelectedThread(); "
230 "lldb.frame = lldb.thread:GetSelectedFrame()";
231 return m_lua->Run(llvm::formatv(fmt_str, debugger_id).str());
232 }
233
LeaveSession()234 llvm::Error ScriptInterpreterLua::LeaveSession() {
235 if (!m_session_is_active)
236 return llvm::Error::success();
237
238 m_session_is_active = false;
239
240 llvm::StringRef str = "lldb.debugger = nil; "
241 "lldb.target = nil; "
242 "lldb.process = nil; "
243 "lldb.thread = nil; "
244 "lldb.frame = nil";
245 return m_lua->Run(str);
246 }
247
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)248 bool ScriptInterpreterLua::BreakpointCallbackFunction(
249 void *baton, StoppointCallbackContext *context, user_id_t break_id,
250 user_id_t break_loc_id) {
251 assert(context);
252
253 ExecutionContext exe_ctx(context->exe_ctx_ref);
254 Target *target = exe_ctx.GetTargetPtr();
255 if (target == nullptr)
256 return true;
257
258 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
259 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
260 BreakpointLocationSP bp_loc_sp(breakpoint_sp->FindLocationByID(break_loc_id));
261
262 Debugger &debugger = target->GetDebugger();
263 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
264 debugger.GetScriptInterpreter(true, eScriptLanguageLua));
265 Lua &lua = lua_interpreter->GetLua();
266
267 CommandDataLua *bp_option_data = static_cast<CommandDataLua *>(baton);
268 llvm::Expected<bool> BoolOrErr = lua.CallBreakpointCallback(
269 baton, stop_frame_sp, bp_loc_sp, bp_option_data->m_extra_args_sp);
270 if (llvm::Error E = BoolOrErr.takeError()) {
271 debugger.GetErrorStream() << toString(std::move(E));
272 return true;
273 }
274
275 return *BoolOrErr;
276 }
277
CollectDataForBreakpointCommandCallback(std::vector<BreakpointOptions * > & bp_options_vec,CommandReturnObject & result)278 void ScriptInterpreterLua::CollectDataForBreakpointCommandCallback(
279 std::vector<BreakpointOptions *> &bp_options_vec,
280 CommandReturnObject &result) {
281 IOHandlerSP io_handler_sp(
282 new IOHandlerLuaInterpreter(m_debugger, *this, eIOHandlerBreakpoint));
283 io_handler_sp->SetUserData(&bp_options_vec);
284 m_debugger.RunIOHandlerAsync(io_handler_sp);
285 }
286
SetBreakpointCommandCallbackFunction(BreakpointOptions * bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)287 Status ScriptInterpreterLua::SetBreakpointCommandCallbackFunction(
288 BreakpointOptions *bp_options, const char *function_name,
289 StructuredData::ObjectSP extra_args_sp) {
290 const char *fmt_str = "return {0}(frame, bp_loc, ...)";
291 std::string oneliner = llvm::formatv(fmt_str, function_name).str();
292 return RegisterBreakpointCallback(bp_options, oneliner.c_str(),
293 extra_args_sp);
294 }
295
SetBreakpointCommandCallback(BreakpointOptions * bp_options,const char * command_body_text)296 Status ScriptInterpreterLua::SetBreakpointCommandCallback(
297 BreakpointOptions *bp_options, const char *command_body_text) {
298 return RegisterBreakpointCallback(bp_options, command_body_text, {});
299 }
300
RegisterBreakpointCallback(BreakpointOptions * bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp)301 Status ScriptInterpreterLua::RegisterBreakpointCallback(
302 BreakpointOptions *bp_options, const char *command_body_text,
303 StructuredData::ObjectSP extra_args_sp) {
304 Status error;
305 auto data_up = std::make_unique<CommandDataLua>(extra_args_sp);
306 error = m_lua->RegisterBreakpointCallback(data_up.get(), command_body_text);
307 if (error.Fail())
308 return error;
309 auto baton_sp =
310 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
311 bp_options->SetCallback(ScriptInterpreterLua::BreakpointCallbackFunction,
312 baton_sp);
313 return error;
314 }
315
316 lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)317 ScriptInterpreterLua::CreateInstance(Debugger &debugger) {
318 return std::make_shared<ScriptInterpreterLua>(debugger);
319 }
320
GetPluginNameStatic()321 lldb_private::ConstString ScriptInterpreterLua::GetPluginNameStatic() {
322 static ConstString g_name("script-lua");
323 return g_name;
324 }
325
GetPluginDescriptionStatic()326 const char *ScriptInterpreterLua::GetPluginDescriptionStatic() {
327 return "Lua script interpreter";
328 }
329
GetPluginName()330 lldb_private::ConstString ScriptInterpreterLua::GetPluginName() {
331 return GetPluginNameStatic();
332 }
333
GetPluginVersion()334 uint32_t ScriptInterpreterLua::GetPluginVersion() { return 1; }
335
GetLua()336 Lua &ScriptInterpreterLua::GetLua() { return *m_lua; }
337