xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Lua/ScriptInterpreterLua.cpp (revision 5c1c8443eb7366e6e5086426b5d8dc7d24afc13b)
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/Support/FormatAdapters.h"
21 #include <memory>
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 LLDB_PLUGIN_DEFINE(ScriptInterpreterLua)
27 
28 class IOHandlerLuaInterpreter : public IOHandlerDelegate,
29                                 public IOHandlerEditline {
30 public:
31   IOHandlerLuaInterpreter(Debugger &debugger,
32                           ScriptInterpreterLua &script_interpreter)
33       : IOHandlerEditline(debugger, IOHandler::Type::LuaInterpreter, "lua",
34                           ">>> ", "..> ", true, debugger.GetUseColor(), 0,
35                           *this, nullptr),
36         m_script_interpreter(script_interpreter) {
37     llvm::cantFail(m_script_interpreter.GetLua().ChangeIO(
38         debugger.GetOutputFile().GetStream(),
39         debugger.GetErrorFile().GetStream()));
40     llvm::cantFail(m_script_interpreter.EnterSession(debugger.GetID()));
41   }
42 
43   ~IOHandlerLuaInterpreter() override {
44     llvm::cantFail(m_script_interpreter.LeaveSession());
45   }
46 
47   void IOHandlerInputComplete(IOHandler &io_handler,
48                               std::string &data) override {
49     if (llvm::StringRef(data).rtrim() == "quit") {
50       io_handler.SetIsDone(true);
51       return;
52     }
53 
54     if (llvm::Error error = m_script_interpreter.GetLua().Run(data)) {
55       *GetOutputStreamFileSP() << llvm::toString(std::move(error));
56     }
57   }
58 
59 private:
60   ScriptInterpreterLua &m_script_interpreter;
61 };
62 
63 ScriptInterpreterLua::ScriptInterpreterLua(Debugger &debugger)
64     : ScriptInterpreter(debugger, eScriptLanguageLua),
65       m_lua(std::make_unique<Lua>()) {}
66 
67 ScriptInterpreterLua::~ScriptInterpreterLua() {}
68 
69 bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command,
70                                           CommandReturnObject *result,
71                                           const ExecuteScriptOptions &options) {
72   if (command.empty()) {
73     if (result)
74       result->AppendError("empty command passed to lua\n");
75     return false;
76   }
77 
78   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
79       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
80           options.GetEnableIO(), m_debugger, result);
81   if (!io_redirect_or_error) {
82     if (result)
83       result->AppendErrorWithFormatv(
84           "failed to redirect I/O: {0}\n",
85           llvm::fmt_consume(io_redirect_or_error.takeError()));
86     else
87       llvm::consumeError(io_redirect_or_error.takeError());
88     return false;
89   }
90 
91   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
92 
93   if (llvm::Error e =
94           m_lua->ChangeIO(io_redirect.GetOutputFile()->GetStream(),
95                           io_redirect.GetErrorFile()->GetStream())) {
96     result->AppendErrorWithFormatv("lua failed to redirect I/O: {0}\n",
97                                    llvm::toString(std::move(e)));
98     return false;
99   }
100 
101   if (llvm::Error e = m_lua->Run(command)) {
102     result->AppendErrorWithFormatv(
103         "lua failed attempting to evaluate '{0}': {1}\n", command,
104         llvm::toString(std::move(e)));
105     return false;
106   }
107 
108   io_redirect.Flush();
109   return true;
110 }
111 
112 void ScriptInterpreterLua::ExecuteInterpreterLoop() {
113   LLDB_SCOPED_TIMER();
114 
115   // At the moment, the only time the debugger does not have an input file
116   // handle is when this is called directly from lua, in which case it is
117   // both dangerous and unnecessary (not to mention confusing) to try to embed
118   // a running interpreter loop inside the already running lua interpreter
119   // loop, so we won't do it.
120   if (!m_debugger.GetInputFile().IsValid())
121     return;
122 
123   IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(m_debugger, *this));
124   m_debugger.RunIOHandlerAsync(io_handler_sp);
125 }
126 
127 bool ScriptInterpreterLua::LoadScriptingModule(
128     const char *filename, bool init_session, lldb_private::Status &error,
129     StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) {
130 
131   FileSystem::Instance().Collect(filename);
132   if (llvm::Error e = m_lua->LoadModule(filename)) {
133     error.SetErrorStringWithFormatv("lua failed to import '{0}': {1}\n",
134                                     filename, llvm::toString(std::move(e)));
135     return false;
136   }
137   return true;
138 }
139 
140 void ScriptInterpreterLua::Initialize() {
141   static llvm::once_flag g_once_flag;
142 
143   llvm::call_once(g_once_flag, []() {
144     PluginManager::RegisterPlugin(GetPluginNameStatic(),
145                                   GetPluginDescriptionStatic(),
146                                   lldb::eScriptLanguageLua, CreateInstance);
147   });
148 }
149 
150 void ScriptInterpreterLua::Terminate() {}
151 
152 llvm::Error ScriptInterpreterLua::EnterSession(user_id_t debugger_id) {
153   if (m_session_is_active)
154     return llvm::Error::success();
155 
156   const char *fmt_str =
157       "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); "
158       "lldb.target = lldb.debugger:GetSelectedTarget(); "
159       "lldb.process = lldb.target:GetProcess(); "
160       "lldb.thread = lldb.process:GetSelectedThread(); "
161       "lldb.frame = lldb.thread:GetSelectedFrame()";
162   return m_lua->Run(llvm::formatv(fmt_str, debugger_id).str());
163 }
164 
165 llvm::Error ScriptInterpreterLua::LeaveSession() {
166   if (!m_session_is_active)
167     return llvm::Error::success();
168 
169   m_session_is_active = false;
170 
171   llvm::StringRef str = "lldb.debugger = nil; "
172                         "lldb.target = nil; "
173                         "lldb.process = nil; "
174                         "lldb.thread = nil; "
175                         "lldb.frame = nil";
176   return m_lua->Run(str);
177 }
178 
179 bool ScriptInterpreterLua::BreakpointCallbackFunction(
180     void *baton, StoppointCallbackContext *context, user_id_t break_id,
181     user_id_t break_loc_id) {
182   assert(context);
183 
184   ExecutionContext exe_ctx(context->exe_ctx_ref);
185   Target *target = exe_ctx.GetTargetPtr();
186   if (target == nullptr)
187     return true;
188 
189   StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
190   BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
191   BreakpointLocationSP bp_loc_sp(breakpoint_sp->FindLocationByID(break_loc_id));
192 
193   Debugger &debugger = target->GetDebugger();
194   ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
195       debugger.GetScriptInterpreter(true, eScriptLanguageLua));
196   Lua &lua = lua_interpreter->GetLua();
197 
198   llvm::Expected<bool> BoolOrErr =
199       lua.CallBreakpointCallback(baton, stop_frame_sp, bp_loc_sp);
200   if (llvm::Error E = BoolOrErr.takeError()) {
201     debugger.GetErrorStream() << toString(std::move(E));
202     return true;
203   }
204 
205   return *BoolOrErr;
206 }
207 
208 Status ScriptInterpreterLua::SetBreakpointCommandCallback(
209     BreakpointOptions *bp_options, const char *command_body_text) {
210   Status error;
211   auto data_up = std::make_unique<CommandDataLua>();
212   error = m_lua->RegisterBreakpointCallback(data_up.get(), command_body_text);
213   if (error.Fail())
214     return error;
215   auto baton_sp =
216       std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
217   bp_options->SetCallback(ScriptInterpreterLua::BreakpointCallbackFunction,
218                           baton_sp);
219   return error;
220 }
221 
222 lldb::ScriptInterpreterSP
223 ScriptInterpreterLua::CreateInstance(Debugger &debugger) {
224   return std::make_shared<ScriptInterpreterLua>(debugger);
225 }
226 
227 lldb_private::ConstString ScriptInterpreterLua::GetPluginNameStatic() {
228   static ConstString g_name("script-lua");
229   return g_name;
230 }
231 
232 const char *ScriptInterpreterLua::GetPluginDescriptionStatic() {
233   return "Lua script interpreter";
234 }
235 
236 lldb_private::ConstString ScriptInterpreterLua::GetPluginName() {
237   return GetPluginNameStatic();
238 }
239 
240 uint32_t ScriptInterpreterLua::GetPluginVersion() { return 1; }
241 
242 Lua &ScriptInterpreterLua::GetLua() { return *m_lua; }
243