Fix re-entrant context borrow during subscript calls

Move `SubscriptManager` to its own app data slot and dispatch subscript
calls only after releasing the context and manager borrow.
This commit is contained in:
meehl committed 2026-10-15 18:58:11 +02:00
1 parent c6d5241b98
commit 8ddcbf89f7
3 files changed
+88 -56

No files matched your search

+44 -14
View File
@@ -10,7 +10,7 @@ use crate::{
draw_commands::DrawCommandRecorder,
fonts::Fonts,
input::InputState,
pob::subscript::{SubscriptManager, SubscriptResult},
pob::subscript::{NativeMultiValue, SubscriptEvent, SubscriptManager},
renderer::textures::TextureManager,
stage::{StageEvent, StageFrameOutput, StageTransition},
util::{append_lua_package_dir, change_working_directory},
@@ -36,7 +36,6 @@ pub struct Context {
pub recorder: DrawCommandRecorder,
pub fonts: Rc<RefCell<Fonts>>,
pub texture_manager: Rc<RefCell<TextureManager>>,
pub subscript_manager: RefCell<SubscriptManager>,
/// Directory containing the PoB Lua scripts
pub script_dir: PathBuf,
pub current_working_dir: PathBuf,
@@ -59,7 +58,6 @@ impl Context {
recorder: DrawCommandRecorder::default(),
fonts,
texture_manager,
subscript_manager: RefCell::new(SubscriptManager::default()),
script_dir: script_dir.to_owned(),
current_working_dir: PathBuf::default(),
needs_restart: false,
@@ -97,7 +95,7 @@ impl PathOfBuilding {
texture_manager: Rc<RefCell<TextureManager>>,
) -> anyhow::Result<Self> {
let ctx = Context::new(script_dir, fonts, texture_manager);
let lua = Self::create_lua(ctx)?;
let lua = Self::create_lua(ctx, SubscriptManager::default())?;
Self::launch(&lua, script_dir)?;
@@ -108,7 +106,7 @@ impl PathOfBuilding {
}
/// Builds a `Lua` state with package paths, context, and all API functions registered.
fn create_lua(ctx: Context) -> LuaResult<Lua> {
fn create_lua(ctx: Context, subscript_manager: SubscriptManager) -> LuaResult<Lua> {
// `unsafe_new` needed to allow loading of C modules
let lua = unsafe { Lua::unsafe_new() };
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
@@ -118,8 +116,9 @@ impl PathOfBuilding {
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
lua.globals().set("arg", args_table)?;
// make context accessible to API functions
// make context and subscript manager accessible to API functions
lua.set_app_data(ctx);
lua.set_app_data(subscript_manager);
// register API functions
api::register_globals(&lua)?;
@@ -143,13 +142,18 @@ impl PathOfBuilding {
/// Rebuilds the Lua instance from scratch. Preserves the current `Context`.
fn restart(&mut self) -> LuaResult<()> {
// move context out of current lua instance...
// move context and subscript manager out of current lua instance
let mut ctx = self.lua.remove_app_data::<Context>().unwrap();
let script_dir = ctx.script_dir.clone();
ctx.needs_restart = false;
// and move it into new instance
self.lua = Self::create_lua(ctx)?;
let subscript_manager = self
.lua
.remove_app_data::<SubscriptManager>()
.unwrap_or_default();
// and move both into the new instance
self.lua = Self::create_lua(ctx, subscript_manager)?;
Self::launch(&self.lua, &script_dir)?;
Ok(())
@@ -267,7 +271,7 @@ impl PathOfBuilding {
// this mirrors SimpleGraphic's behavior.
let is_focused = ctx.window_state.is_focused;
let is_hovered = ctx.window_state.is_hovered;
let has_active_subscript = ctx.subscript_manager.borrow().has_running_subscripts();
let has_active_subscript = self.has_active_subscript();
let has_active_coroutine = self.has_active_coroutine();
let request_redraw =
is_focused || is_hovered || has_active_subscript || has_active_coroutine;
@@ -285,15 +289,34 @@ impl PathOfBuilding {
fn handle_subscripts(&self) -> LuaResult<()> {
profiling::scope!("handle_subscripts");
let subscript_events = self.ctx().subscript_manager.borrow_mut().process(&self.lua);
// advance the subscripts and collect the work they produced
let subscript_events = self
.lua
.app_data_mut::<SubscriptManager>()
.unwrap()
.process();
// Handle finished/errored subscripts.
for event in subscript_events {
match event {
SubscriptResult::SubscriptFinished { id, return_values } => {
SubscriptEvent::Call {
function_name,
arguments,
reply_tx,
} => {
let result = api::on_sub_call(&self.lua, function_name, arguments)
.map_err(anyhow::Error::from)
.and_then(NativeMultiValue::try_from);
// non-blocking calls have no reply channel and discard their result
if let Some(reply_tx) = reply_tx {
// if the subscript's thread has already gone away, there's nowhere to send
// the result, so ignore the error
let _ = reply_tx.send(result);
}
}
SubscriptEvent::Finished { id, return_values } => {
api::on_sub_finished(&self.lua, id, return_values)?;
}
SubscriptResult::SubscriptError { id, error } => {
SubscriptEvent::Error { id, error } => {
api::on_sub_error(&self.lua, id, error)?;
}
}
@@ -301,6 +324,13 @@ impl PathOfBuilding {
Ok(())
}
fn has_active_subscript(&self) -> bool {
self.lua
.app_data_ref::<SubscriptManager>()
.unwrap()
.has_running_subscripts()
}
fn has_active_coroutine(&self) -> bool {
self.get_coroutines().is_ok_and(|coroutines| {
coroutines.pairs::<mlua::Thread, bool>().any(|pair| {
+5 -6
View File
@@ -1,6 +1,6 @@
use mlua::{Lua, MultiValue, Result as LuaResult};
use crate::pob::Context;
use crate::pob::{Context, subscript::SubscriptManager};
pub fn launch_subscript(
l: &Lua,
@@ -20,9 +20,8 @@ pub fn launch_subscript(
.collect();
let arguments = args.try_into()?;
let ctx = l.app_data_ref::<Context>().unwrap();
let script_dir = ctx.script_dir.clone();
let subscript_id = ctx.subscript_manager.borrow_mut().push(
let script_dir = l.app_data_ref::<Context>().unwrap().script_dir.clone();
let subscript_id = l.app_data_mut::<SubscriptManager>().unwrap().push(
script_dir,
script_text,
blocking_calls,
@@ -34,8 +33,8 @@ pub fn launch_subscript(
}
pub fn is_subscript_running(l: &Lua, subscript_id: u64) -> LuaResult<bool> {
let ctx = l.app_data_ref::<Context>().unwrap();
Ok(ctx.subscript_manager.borrow().is_running(subscript_id))
let manager = l.app_data_ref::<SubscriptManager>().unwrap();
Ok(manager.is_running(subscript_id))
}
pub fn abort_subscript(_: &Lua, _subscript_id: u64) -> LuaResult<()> {
+39 -36
View File
@@ -1,4 +1,4 @@
use crate::{pob::api, util::append_lua_package_dir};
use crate::util::append_lua_package_dir;
use anyhow::{Result, anyhow};
use mlua::{Integer, IntoLuaMulti, Lua, MultiValue, Number, Value};
use std::{
@@ -7,17 +7,22 @@ use std::{
thread::JoinHandle,
};
/// The outcome of a [`Subscript`] that has finished.
#[derive(Debug)]
pub enum SubscriptResult {
SubscriptFinished {
/// A unit of work produced by advancing the running subscripts.
pub enum SubscriptEvent {
/// A subscript requested that a function in the main Lua instance be called on its behalf.
Call {
function_name: String,
arguments: NativeMultiValue,
/// Present for blocking calls. The return values of the callback must be sent back over it.
reply_tx: Option<Sender<Result<NativeMultiValue>>>,
},
/// A subscript finished successfully.
Finished {
id: u64,
return_values: NativeMultiValue,
},
SubscriptError {
id: u64,
error: String,
},
/// A subscript errored or panicked.
Error { id: u64, error: String },
}
#[derive(Default)]
@@ -53,20 +58,20 @@ impl SubscriptManager {
}
/// Advances all running subscripts by one step.
pub fn process(&mut self, lua: &Lua) -> Vec<SubscriptResult> {
let mut results = vec![];
pub fn process(&mut self) -> Vec<SubscriptEvent> {
let mut events = vec![];
self.scripts.retain_mut(|subscript| {
subscript.handle_calls(lua);
subscript.take_call(&mut events);
subscript.try_join().is_none_or(|event| {
results.push(event);
events.push(event);
// subscript has finished or errored, remove it
false
})
});
results
events
}
/// Returns `true` if at least one subscript is running.
@@ -190,56 +195,54 @@ impl Subscript {
}
}
/// Handles pending `SubscriptCall`s.
/// Collects a pending `SubscriptCall` into `events`.
///
/// Does nothing if there is no pending call.
fn handle_calls(&self, lua: &Lua) {
fn take_call(&self, events: &mut Vec<SubscriptEvent>) {
let Ok(call) = self.call_rx.try_recv() else {
// no pending call, or thread disconnected which is handled on join
return;
};
match call {
events.push(match call {
SubscriptCall::Blocking {
function_name,
arguments,
reply_tx: return_values_sender,
} => {
let result = api::on_sub_call(lua, function_name, arguments)
.map_err(anyhow::Error::from)
.and_then(NativeMultiValue::try_from);
// if the subscript's thread has already gone away, there's nowhere to send the
// result, so ignore the error
let _ = return_values_sender.send(result);
}
reply_tx,
} => SubscriptEvent::Call {
function_name,
arguments,
reply_tx: Some(reply_tx),
},
SubscriptCall::NonBlocking {
function_name,
arguments,
} => {
// return values and errors of non-blocking calls are discarded
let _ = api::on_sub_call(lua, function_name, arguments);
}
}
} => SubscriptEvent::Call {
function_name,
arguments,
reply_tx: None,
},
});
}
/// If the subscript's thread has finished, joins it and returns the resulting
/// `SubscriptResult`.
fn try_join(&mut self) -> Option<SubscriptResult> {
/// `SubscriptEvent`.
fn try_join(&mut self) -> Option<SubscriptEvent> {
if !self.handle.as_ref().is_some_and(JoinHandle::is_finished) {
return None;
}
let event = match self.handle.take().unwrap().join() {
Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished {
Ok(Ok(return_values)) => SubscriptEvent::Finished {
id: self.id,
return_values,
},
Ok(Err(err)) => SubscriptResult::SubscriptError {
Ok(Err(err)) => SubscriptEvent::Error {
id: self.id,
error: err.to_string(),
},
// the thread panicked
Err(_) => SubscriptResult::SubscriptError {
Err(_) => SubscriptEvent::Error {
id: self.id,
error: String::from("Subscript thread panicked!"),
},