Multiple Lua environments issue - c++

I'm having trouble on creating multiple Lua environments to run multiple similar scripts in the same lua_State.
The program crashes with the following error
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
Here's the Script.Compile and Script.runFunc methods:
void Script::Compile() {
if (m_filename.IsEmpty()) return;
if (m_filename.Contains("res:")) {
astd::String file = m_filename.Replace("res:", "");
astd::String filecontent = AEIO::OpenTextFromAssetPack(file);
m_lua->RunString(filecontent);
} else {
m_lua->RunScript(m_filename);
}
astd::String id = astd::String("file") + astd::String(UID);
lua_setfield(m_lua->State(), LUA_REGISTRYINDEX, id.CStr());
UID++;
}
void Script::runFunc(astd::String func) {
astd::String id = astd::String("file") + astd::String(UID);
lua_State* state = m_lua->State();
// Weird behaviour during debug.
// The debugger goes back and forth on these 2 lines.
lua_getfield(state, LUA_REGISTRYINDEX, id.CStr());
lua_getfield(state, -1, func.CStr()); // CRASH!
if (lua_isfunction(state, -1)) {
lua_pcall(state, 0, 0, 0);
}
luabind::globals(state)["self"] = m_owner;
}
And this is the basic structure of the scripts:
print("Script Created") --Gets printed before the error occurs.
function onInit()
print("Script Initialized")
end
function onUpdate()
print("Script Update")
end
And it only fails when I call runFunc("onInit") or runFunc("onUpdate").
Thanks in advance.

Related

Lua 5.2 Sandboxing in different objects with C API

Consider the following C++ code using the Lua C API:
#include <string>
#include <cassert>
#include <lua/lua.hpp>
class AwesomeThing
{
lua_State* _lua;
std::string _name;
public:
AwesomeThing(lua_State* L, const std::string& name, const std::string& luafile)
: _lua{ L },
_name{ name }
{
assert(luaL_loadfile(_lua, luafile.c_str()) == 0); // 1:chunk
lua_newtable(_lua); // 1:chunk, 2:tbl
lua_newtable(_lua); // 1:chunk, 2:tbl, 3:tbl(mt)
lua_getglobal(_lua, "_G"); // 1:chunk, 2: tbl, 3:tbl(mt), 4:_G
lua_setfield(_lua, 3, "__index"); // 1:chunk, 2: tbl, 3:tbl(mt)
lua_setmetatable(_lua, 2); // 1:chunk, 2: tbl
lua_setupvalue(_lua, -2, 1); // 1:chunk
if (lua_pcall(_lua, 0, 0, 0) != 0) // compiled chunk
{
auto error = lua_tostring(_lua, -1);
throw std::runtime_error(error);
}
lua_setglobal(_lua, _name.c_str()); // empty stack
}
void init()
{
lua_getglobal(_lua, _name.c_str()); // 1:env
assert(lua_isnil(_lua, 1) == 0);
lua_getfield(_lua, 1, "onInit"); // 1:env, 2:func
assert(lua_isnil(_lua, 2) == 0);
assert(lua_isfunction(_lua, 2) == 1);
assert(lua_pcall(_lua, 0, LUA_MULTRET, 0) == 0); // 1:env, 2:retval
lua_pop(_lua, 1); // -1:env
lua_pop(_lua, 1); // empty stack
assert(lua_gettop(_lua) == 0);
}
};
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
AwesomeThing at1(L, "thing1", "file1.lua");
AwesomeThing at2(L, "thing2", "file2.lua");
at1.init();
at2.init();
return 0;
}
With two very basic Lua files:
file1.lua
function onInit()
print("init file1")
end
file2.lua
function onInit()
print("init file2")
end
As is, I get an error in at2's constructor call at lua_pcall: attempt to call table value
When I comment out all references/calls to at2, I instead get an error in at1's init() at lua_getfield(_lua, 1, "onInit"): PANIC: unprotected error in call to Lua API (attempt to index a nil value)
I feel like there's something fundamental I'm missing in the way I'm handling the sandboxing. I've tried my best to follow a few other Lua 5.2 sandboxing examples I've found online, but so far nothing has helped.
After messing around with the code myself, I was able to fix it and the errors seem to come from just a few errors.
lua_pcall pops the called function from the stack, but in both cases in your code you assume the function is still on the stack after lua_pcall. This results in bad stack manipulation.
In the constructor, you apparently try to store a reference to the chunk (function) instead of the environment table. This doesn't even work though, because the function was already popped. If it did work, the lua_getfield call in init() wouldn't work as intended since the chunk doesn't have a field named onInit -- the environment table does.
Fixing the constructor involves creating the environment table and loading the chunk in the opposite order, so that the environment table is left on the stack after the function call:
lua_newtable(_lua); // 1:tbl
assert(luaL_loadfile(_lua, luafile.c_str()) == 0); // 1:tbl, 2:chunk
lua_newtable(_lua); // 1:tbl, 2:chunk, 3:tbl(mt)
lua_getglobal(_lua, "_G"); // 1:tbl, 2:chunk, 3:tbl(mt), 4:_G
lua_setfield(_lua, 3, "__index"); // 1:tbl, 2:chunk, 3:tbl(mt)
lua_setmetatable(_lua, 1); // 1:tbl, 2:chunk
lua_pushvalue(_lua, 1); // 1:tbl, 2:chunk, 3:tbl
lua_setupvalue(_lua, -2, 1); // 1:tbl, 2:chunk
if (lua_pcall(_lua, 0, 0, 0) != 0) // compiled chunk
{
auto error = lua_tostring(_lua, -1);
throw std::runtime_error(error);
}
// 1:tbl
lua_setglobal(_lua, _name.c_str()); // empty stack
Then in init(), since you use LUA_MULTRET, just clear the stack by replacing both pop calls with lua_settop(_lua, 0).

