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: 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 53 ~IOHandlerLuaInterpreter() override { 54 llvm::cantFail(m_script_interpreter.LeaveSession()); 55 } 56 57 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { 58 const char *instructions = nullptr; 59 switch (m_active_io_handler) { 60 case eIOHandlerNone: 61 break; 62 case eIOHandlerWatchpoint: 63 instructions = "Enter your Lua command(s). Type 'quit' to end.\n" 64 "The commands are compiled as the body of the following " 65 "Lua function\n" 66 "function (frame, wp) end\n"; 67 SetPrompt(llvm::StringRef("..> ")); 68 break; 69 case eIOHandlerBreakpoint: 70 instructions = "Enter your Lua command(s). Type 'quit' to end.\n" 71 "The commands are compiled as the body of the following " 72 "Lua function\n" 73 "function (frame, bp_loc, ...) end\n"; 74 SetPrompt(llvm::StringRef("..> ")); 75 break; 76 } 77 if (instructions == nullptr) 78 return; 79 if (interactive) 80 *io_handler.GetOutputStreamFileSP() << instructions; 81 } 82 83 bool IOHandlerIsInputComplete(IOHandler &io_handler, 84 StringList &lines) override { 85 size_t last = lines.GetSize() - 1; 86 if (IsQuitCommand(lines.GetStringAtIndex(last))) { 87 if (m_active_io_handler == eIOHandlerBreakpoint || 88 m_active_io_handler == eIOHandlerWatchpoint) 89 lines.DeleteStringAtIndex(last); 90 return true; 91 } 92 StreamString str; 93 lines.Join("\n", str); 94 if (llvm::Error E = 95 m_script_interpreter.GetLua().CheckSyntax(str.GetString())) { 96 std::string error_str = toString(std::move(E)); 97 // Lua always errors out to incomplete code with '<eof>' 98 return error_str.find("<eof>") == std::string::npos; 99 } 100 // The breakpoint and watchpoint handler only exits with a explicit 'quit' 101 return m_active_io_handler != eIOHandlerBreakpoint && 102 m_active_io_handler != eIOHandlerWatchpoint; 103 } 104 105 void IOHandlerInputComplete(IOHandler &io_handler, 106 std::string &data) override { 107 switch (m_active_io_handler) { 108 case eIOHandlerBreakpoint: { 109 auto *bp_options_vec = 110 static_cast<std::vector<std::reference_wrapper<BreakpointOptions>> *>( 111 io_handler.GetUserData()); 112 for (BreakpointOptions &bp_options : *bp_options_vec) { 113 Status error = m_script_interpreter.SetBreakpointCommandCallback( 114 bp_options, data.c_str()); 115 if (error.Fail()) 116 *io_handler.GetErrorStreamFileSP() << error.AsCString() << '\n'; 117 } 118 io_handler.SetIsDone(true); 119 } break; 120 case eIOHandlerWatchpoint: { 121 auto *wp_options = 122 static_cast<WatchpointOptions *>(io_handler.GetUserData()); 123 m_script_interpreter.SetWatchpointCommandCallback(wp_options, 124 data.c_str()); 125 io_handler.SetIsDone(true); 126 } break; 127 case eIOHandlerNone: 128 if (IsQuitCommand(data)) { 129 io_handler.SetIsDone(true); 130 return; 131 } 132 if (llvm::Error error = m_script_interpreter.GetLua().Run(data)) 133 *io_handler.GetErrorStreamFileSP() << toString(std::move(error)); 134 break; 135 } 136 } 137 138 private: 139 ScriptInterpreterLua &m_script_interpreter; 140 ActiveIOHandler m_active_io_handler; 141 142 bool IsQuitCommand(llvm::StringRef cmd) { return cmd.rtrim() == "quit"; } 143 }; 144 145 ScriptInterpreterLua::ScriptInterpreterLua(Debugger &debugger) 146 : ScriptInterpreter(debugger, eScriptLanguageLua), 147 m_lua(std::make_unique<Lua>()) {} 148 149 ScriptInterpreterLua::~ScriptInterpreterLua() = default; 150 151 bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command, 152 CommandReturnObject *result, 153 const ExecuteScriptOptions &options) { 154 if (command.empty()) { 155 if (result) 156 result->AppendError("empty command passed to lua\n"); 157 return false; 158 } 159 160 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 161 io_redirect_or_error = ScriptInterpreterIORedirect::Create( 162 options.GetEnableIO(), m_debugger, result); 163 if (!io_redirect_or_error) { 164 if (result) 165 result->AppendErrorWithFormatv( 166 "failed to redirect I/O: {0}\n", 167 llvm::fmt_consume(io_redirect_or_error.takeError())); 168 else 169 llvm::consumeError(io_redirect_or_error.takeError()); 170 return false; 171 } 172 173 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 174 175 if (llvm::Error e = 176 m_lua->ChangeIO(io_redirect.GetOutputFile()->GetStream(), 177 io_redirect.GetErrorFile()->GetStream())) { 178 result->AppendErrorWithFormatv("lua failed to redirect I/O: {0}\n", 179 llvm::toString(std::move(e))); 180 return false; 181 } 182 183 if (llvm::Error e = m_lua->Run(command)) { 184 result->AppendErrorWithFormatv( 185 "lua failed attempting to evaluate '{0}': {1}\n", command, 186 llvm::toString(std::move(e))); 187 return false; 188 } 189 190 io_redirect.Flush(); 191 return true; 192 } 193 194 void ScriptInterpreterLua::ExecuteInterpreterLoop() { 195 LLDB_SCOPED_TIMER(); 196 197 // At the moment, the only time the debugger does not have an input file 198 // handle is when this is called directly from lua, in which case it is 199 // both dangerous and unnecessary (not to mention confusing) to try to embed 200 // a running interpreter loop inside the already running lua interpreter 201 // loop, so we won't do it. 202 if (!m_debugger.GetInputFile().IsValid()) 203 return; 204 205 IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(m_debugger, *this)); 206 m_debugger.RunIOHandlerAsync(io_handler_sp); 207 } 208 209 bool ScriptInterpreterLua::LoadScriptingModule( 210 const char *filename, bool init_session, lldb_private::Status &error, 211 StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) { 212 213 FileSystem::Instance().Collect(filename); 214 if (llvm::Error e = m_lua->LoadModule(filename)) { 215 error.SetErrorStringWithFormatv("lua failed to import '{0}': {1}\n", 216 filename, llvm::toString(std::move(e))); 217 return false; 218 } 219 return true; 220 } 221 222 void ScriptInterpreterLua::Initialize() { 223 static llvm::once_flag g_once_flag; 224 225 llvm::call_once(g_once_flag, []() { 226 PluginManager::RegisterPlugin(GetPluginNameStatic(), 227 GetPluginDescriptionStatic(), 228 lldb::eScriptLanguageLua, CreateInstance); 229 }); 230 } 231 232 void ScriptInterpreterLua::Terminate() {} 233 234 llvm::Error ScriptInterpreterLua::EnterSession(user_id_t debugger_id) { 235 if (m_session_is_active) 236 return llvm::Error::success(); 237 238 const char *fmt_str = 239 "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); " 240 "lldb.target = lldb.debugger:GetSelectedTarget(); " 241 "lldb.process = lldb.target:GetProcess(); " 242 "lldb.thread = lldb.process:GetSelectedThread(); " 243 "lldb.frame = lldb.thread:GetSelectedFrame()"; 244 return m_lua->Run(llvm::formatv(fmt_str, debugger_id).str()); 245 } 246 247 llvm::Error ScriptInterpreterLua::LeaveSession() { 248 if (!m_session_is_active) 249 return llvm::Error::success(); 250 251 m_session_is_active = false; 252 253 llvm::StringRef str = "lldb.debugger = nil; " 254 "lldb.target = nil; " 255 "lldb.process = nil; " 256 "lldb.thread = nil; " 257 "lldb.frame = nil"; 258 return m_lua->Run(str); 259 } 260 261 bool ScriptInterpreterLua::BreakpointCallbackFunction( 262 void *baton, StoppointCallbackContext *context, user_id_t break_id, 263 user_id_t break_loc_id) { 264 assert(context); 265 266 ExecutionContext exe_ctx(context->exe_ctx_ref); 267 Target *target = exe_ctx.GetTargetPtr(); 268 if (target == nullptr) 269 return true; 270 271 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 272 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 273 BreakpointLocationSP bp_loc_sp(breakpoint_sp->FindLocationByID(break_loc_id)); 274 275 Debugger &debugger = target->GetDebugger(); 276 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>( 277 debugger.GetScriptInterpreter(true, eScriptLanguageLua)); 278 Lua &lua = lua_interpreter->GetLua(); 279 280 CommandDataLua *bp_option_data = static_cast<CommandDataLua *>(baton); 281 llvm::Expected<bool> BoolOrErr = lua.CallBreakpointCallback( 282 baton, stop_frame_sp, bp_loc_sp, bp_option_data->m_extra_args_sp); 283 if (llvm::Error E = BoolOrErr.takeError()) { 284 debugger.GetErrorStream() << toString(std::move(E)); 285 return true; 286 } 287 288 return *BoolOrErr; 289 } 290 291 bool ScriptInterpreterLua::WatchpointCallbackFunction( 292 void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 293 assert(context); 294 295 ExecutionContext exe_ctx(context->exe_ctx_ref); 296 Target *target = exe_ctx.GetTargetPtr(); 297 if (target == nullptr) 298 return true; 299 300 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 301 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 302 303 Debugger &debugger = target->GetDebugger(); 304 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>( 305 debugger.GetScriptInterpreter(true, eScriptLanguageLua)); 306 Lua &lua = lua_interpreter->GetLua(); 307 308 llvm::Expected<bool> BoolOrErr = 309 lua.CallWatchpointCallback(baton, stop_frame_sp, wp_sp); 310 if (llvm::Error E = BoolOrErr.takeError()) { 311 debugger.GetErrorStream() << toString(std::move(E)); 312 return true; 313 } 314 315 return *BoolOrErr; 316 } 317 318 void ScriptInterpreterLua::CollectDataForBreakpointCommandCallback( 319 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, 320 CommandReturnObject &result) { 321 IOHandlerSP io_handler_sp( 322 new IOHandlerLuaInterpreter(m_debugger, *this, eIOHandlerBreakpoint)); 323 io_handler_sp->SetUserData(&bp_options_vec); 324 m_debugger.RunIOHandlerAsync(io_handler_sp); 325 } 326 327 void ScriptInterpreterLua::CollectDataForWatchpointCommandCallback( 328 WatchpointOptions *wp_options, CommandReturnObject &result) { 329 IOHandlerSP io_handler_sp( 330 new IOHandlerLuaInterpreter(m_debugger, *this, eIOHandlerWatchpoint)); 331 io_handler_sp->SetUserData(wp_options); 332 m_debugger.RunIOHandlerAsync(io_handler_sp); 333 } 334 335 Status ScriptInterpreterLua::SetBreakpointCommandCallbackFunction( 336 BreakpointOptions &bp_options, const char *function_name, 337 StructuredData::ObjectSP extra_args_sp) { 338 const char *fmt_str = "return {0}(frame, bp_loc, ...)"; 339 std::string oneliner = llvm::formatv(fmt_str, function_name).str(); 340 return RegisterBreakpointCallback(bp_options, oneliner.c_str(), 341 extra_args_sp); 342 } 343 344 Status ScriptInterpreterLua::SetBreakpointCommandCallback( 345 BreakpointOptions &bp_options, const char *command_body_text) { 346 return RegisterBreakpointCallback(bp_options, command_body_text, {}); 347 } 348 349 Status ScriptInterpreterLua::RegisterBreakpointCallback( 350 BreakpointOptions &bp_options, const char *command_body_text, 351 StructuredData::ObjectSP extra_args_sp) { 352 Status error; 353 auto data_up = std::make_unique<CommandDataLua>(extra_args_sp); 354 error = m_lua->RegisterBreakpointCallback(data_up.get(), command_body_text); 355 if (error.Fail()) 356 return error; 357 auto baton_sp = 358 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 359 bp_options.SetCallback(ScriptInterpreterLua::BreakpointCallbackFunction, 360 baton_sp); 361 return error; 362 } 363 364 void ScriptInterpreterLua::SetWatchpointCommandCallback( 365 WatchpointOptions *wp_options, const char *command_body_text) { 366 RegisterWatchpointCallback(wp_options, command_body_text, {}); 367 } 368 369 Status ScriptInterpreterLua::RegisterWatchpointCallback( 370 WatchpointOptions *wp_options, const char *command_body_text, 371 StructuredData::ObjectSP extra_args_sp) { 372 Status error; 373 auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 374 error = m_lua->RegisterWatchpointCallback(data_up.get(), command_body_text); 375 if (error.Fail()) 376 return error; 377 auto baton_sp = 378 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 379 wp_options->SetCallback(ScriptInterpreterLua::WatchpointCallbackFunction, 380 baton_sp); 381 return error; 382 } 383 384 lldb::ScriptInterpreterSP 385 ScriptInterpreterLua::CreateInstance(Debugger &debugger) { 386 return std::make_shared<ScriptInterpreterLua>(debugger); 387 } 388 389 lldb_private::ConstString ScriptInterpreterLua::GetPluginNameStatic() { 390 static ConstString g_name("script-lua"); 391 return g_name; 392 } 393 394 const char *ScriptInterpreterLua::GetPluginDescriptionStatic() { 395 return "Lua script interpreter"; 396 } 397 398 lldb_private::ConstString ScriptInterpreterLua::GetPluginName() { 399 return GetPluginNameStatic(); 400 } 401 402 uint32_t ScriptInterpreterLua::GetPluginVersion() { return 1; } 403 404 Lua &ScriptInterpreterLua::GetLua() { return *m_lua; } 405