use crate::error::{IsleError, LuaErrorKind, LuaFailure};
use mlua::{Function, Lua, MultiValue, RegistryKey, Value};
use std::ffi::{c_int, CStr};
const TRACES: &CStr = c"__mlua_isle_traces";
#[cfg(feature = "tokio")]
pub(crate) const WRAP_CALL: &str = "\
local mark, f, xpcall, handler, take = ...
local function finish(ok, ...)
if ok then return true, ... end
local e = ...
return false, e, take(e)
end
return function(...)
mark()
take()
return finish(xpcall(f, handler, ...))
end";
struct Protect {
xpcall: RegistryKey,
handler: RegistryKey,
take: RegistryKey,
}
pub(crate) fn install(lua: &Lua) -> Result<(), IsleError> {
install_inner(lua).map_err(|e| IsleError::Init(LuaFailure::from_mlua(&e)))?
}
fn install_inner(lua: &Lua) -> mlua::Result<Result<(), IsleError>> {
if lua.app_data_ref::<Protect>().is_some() {
return Ok(Ok(()));
}
let xpcall = match lua.globals().get::<Value>("xpcall")? {
Value::Function(f) => f,
_ => {
return Ok(Err(IsleError::Init(LuaFailure::new(
LuaErrorKind::External,
"the `xpcall` global is not a function; \
attach the VM before sandboxing its globals",
))))
}
};
let traces = lua.create_table()?;
traces.set_metatable(Some(lua.create_table_from([("__mode", "k")])?))?;
lua.set_named_registry_value(TRACES.to_str().expect("ASCII key"), &traces)?;
let handler = unsafe { lua.create_c_function(trace_handler)? };
let take = unsafe { lua.create_c_function(take_handler)? };
let protect = Protect {
xpcall: lua.create_registry_value(xpcall)?,
handler: lua.create_registry_value(handler)?,
take: lua.create_registry_value(take)?,
};
lua.set_app_data(protect);
Ok(Ok(()))
}
pub(crate) type Parts = (Function, Function, Function);
pub(crate) fn parts(lua: &Lua) -> Result<Parts, IsleError> {
install(lua)?;
let p = lua.app_data_ref::<Protect>().expect("installed just above");
Ok((
lua.registry_value(&p.xpcall)?,
lua.registry_value(&p.handler)?,
lua.registry_value(&p.take)?,
))
}
unsafe extern "C-unwind" fn trace_handler(l: *mut mlua::ffi::lua_State) -> c_int {
use mlua::ffi;
ffi::lua_settop(l, 1);
if ffi::lua_checkstack(l, 4 + ffi::LUA_TRACEBACK_STACK) == 0 {
return 1;
}
if ffi::lua_getfield(l, ffi::LUA_REGISTRYINDEX, TRACES.as_ptr()) != ffi::LUA_TTABLE {
ffi::lua_settop(l, 1);
return 1;
}
ffi::lua_pushthread(l);
ffi::lua_createtable(l, 2, 0);
ffi::lua_pushvalue(l, 1);
ffi::lua_rawseti(l, -2, 1);
ffi::luaL_traceback(l, l, std::ptr::null(), 1);
ffi::lua_rawseti(l, -2, 2);
ffi::lua_rawset(l, 2);
ffi::lua_settop(l, 1);
1
}
unsafe extern "C-unwind" fn take_handler(l: *mut mlua::ffi::lua_State) -> c_int {
use mlua::ffi;
ffi::lua_settop(l, 1);
if ffi::lua_checkstack(l, 4) == 0 {
ffi::lua_settop(l, 0);
ffi::lua_pushboolean(l, 0);
return 1;
}
if ffi::lua_getfield(l, ffi::LUA_REGISTRYINDEX, TRACES.as_ptr()) != ffi::LUA_TTABLE {
ffi::lua_settop(l, 0);
ffi::lua_pushboolean(l, 0);
return 1;
}
ffi::lua_pushthread(l);
ffi::lua_rawget(l, 2);
if ffi::lua_type(l, 3) != ffi::LUA_TTABLE {
ffi::lua_settop(l, 0);
ffi::lua_pushboolean(l, 0);
return 1;
}
ffi::lua_pushthread(l);
ffi::lua_pushnil(l);
ffi::lua_rawset(l, 2);
ffi::lua_rawgeti(l, 3, 1);
if ffi::lua_rawequal(l, 1, 4) == 0 {
ffi::lua_settop(l, 0);
ffi::lua_pushboolean(l, 0);
return 1;
}
ffi::lua_pushboolean(l, 1);
ffi::lua_rawgeti(l, 3, 2);
2
}
fn take_trace(take: &Function, err: Value) -> mlua::Result<(bool, Option<String>)> {
let (handled, trace): (bool, Option<mlua::LuaString>) = take.call(err)?;
Ok((handled, trace.map(|s| s.to_string_lossy())))
}
pub(crate) fn call(lua: &Lua, func: Function, args: MultiValue) -> Result<MultiValue, IsleError> {
let (xpcall, handler, take) = parts(lua)?;
take_trace(&take, Value::Nil)?;
let mut call_args = MultiValue::with_capacity(args.len() + 2);
call_args.push_back(Value::Function(func));
call_args.push_back(Value::Function(handler));
call_args.extend(args);
let mut out: MultiValue = xpcall.call(call_args)?;
match out.pop_front() {
Some(Value::Boolean(true)) => Ok(out),
_ => {
let err = out.pop_front().unwrap_or(Value::Nil);
let (handled, trace) = take_trace(&take, err.clone())?;
Err(error_from_value(lua, err, handled, trace))
}
}
}
#[cfg(feature = "tokio")]
pub(crate) fn unwrap_root(lua: &Lua, mut values: MultiValue) -> Result<MultiValue, IsleError> {
match values.pop_front() {
Some(Value::Boolean(true)) => Ok(values),
Some(Value::Boolean(false)) => {
let err = values.pop_front().unwrap_or(Value::Nil);
let handled = matches!(values.pop_front(), Some(Value::Boolean(true)));
let trace = match values.pop_front() {
Some(Value::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
Err(error_from_value(lua, err, handled, trace))
}
other => Err(IsleError::Lua(LuaFailure::new(
LuaErrorKind::Other,
format!("unexpected protected-call result: {other:?}"),
))),
}
}
fn error_from_value(lua: &Lua, value: Value, handled: bool, trace: Option<String>) -> IsleError {
if let Value::Error(e) = &value {
return match IsleError::from((**e).clone()) {
IsleError::Lua(mut f) => {
if f.traceback.is_none() {
f.traceback = trace;
}
IsleError::Lua(f)
}
other => other,
};
}
let message = match value.to_string() {
Ok(s) => s,
Err(_) => match &value {
Value::String(s) => s.to_string_lossy(),
other => format!("{other:?}"),
},
};
if !handled {
let kind = if message.contains("not enough memory") {
LuaErrorKind::Memory
} else if message.contains("error in error handling") {
LuaErrorKind::Other
} else {
LuaErrorKind::Runtime
};
return IsleError::Lua(LuaFailure::new(kind, message));
}
let mut f = LuaFailure::new(LuaErrorKind::Runtime, message);
f.traceback = trace;
#[cfg(feature = "serde")]
{
use mlua::LuaSerdeExt;
f.value = lua.from_value::<serde_json::Value>(value).ok();
}
#[cfg(not(feature = "serde"))]
let _ = lua;
IsleError::Lua(f)
}