SetPerTcpConnectionEStats fails and can't get GetPerTcpConnectionEStats multiple times c++

I am following the example in https://learn.microsoft.com/en-gb/windows/win32/api/iphlpapi/nf-iphlpapi-getpertcp6connectionestats?redirectedfrom=MSDN to get the TCP statistics. Although, I got it working and get the statistics in the first place, still I want to record them every a time interval (which I haven't managed to do so), and I have the following questions.
The SetPerTcpConnectionEStats () fails with status != NO_ERROR and equal to 5. Although, it fails, I can get the statistics. Why?
I want to get the statistics every, let's say 1 second. I have tried two different ways; a) to use a while loop and use a std::this_thread::sleep_for(1s), where I could get the statistics every ~1sec, but the whole app was stalling (is it because of the this), I supposed that I am blocking the operation of the main, and b) (since a) failed) I tried to call TcpStatistics() from another function (in different class) that is triggered every 1 sec (I store clientConnectRow to a global var). However, in that case (b), GetPerTcpConnectionEStats() fails with winStatus = 1214 (ERROR_INVALID_NETNAME) and of course TcpStatistics() cannot get any of the statistics.
a)
ClassB::ClassB()
{
UINT winStatus = GetTcpRow(localPort, hostPort, MIB_TCP_STATE_ESTAB, (PMIB_TCPROW)clientConnectRow);
ToggleAllEstats(clientConnectRow, TRUE);
thread t1(&ClassB::TcpStatistics, this, clientConnectRow);
t1.join();
}
ClassB::TcpStatistics()
{
while (true)
{
GetAndOutputEstats(row, TcpConnectionEstatsBandwidth)
// some more code here
this_thread::sleep_for(milliseconds(1000));
}
}
b)
ClassB::ClassB()
{
MIB_TCPROW client4ConnectRow;
void* clientConnectRow = NULL;
clientConnectRow = &client4ConnectRow;
UINT winStatus = GetTcpRow(localPort, hostPort, MIB_TCP_STATE_ESTAB, (PMIB_TCPROW)clientConnectRow);
m_clientConnectRow = clientConnectRow;
TcpStatistics();
}
ClassB::TcpStatistics()
{
ToggleAllEstats(m_clientConnectRow , TRUE);
void* row = m_clientConnectRow;
GetAndOutputEstats(row, TcpConnectionEstatsBandwidth)
// some more code here
}
ClassB::GetAndOutputEstats(void* row, TCP_ESTATS_TYPE type)
{
//...
winStatus = GetPerTcpConnectionEStats((PMIB_TCPROW)row, type, NULL, 0, 0, ros, 0, rosSize, rod, 0, rodSize);
if (winStatus != NO_ERROR) {wprintf(L"\nGetPerTcpConnectionEStats %s failed. status = %d", estatsTypeNames[type], winStatus); //
}
else { ...}
}
ClassA::FunA()
{
classB_ptr->TcpStatistics();
}
I found a work around for the second part of my question. I am posting it here, in case someone else find it useful. There might be other solutions too, more advanced, but this is how I did it myself. We have to first Obtain MIB_TCPROW corresponding to the TCP connection and then to Enable Estats collection before dumping current stats. So, what I did was to add all of these in a function and call this instead, every time I want to get the stats.
void
ClassB::FunSetTcpStats()
{
MIB_TCPROW client4ConnectRow;
void* clientConnectRow = NULL;
clientConnectRow = &client4ConnectRow;
//this is for the statistics
UINT winStatus = GetTcpRow(lPort, hPort, MIB_TCP_STATE_ESTAB, (PMIB_TCPROW)clientConnectRow); //lPort & hPort in htons!
if (winStatus != ERROR_SUCCESS) {
wprintf(L"\nGetTcpRow failed on the client established connection with %d", winStatus);
return;
}
//
// Enable Estats collection and dump current stats.
//
ToggleAllEstats(clientConnectRow, TRUE);
TcpStatistics(clientConnectRow); // same as GetAllEstats() in msdn
}

