Test LuaUtil::safeGet preventing crash

BindlessTest
uramer 11 months ago committed by Anton Uramer
parent 550659c2d9
commit 08b7ee8a44

@ -51,6 +51,9 @@ return {
} }
)X"); )X");
TestingOpenMW::VFSTestFile metaIndexErrorFile(
"return setmetatable({}, { __index = function(t, key) error('meta index error') end })");
std::string genBigScript() std::string genBigScript()
{ {
std::stringstream buf; std::stringstream buf;
@ -70,7 +73,7 @@ return {
{ {
std::unique_ptr<VFS::Manager> mVFS = TestingOpenMW::createTestVFS({ { "aaa/counter.lua", &counterFile }, std::unique_ptr<VFS::Manager> mVFS = TestingOpenMW::createTestVFS({ { "aaa/counter.lua", &counterFile },
{ "bbb/tests.lua", &testsFile }, { "invalid.lua", &invalidScriptFile }, { "big.lua", &bigScriptFile }, { "bbb/tests.lua", &testsFile }, { "invalid.lua", &invalidScriptFile }, { "big.lua", &bigScriptFile },
{ "requireBig.lua", &requireBigScriptFile } }); { "requireBig.lua", &requireBigScriptFile }, { "metaIndexError.lua", &metaIndexErrorFile } });
LuaUtil::ScriptsConfiguration mCfg; LuaUtil::ScriptsConfiguration mCfg;
LuaUtil::LuaState mLua{ mVFS.get(), &mCfg }; LuaUtil::LuaState mLua{ mVFS.get(), &mCfg };
@ -223,4 +226,11 @@ return {
// At this moment all instances of the script should be garbage-collected. // At this moment all instances of the script should be garbage-collected.
EXPECT_LT(memWithoutScript, memWithScript); EXPECT_LT(memWithoutScript, memWithScript);
} }
TEST_F(LuaStateTest, SafeIndexMetamethod)
{
sol::table t = mLua.runInNewSandbox("metaIndexError.lua");
// without safe get we crash here
EXPECT_ERROR(LuaUtil::safeGet(t, "any key"), "meta index error");
}
} }

@ -235,7 +235,7 @@ namespace LuaUtil
// work around for a (likely) sol3 bug // work around for a (likely) sol3 bug
// when the index meta method throws, simply calling table.get crashes instead of re-throwing the error // when the index meta method throws, simply calling table.get crashes instead of re-throwing the error
template <class Key> template <class Key>
sol::object safe_get(const sol::table& table, const Key& key) sol::object safeGet(const sol::table& table, const Key& key)
{ {
auto index = table.traverse_raw_get<sol::optional<sol::main_protected_function>>( auto index = table.traverse_raw_get<sol::optional<sol::main_protected_function>>(
sol::metatable_key, sol::meta_function::index); sol::metatable_key, sol::meta_function::index);
@ -257,7 +257,7 @@ namespace LuaUtil
{ {
if (!table.is<sol::table>()) if (!table.is<sol::table>())
return sol::nil; return sol::nil;
sol::object value = safe_get(table.as<sol::table>(), first); sol::object value = safeGet(table.as<sol::table>(), first);
if constexpr (sizeof...(str) == 0) if constexpr (sizeof...(str) == 0)
return value; return value;
else else

Loading…
Cancel
Save