diff --git a/VM/src/linit.cpp b/VM/src/linit.cpp index b7491952..d2176a97 100644 --- a/VM/src/linit.cpp +++ b/VM/src/linit.cpp @@ -43,9 +43,13 @@ void luaL_sandbox(lua_State* L) // set all builtin metatables to read-only lua_pushliteral(L, ""); - lua_getmetatable(L, -1); - lua_setreadonly(L, -1, true); - lua_pop(L, 2); + if (lua_getmetatable(L, -1)) + { + lua_setreadonly(L, -1, true); + lua_pop(L, 2); + } + else + lua_pop(L, 1); // set globals to readonly and activate safeenv since the env is immutable lua_setreadonly(L, LUA_GLOBALSINDEX, true); diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index 2d6a5ac7..298c5322 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -884,6 +884,17 @@ TEST_CASE("NewUserdataOverflow") CHECK(strcmp(lua_tostring(L, -1), "memory allocation error: block too big") == 0); } +TEST_CASE("SandboxWithoutLibs") +{ + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + + luaopen_base(L); // Load only base library + luaL_sandbox(L); + + CHECK(lua_getreadonly(L, LUA_GLOBALSINDEX)); +} + TEST_CASE("ApiTables") { StateRef globalState(luaL_newstate(), lua_close);