From e30b42522433b31523eb929c1ac37bfbaf07ebfc Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Sat, 27 Jan 2024 11:51:59 +0000 Subject: [PATCH] Fix crash when initializing Luau sandbox without stdlibs (#361) --- mlua-sys/src/luau/lauxlib.rs | 9 ++++++--- tests/luau.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/mlua-sys/src/luau/lauxlib.rs b/mlua-sys/src/luau/lauxlib.rs index 73788af..9f4384c 100644 --- a/mlua-sys/src/luau/lauxlib.rs +++ b/mlua-sys/src/luau/lauxlib.rs @@ -144,9 +144,12 @@ pub unsafe fn luaL_sandbox(L: *mut lua_State, enabled: c_int) { // set all builtin metatables to read-only lua_pushliteral(L, ""); - lua_getmetatable(L, -1); - lua_setreadonly(L, -1, enabled); - lua_pop(L, 2); + if lua_getmetatable(L, -1) != 0 { + lua_setreadonly(L, -1, enabled); + 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, enabled); diff --git a/tests/luau.rs b/tests/luau.rs index 987ea4f..aedcc53 100644 --- a/tests/luau.rs +++ b/tests/luau.rs @@ -275,6 +275,22 @@ fn test_sandbox() -> Result<()> { Ok(()) } +#[test] +fn test_sandbox_nolibs() -> Result<()> { + let lua = Lua::new_with(StdLib::NONE, LuaOptions::default()).unwrap(); + + lua.sandbox(true)?; + lua.load("global = 123").exec()?; + let n: i32 = lua.load("return global").eval()?; + assert_eq!(n, 123); + assert_eq!(lua.globals().get::<_, Option>("global")?, Some(123)); + + lua.sandbox(false)?; + assert_eq!(lua.globals().get::<_, Option>("global")?, None); + + Ok(()) +} + #[test] fn test_sandbox_threads() -> Result<()> { let lua = Lua::new();