sd-bus signal not calling cb function

I have one problem. In c++ app, I am using sd-bus and signal does not call my callback function.
I hooked to org.freedesktop.login1, interface is org.freedesktop.DBus.Properties, member is PropertiesChanged and path is /org/freedesktop/login1/seat/seat0
In my connect method I have this:
sd_bus_add_match(m_bus, NULL, "interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='/org/freedesktop/login1/seat/seat0',type='signal'", on_properties_changed, NULL)
On properties changed method is this:
static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
printf("got some signal");
}
So, when I ran this program, I also ran following command in cmd:ΒΈ
gdbus monitor --system --dest org.freedesktop.login1 --object-path /org/freedesktop/login1/seat/seat0
However, when I switch from userA to userB, I got following line in cmd window:
/org/freedesktop/login1/seat/seat0: org.freedesktop.DBus.Properties.PropertiesChanged ('org.freedesktop.login1.Seat', {'ActiveSession': <('c7', objectpath '/org/freedesktop/login1/session/c7')>}, #as [])
Also when I tried this
busctl --system --match "interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='/org/freedesktop/login1/seat/seat0',type='signal' monitor
then I also get proper response
Type=signal Endian=l Flags=1 Version=1 Priority=0 Cookie=2281
Sender=:1.0 Path=/org/freedesktop/login1/seat/seat0 Interface=org.freedesktop.DBus.Properties Member=PropertiesChanged
UniqueName=:1.0
MESSAGE "sa{sv}as" {
STRING "org.freedesktop.login1.Seat";
ARRAY "{sv}" {
DICT_ENTRY "sv" {
STRING "ActiveSession";
VARIANT "(so)" {
STRUCT "so" {
STRING "c2";
OBJECT_PATH "/org/freedesktop/login1/session/c2";
};
};
};
};
ARRAY "s" {
};
};
But in c++ that callback function is not called. Any idea why is it not called?
I am using Ubuntu 16.04 and my systemd version is 229.
I found a solution to this problem. Problem was that I wasn't hooked to any event loop.
So I created new function run() and in this function I say this:
while(m_running) {
sd_bus_message *m = NULL;
r = sd_bus_process(m_bus, &m);
if (r < 0) {
//error handling
}
r = sd_bus_wait(m_bus, (uint64_t)-1);
if (r < 0) {
//error handling
}
}
and now I call this function after I connect to signal, and callback function of sd_bus_add_match is normally called

Safe Lua invoke C++ registered function

Hey,everyone! I've a C++ app embedded Lua as script. A non-programmer edits the Lua script, then the C++ app invoke the Lua script and the Lua script also invokes C++ registered function.
I use Luaplus to do the above job. My question is: when the script-editor makes mistakes such as misspelling the the parameter, the C++ app crashes! What can I do to prevent this happening? thanks
Look at lua_cpcall and lua_pcall. They both allow protected function calls of lua in c. If they return a non-negative number then the call failed and the lua stack contains only the error string. In cpcalls case the stack is otherwise unmodified. For pcall you'll need to look at lua_pushcclosure to invoke a cfunction safely.
What you do is this: you create a c function with all of the lua_* calls you want, such as loadfile and dofile. You call this function using lua_cpcall or lua_pushcclosure amd lua_pcall. This allows you to detect if an error occured in t
he function you passed to cpcall.
Examples:
function hello() {
string hello_ = "Hello Lua!";
struct C {
static int call(lua_State* L) {
C *p = static_cast<C*>(lua_touserdata(L,-1));
lua_pushstring(L, p->str.c_str() );
lua_getglobal(L, "print");
lua_call(L, 1, 0); //ok
lua_pushstring(L, p->str.c_str() );
lua_getglobal(L, "notprint");
lua_call(L, 1, 0); //error -> longjmps
return 0; //Number of values on stack to 'return' to lua
}
const string& str;
} p = { hello_ };
//protected call of C::call() above
//with &p as 1st/only element on Lua stack
//any errors encountered will trigger a longjmp out of lua and
//return a non-0 error code and a string on the stack
//A return of 0 indicates success and the stack is unmodified
//to invoke LUA functions safely use the lua_pcall function
int res = lua_cpcall(L, &C::call, &p);
if( res ) {
string err = lua_tostring(L, -1);
lua_pop(L, 1);
//Error hanlder here
}
//load a .lua file
if( (res=luaL_loadfile(L, "myLuaFile.lua")) ) {
string err = lua_tostring(L, -1);
lua_pop(L, 1);
//res is one of
//LUA_ERRSYNTAX - Lua syntax error
//LUA_ERRMEM - Out of memory error
//LUE_ERRFILE - File not found/accessible error
}
//execute it
if( (res=lua_pcall(L,0,0,0)) ) {
string err = lua_tostring(L, -1);
lua_pop(L, 1);
// res is one of
// LUA_ERRRUN: a runtime error.
// LUA_ERRMEM: memory allocation error.
// LUA_ERRERR: error while running the error handler function (NULL in this case).
}
// try to call [a_int,b_str] = Foo(1,2,"3")
lua_getglobal(L,"Foo");
if( lua_isfunction(L,lua_gettop(L)) ) { //Foo exists
lua_pushnumber(L,1);
lua_pushnumber(L,2);
lua_pushstring(L,"3");
lua_pushvalue(L, -4); //copy of foo()
if( (res = lua_pcall(L, 3, 2, 0/*default error func*/)) ) {
string err = lua_tostring(L, -1);
lua_pop(L, 1);
//error: see above
}
int a_int = (int)lua_tointeger(L,-2);
string b_str = lua_tostring(L,-1);
lua_pop(L,2+1); //2 returns, + extra copy of Foo()
}
}

Can't lua_resume after async_wait?

I have some lua script that have some long running task like getting a web page so I make it yield then the C code handle get page job async, so the thread free to do other job and after a specify time it check back to see is the get page job finished , if so then resume the script. the problem is the thread can't resume the job after async wait.
here is my code I riped it from a class so a little messy sorry
////script:
function Loginmegaupload_com(hp, user, pass, cookie)
setURL(hp, "http://megaupload.com/?c=login")
importPost(hp, "login=1&redir=1")
addPost(hp, "username", user)
addPost(hp, "password", pass)
GetPage()
if isHeaderContain(hp, "user=") ~= nil then
SetFileLink(cookie, GetAllCookie(hp))
return 1
else
return 0
end
end
////c code
int FileSharingService::GetPage(lua_State *ls)
{
return lua_yield(ls, 0);
}
void FileSharingService::AsyncWait(Http_RequestEx *Http, lua_State *LS, boost::asio::deadline_timer* Timer)
{
if( (Http->status_code == Http_RequestEx::ERROR) || (Http->status_code == Http_RequestEx::FISNISHED))
{
if(Http->status_code == Http_RequestEx::FISNISHED)
{
int result = lua_resume(LS, 0); // here I got result == 2 mean error ?
if(result == 0)//lua script exit normal, resume success
{
delete Http;
delete Timer;
}
}
else
return;
}
else
{
Timer->expires_from_now(boost::posix_time::milliseconds(200));
Timer->async_wait(boost::bind(&FileSharingService::AsyncWait, this, Http, LS, Timer));
}
}
bool FileSharingService::Login(string URL, string User, string Pass, string &Cookie)
{
Http_RequestEx *http = new Http_RequestEx;
http->url = URL;
LuaWarper* Lua = Lua_map[boost::this_thread::get_id()]; //one main luaState per ioservice thread
lua_State *thread = lua_newthread(Lua->GetState());
boost::asio::deadline_timer *timer = new boost::asio::deadline_timer(*HClient.ioservice);
string functioname = "Login" + GetServicename(URL);
if( Lua->isFunctionAvaliable(functioname.c_str()) == false )
{
throw(FileSharingService::SERVICE_NOT_AVALIABLE);
}
else
{
lua_getglobal(thread, functioname.c_str());
lua_pushlightuserdata(thread, http);
lua_pushstring(thread, User.c_str());
lua_pushstring(thread, Pass.c_str());
lua_pushlightuserdata(thread, &Cookie);
int result = lua_resume(thread, 4);
if(result == LUA_YIELD)
{
HClient.Do(*http, false);
AsyncWait(http, thread, timer);
}
else if(result == 0)
{
//fisnished at first call
}
else
{
//yield error, will handle late
}
}
}
Sorry never mind this question, lua_resume return 2 mean error but script work just fine, asio get page work fine too, and I tracked down the line that respond for fail of lua_resume :
httpinfo.header.append(buffer, (HeaderEndIndex-buffer+2) );
if I comment that line lua_resume work as expected it return 0 mean script exit, this line don't do any thing that can affect the lua thread state it just a string assign, I checked there no overflow. so weird.