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 "Lua.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.GetLua().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.GetLua().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 Status error = m_script_interpreter.SetBreakpointCommandCallback(
120 bp_options, data.c_str(), /*is_callback=*/false);
121 if (error.Fail()) {
122 LockedStreamFile locked_stream =
123 io_handler.GetErrorStreamFileSP()->Lock();
124 locked_stream << error.AsCString() << '\n';
125 }
126 }
127 io_handler.SetIsDone(true);
128 } break;
130 auto *wp_options =
131 static_cast<WatchpointOptions *>(io_handler.GetUserData());
132 m_script_interpreter.SetWatchpointCommandCallback(wp_options,
133 data.c_str(),
134 /*is_callback=*/false);
135 io_handler.SetIsDone(true);
136 } break;
137 case eIOHandlerNone:
138 if (IsQuitCommand(data)) {
139 io_handler.SetIsDone(true);
140 return;
141 }
142 if (llvm::Error error = m_script_interpreter.GetLua().Run(data)) {
143 LockedStreamFile locked_stream =
144 io_handler.GetErrorStreamFileSP()->Lock();
145 locked_stream << toString(std::move(error));
146 }
147 break;
148 }
149 }
150
151private:
154
155 bool IsQuitCommand(llvm::StringRef cmd) { return cmd.rtrim() == "quit"; }
156};
157
161
163
165 auto info = std::make_shared<StructuredData::Dictionary>();
166 info->AddStringItem("language", "lua");
167 return info;
168}
169
170bool ScriptInterpreterLua::ExecuteOneLine(llvm::StringRef command,
171 CommandReturnObject *result,
172 const ExecuteScriptOptions &options) {
173 if (command.empty()) {
174 if (result)
175 result->AppendError("empty command passed to lua\n");
176 return false;
177 }
178
179 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
180 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
181 options.GetEnableIO(), m_debugger, result);
182 if (!io_redirect_or_error) {
183 if (result)
185 "failed to redirect I/O: {0}\n",
186 llvm::fmt_consume(io_redirect_or_error.takeError()));
187 else
188 llvm::consumeError(io_redirect_or_error.takeError());
189 return false;
190 }
191
192 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
193
194 if (llvm::Error e =
195 m_lua->ChangeIO(io_redirect.GetOutputFile()->GetStream(),
196 io_redirect.GetErrorFile()->GetStream())) {
197 result->AppendErrorWithFormatv("lua failed to redirect I/O: {0}\n",
198 llvm::toString(std::move(e)));
199 return false;
200 }
201
202 if (llvm::Error e = m_lua->Run(command)) {
204 "lua failed attempting to evaluate '{0}': {1}\n", command,
205 llvm::toString(std::move(e)));
206 return false;
207 }
208
209 io_redirect.Flush();
210 return true;
211}
212
215
216 // At the moment, the only time the debugger does not have an input file
217 // handle is when this is called directly from lua, in which case it is
218 // both dangerous and unnecessary (not to mention confusing) to try to embed
219 // a running interpreter loop inside the already running lua interpreter
220 // loop, so we won't do it.
221 if (!m_debugger.GetInputFile().IsValid())
222 return;
223
224 IOHandlerSP io_handler_sp(new IOHandlerLuaInterpreter(m_debugger, *this));
225 m_debugger.RunIOHandlerAsync(io_handler_sp);
226}
227
229 const char *filename, const LoadScriptOptions &options,
231 FileSpec extra_search_dir, lldb::TargetSP loaded_into_target_sp) {
232
233 if (llvm::Error e = m_lua->LoadModule(filename)) {
235 "lua failed to import '{0}': {1}\n", filename,
236 llvm::toString(std::move(e)));
237 return false;
238 }
239 return true;
240}
241
243 static llvm::once_flag g_once_flag;
244
245 llvm::call_once(g_once_flag, []() {
249 });
250}
251
253
256 return llvm::Error::success();
257
258 const char *fmt_str =
259 "lldb.debugger = lldb.SBDebugger.FindDebuggerWithID({0}); "
260 "lldb.target = lldb.debugger:GetSelectedTarget(); "
261 "lldb.process = lldb.target:GetProcess(); "
262 "lldb.thread = lldb.process:GetSelectedThread(); "
263 "lldb.frame = lldb.thread:GetSelectedFrame()";
264 return m_lua->Run(llvm::formatv(fmt_str, debugger_id).str());
265}
266
269 return llvm::Error::success();
270
271 m_session_is_active = false;
272
273 llvm::StringRef str = "lldb.debugger = nil; "
274 "lldb.target = nil; "
275 "lldb.process = nil; "
276 "lldb.thread = nil; "
277 "lldb.frame = nil";
278 return m_lua->Run(str);
279}
280
282 void *baton, StoppointCallbackContext *context, user_id_t break_id,
283 user_id_t break_loc_id) {
284 assert(context);
285
286 ExecutionContext exe_ctx(context->exe_ctx_ref);
287 Target *target = exe_ctx.GetTargetPtr();
288 if (target == nullptr)
289 return true;
290
291 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
292 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
293 BreakpointLocationSP bp_loc_sp(breakpoint_sp->FindLocationByID(break_loc_id));
294
295 Debugger &debugger = target->GetDebugger();
296 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
298 Lua &lua = lua_interpreter->GetLua();
299
300 CommandDataLua *bp_option_data = static_cast<CommandDataLua *>(baton);
301 llvm::Expected<bool> BoolOrErr = lua.CallBreakpointCallback(
302 baton, stop_frame_sp, bp_loc_sp, bp_option_data->m_extra_args_sp);
303 if (llvm::Error E = BoolOrErr.takeError()) {
304 *debugger.GetAsyncErrorStream() << toString(std::move(E));
305 return true;
306 }
307
308 return *BoolOrErr;
309}
310
312 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
313 assert(context);
314
315 ExecutionContext exe_ctx(context->exe_ctx_ref);
316 Target *target = exe_ctx.GetTargetPtr();
317 if (target == nullptr)
318 return true;
319
320 StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
321 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
322
323 Debugger &debugger = target->GetDebugger();
324 ScriptInterpreterLua *lua_interpreter = static_cast<ScriptInterpreterLua *>(
326 Lua &lua = lua_interpreter->GetLua();
327
328 llvm::Expected<bool> BoolOrErr =
329 lua.CallWatchpointCallback(baton, stop_frame_sp, wp_sp);
330 if (llvm::Error E = BoolOrErr.takeError()) {
331 *debugger.GetAsyncErrorStream() << toString(std::move(E));
332 return true;
333 }
334
335 return *BoolOrErr;
336}
337
339 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
340 CommandReturnObject &result) {
341 IOHandlerSP io_handler_sp(
343 io_handler_sp->SetUserData(&bp_options_vec);
344 m_debugger.RunIOHandlerAsync(io_handler_sp);
345}
346
348 WatchpointOptions *wp_options, CommandReturnObject &result) {
349 IOHandlerSP io_handler_sp(
351 io_handler_sp->SetUserData(wp_options);
352 m_debugger.RunIOHandlerAsync(io_handler_sp);
353}
354
356 BreakpointOptions &bp_options, const char *function_name,
357 StructuredData::ObjectSP extra_args_sp) {
358 const char *fmt_str = "return {0}(frame, bp_loc, ...)";
359 std::string oneliner = llvm::formatv(fmt_str, function_name).str();
360 return RegisterBreakpointCallback(bp_options, oneliner.c_str(),
361 extra_args_sp);
362}
363
365 BreakpointOptions &bp_options, const char *command_body_text,
366 bool is_callback) {
367 return RegisterBreakpointCallback(bp_options, command_body_text, {});
368}
369
371 BreakpointOptions &bp_options, const char *command_body_text,
372 StructuredData::ObjectSP extra_args_sp) {
373 auto data_up = std::make_unique<CommandDataLua>(extra_args_sp);
374 llvm::Error err =
375 m_lua->RegisterBreakpointCallback(data_up.get(), command_body_text);
376 if (err)
377 return Status::FromError(std::move(err));
378 auto baton_sp =
379 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
381 baton_sp);
382 return {};
383}
384
386 WatchpointOptions *wp_options, const char *command_body_text,
387 bool is_callback) {
388 RegisterWatchpointCallback(wp_options, command_body_text, {});
389}
390
392 WatchpointOptions *wp_options, const char *command_body_text,
393 StructuredData::ObjectSP extra_args_sp) {
394 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
395 llvm::Error err =
396 m_lua->RegisterWatchpointCallback(data_up.get(), command_body_text);
397 if (err)
398 return Status::FromError(std::move(err));
399 auto baton_sp =
400 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
402 baton_sp);
403 return {};
404}
405
408 return std::make_shared<ScriptInterpreterLua>(debugger);
409}
410
412 return "Lua script interpreter";
413}
414
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_PLUGIN_DEFINE(PluginName)
@ eIOHandlerWatchpoint
@ eIOHandlerBreakpoint
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
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 void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormatv(const char *format, Args &&...args)
A class to manage flag bits.
Definition Debugger.h:80
lldb::StreamUP GetAsyncErrorStream()
lldb::FileSP GetErrorFileSP()
Definition Debugger.h:143
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:139
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:57
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
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, 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.
Status SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
llvm::Error EnterSession(lldb::user_id_t debugger_id)
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger)
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
Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *command_body_text, bool is_callback) override
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *command_body_text, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
Status RegisterBreakpointCallback(BreakpointOptions &bp_options, const char *command_body_text, StructuredData::ObjectSP extra_args_sp)
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:137
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:414
Debugger & GetDebugger() const
Definition Target.h:1097
WatchpointList & GetWatchpointList()
Definition Target.h:807
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.
const char * toString(AppleArm64ExceptionClass EC)
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:82
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