Skip to content

Commit

Permalink
[LLDB-lua] modify Lua's 'print' to respect 'io.stdout'
Browse files Browse the repository at this point in the history
This patch changes the implementation of Lua's `print()` function to
respect `io.stdout`.

The original implementation uses `lua_writestring()` internally, which is
hardcoded to `stdout`.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D90787
  • Loading branch information
tammela committed Nov 5, 2020
1 parent e551578 commit ca17571
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 10 deletions.
28 changes: 28 additions & 0 deletions lldb/source/Plugins/ScriptInterpreter/Lua/Lua.cpp
Expand Up @@ -14,6 +14,34 @@
using namespace lldb_private;
using namespace lldb;

static int lldb_print(lua_State *L) {
int n = lua_gettop(L);
lua_getglobal(L, "io");
lua_getfield(L, -1, "stdout");
lua_getfield(L, -1, "write");
for (int i = 1; i <= n; i++) {
lua_pushvalue(L, -1); // write()
lua_pushvalue(L, -3); // io.stdout
luaL_tolstring(L, i, nullptr);
lua_pushstring(L, i != n ? "\t" : "\n");
lua_call(L, 3, 0);
}
return 0;
}

Lua::Lua() : m_lua_state(luaL_newstate()) {
assert(m_lua_state);
luaL_openlibs(m_lua_state);
luaopen_lldb(m_lua_state);
lua_pushcfunction(m_lua_state, lldb_print);
lua_setglobal(m_lua_state, "print");
}

Lua::~Lua() {
assert(m_lua_state);
lua_close(m_lua_state);
}

llvm::Error Lua::Run(llvm::StringRef buffer) {
int error =
luaL_loadbuffer(m_lua_state, buffer.data(), buffer.size(), "buffer") ||
Expand Down
12 changes: 2 additions & 10 deletions lldb/source/Plugins/ScriptInterpreter/Lua/Lua.h
Expand Up @@ -25,16 +25,8 @@ int luaopen_lldb(lua_State *L);

class Lua {
public:
Lua() : m_lua_state(luaL_newstate()) {
assert(m_lua_state);
luaL_openlibs(m_lua_state);
luaopen_lldb(m_lua_state);
}

~Lua() {
assert(m_lua_state);
lua_close(m_lua_state);
}
Lua();
~Lua();

llvm::Error Run(llvm::StringRef buffer);
llvm::Error LoadModule(llvm::StringRef filename);
Expand Down
23 changes: 23 additions & 0 deletions lldb/test/Shell/ScriptInterpreter/Lua/print.test
@@ -0,0 +1,23 @@
# REQUIRES: lua
# UNSUPPORTED: lldb-repro
#
# RUN: rm -rf %t.stderr %t.stdout
# RUN: cat %s | %lldb --script-language lua 2> %t.stderr > %t.stdout
# RUN: cat %t.stdout | FileCheck %s --check-prefix STDOUT
# RUN: cat %t.stderr | FileCheck %s --check-prefix STDERR
script
file = lldb.SBFile(2, "w", false)
lldb.debugger:SetOutputFile(file)
print(95000 + 126, nil, 'a')
quit
script
print({})
quit

# STDOUT: 95126 nil a
# STDOUT-NOT: table: {{0x[[:xdigit:]]+}}
# STDERR: table: {{0x[[:xdigit:]]+}}

# RUN: rm -rf %t.stderr %t.stdout
# RUN: %lldb --script-language lua -o 'script print(95000 + 126, nil, "a")' 2> %t.stderr > %t.stdout
# RUN: cat %t.stdout | FileCheck %s --check-prefix STDOUT

0 comments on commit ca17571

Please sign in to comment.