sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

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

Open gotschmarcel-ni opened this issue 1 year ago • 1 comments

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.

gotschmarcel-ni avatar Apr 11 '24 14:04 gotschmarcel-ni

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';
    }
}

huangqinjin avatar Oct 14 '24 16:10 huangqinjin