ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 492 forks source link

Accessing table field with the wrong user type causes a segmentation fault #1595

Open gotschmarcel-ni opened 2 months ago

gotschmarcel-ni commented 2 months ago

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.