sol2
sol2 copied to clipboard
Accessing table field with the wrong user type causes a segmentation fault
Accessing table field with the wrong user type causes a segmentation fault.
Context
Language: C++
Sol Version: 3.3.0
Defines: SOL_ALL_SAFETIES_ON, SOL_USE_CXX_LUA
Reproduction
Godbolt, which doesn't can't use SOL_USE_CXX_LUA.
#include <sol/sol.hpp>
#include <iostream>
struct T {};
struct C {};
int main() {
sol::state lua;
lua.new_usertype<T>("T", "new", []{ return T{}; });
sol::table tbl = lua.script("return { t = T.new() }");
try {
tbl.get<C>("t");
} catch (const sol::error& error) {
std::cout << "Whoops: " << error.what() << '\n';
}
}
Expectation
get should throw an error that can be caught and handled.
Debugging Context
When debugging this issue, we've identified that the problem is caused by the clean helper created here. It calls lua_pop in it's destructor which tries to call __close on some object, but __close is nil, raising a subsequent panic which results in a throw in a C++ destructor of clean which will call terminate.
Accessing a normal table with a non-existent key also result in segfault.
Repro https://godbolt.org/z/35zPv764v
#include <sol/sol.hpp>
#include <iostream>
int main() {
sol::state lua;
lua.open_libraries();
try {
sol::table os = lua["os"];
int x = os["x"];
} catch (const sol::error& error) {
std::cout << "Whoops: " << error.what() << '\n';
}
}