1 //===-- ScriptInterpreterLua.cpp --------------------------------*- C++ -*-===//
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/Core/Debugger.h"
12 #include "lldb/Core/PluginManager.h"
13 #include "lldb/Core/StreamFile.h"
14 #include "lldb/Interpreter/CommandReturnObject.h"
15 #include "lldb/Utility/Stream.h"
16 #include "lldb/Utility/StringList.h"
17 #include "lldb/Utility/Timer.h"
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 
22 class IOHandlerLuaInterpreter : public IOHandlerDelegate,
23                                 public IOHandlerEditline {
24 public:
25   IOHandlerLuaInterpreter(Debugger &debugger,
26                           ScriptInterpreterLua &script_interpreter)
27       : IOHandlerEditline(debugger, IOHandler::Type::LuaInterpreter, "lua",
28                           ">>> ", "..> ", true, debugger.GetUseColor(), 0,
29                           *this, nullptr),
30         m_script_interpreter(script_interpreter) {
31     llvm::cantFail(m_script_interpreter.EnterSession(debugger.GetID()));
32   }
33 
34   ~IOHandlerLuaInterpreter() {
35     llvm::cantFail(m_script_interpreter.LeaveSession());
36   }
37 
38   void IOHandlerInputComplete(IOHandler &io_handler,
39                               std::string &data) override {
40     if (llvm::Error error = m_script_interpreter.GetLua().Run(data)) {
41       *GetOutputStreamFileSP() << llvm::toString(std::move(error));
42     }
43   }
44 
45 private:
46   ScriptInterpreterLua &m_script_interpreter;
47 };
48 
49 ScriptInterpreterLua::ScriptInterpreterLua(Debugger &debugger)
50     : ScriptInterpreter(debugger, eScriptLanguageLua),
51       m_lua(std::make_unique<Lua>()) {}
52 
53 ScriptInterpreterLua::~ScriptInterpreterLua() {}
54 
55 bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command,
56                                           CommandReturnObject *result,
57                                           const ExecuteScriptOptions &options) {
58   if (llvm::Error e = m_lua->Run(command)) {
59     result->AppendErrorWithFormatv(
60         "lua failed attempting to evaluate '{0}': {1}\n", command,
61         llvm::toString(std::move(e)));
62     return false;
63   }
64   return true;
65 }
66 
67 void ScriptInterpreterLua::ExecuteInterpreterLoop() {
68   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
69   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
70 
71   Debugger &debugger = m_debugger;
72 
73   // At the moment, the only time the debugger does not have an input file
74   // handle is when this is called directly from lua, in which case it is
75   // both dangerous and unnecessary (not to mention confusing) to try to embed
76   // a running interpreter loop inside the already running lua interpreter
77   // loop, so we won't do it.
78 
79   if (!debugger.GetInputFile().IsValid())
80     return;
81 
82   IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(debugger, *this));
83   debugger.PushIOHandler(io_handler_sp);
84 }
85 
86 void ScriptInterpreterLua::Initialize() {
87   static llvm::once_flag g_once_flag;
88 
89   llvm::call_once(g_once_flag, []() {
90     PluginManager::RegisterPlugin(GetPluginNameStatic(),
91                                   GetPluginDescriptionStatic(),
92                                   lldb::eScriptLanguageLua, CreateInstance);
93   });
94 }
95 
96 void ScriptInterpreterLua::Terminate() {}
97 
98 llvm::Error ScriptInterpreterLua::EnterSession(user_id_t debugger_id) {
99   if (m_session_is_active)
100     return llvm::Error::success();
101 
102   const char *fmt_str =
103       "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); "
104       "lldb.target = lldb.debugger:GetSelectedTarget(); "
105       "lldb.process = lldb.target:GetProcess(); "
106       "lldb.thread = lldb.process:GetSelectedThread(); "
107       "lldb.frame = lldb.thread:GetSelectedFrame()";
108   return m_lua->Run(llvm::formatv(fmt_str, debugger_id).str());
109 }
110 
111 llvm::Error ScriptInterpreterLua::LeaveSession() {
112   if (!m_session_is_active)
113     return llvm::Error::success();
114 
115   m_session_is_active = false;
116 
117   llvm::StringRef str = "lldb.debugger = nil; "
118                         "lldb.target = nil; "
119                         "lldb.process = nil; "
120                         "lldb.thread = nil; "
121                         "lldb.frame = nil";
122   return m_lua->Run(str);
123 }
124 
125 lldb::ScriptInterpreterSP
126 ScriptInterpreterLua::CreateInstance(Debugger &debugger) {
127   return std::make_shared<ScriptInterpreterLua>(debugger);
128 }
129 
130 lldb_private::ConstString ScriptInterpreterLua::GetPluginNameStatic() {
131   static ConstString g_name("script-lua");
132   return g_name;
133 }
134 
135 const char *ScriptInterpreterLua::GetPluginDescriptionStatic() {
136   return "Lua script interpreter";
137 }
138 
139 lldb_private::ConstString ScriptInterpreterLua::GetPluginName() {
140   return GetPluginNameStatic();
141 }
142 
143 uint32_t ScriptInterpreterLua::GetPluginVersion() { return 1; }
144 
145 Lua &ScriptInterpreterLua::GetLua() { return *m_lua; }
146