Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Auto Splitting runtime in livesplit-core #749

Merged
merged 1 commit into from
Dec 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 11 additions & 17 deletions capi/src/auto_splitting_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ pub struct AutoSplittingRuntime;
#[allow(missing_docs)]
#[cfg(not(feature = "auto-splitting"))]
impl AutoSplittingRuntime {
pub fn new(_: SharedTimer) -> Self {
pub fn new() -> Self {
Self
}

pub fn unload_script_blocking(&self) -> Result<(), ()> {
pub fn unload(&self) -> Result<(), ()> {
Err(())
}

pub fn load_script_blocking(&self, _: PathBuf) -> Result<(), ()> {
pub fn load(&self, _: PathBuf, _: SharedTimer) -> Result<(), ()> {
Err(())
}
}
Expand All @@ -36,32 +36,26 @@ pub type OwnedAutoSplittingRuntime = Box<AutoSplittingRuntime>;
/// type
pub type NullableOwnedAutoSplittingRuntime = Option<OwnedAutoSplittingRuntime>;

/// Creates a new Auto Splitting Runtime for a Timer.
/// Creates a new Auto Splitting Runtime.
#[no_mangle]
pub extern "C" fn AutoSplittingRuntime_new(
shared_timer: OwnedSharedTimer,
) -> OwnedAutoSplittingRuntime {
Box::new(AutoSplittingRuntime::new(*shared_timer))
pub extern "C" fn AutoSplittingRuntime_new() -> OwnedAutoSplittingRuntime {
Box::new(AutoSplittingRuntime::new())
}

/// Attempts to load an auto splitter. Returns true if successful.
#[no_mangle]
pub unsafe extern "C" fn AutoSplittingRuntime_load_script(
pub unsafe extern "C" fn AutoSplittingRuntime_load(
this: &AutoSplittingRuntime,
path: *const c_char,
shared_timer: OwnedSharedTimer,
) -> bool {
let path = str(path);
if !path.is_empty() {
this.load_script_blocking(PathBuf::from(path)).is_ok()
} else {
false
}
this.load(PathBuf::from(str(path)), *shared_timer).is_ok()
}

/// Attempts to unload the auto splitter. Returns true if successful.
#[no_mangle]
pub extern "C" fn AutoSplittingRuntime_unload_script(this: &AutoSplittingRuntime) -> bool {
this.unload_script_blocking().is_ok()
pub extern "C" fn AutoSplittingRuntime_unload(this: &AutoSplittingRuntime) -> bool {
this.unload().is_ok()
}

/// drop
Expand Down
1 change: 1 addition & 0 deletions crates/livesplit-auto-splitting/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ edition = "2021"

[dependencies]
anyhow = { version = "1.0.45", default-features = false }
arc-swap = "1.6.0"
async-trait = "0.1.73"
bytemuck = { version = "1.14.0", features = ["min_const_generics"] }
indexmap = "2.0.2"
Expand Down
16 changes: 15 additions & 1 deletion crates/livesplit-auto-splitting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,20 @@ pub mod settings;
mod timer;

pub use process::Process;
pub use runtime::{Config, CreationError, InterruptHandle, Runtime, RuntimeGuard};
pub use runtime::{
AutoSplitter, CompiledAutoSplitter, Config, CreationError, ExecutionGuard, InterruptHandle,
Runtime,
};
pub use time;
pub use timer::{Timer, TimerState};

const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Config>();
assert_send_sync::<Process>();
assert_send_sync::<Runtime>();
assert_send_sync::<CompiledAutoSplitter>();
const fn with_timer<T: Send + Sync + Timer>() {
assert_send_sync::<AutoSplitter<T>>();
}
};
16 changes: 12 additions & 4 deletions crates/livesplit-auto-splitting/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,17 @@ pub enum ModuleError {

pub type Address = u64;

// FIXME: Temporary workaround until this is merged and released:
// https://github.com/rbspy/read-process-memory/pull/21
struct UnsafeSendSync<T>(T);
// SAFETY: Temporary
unsafe impl<T> Send for UnsafeSendSync<T> {}
// SAFETY: Temporary
unsafe impl<T> Sync for UnsafeSendSync<T> {}

/// A process that an auto splitter is attached to.
pub struct Process {
handle: ProcessHandle,
handle: UnsafeSendSync<ProcessHandle>,
pid: Pid,
memory_ranges: Vec<MapRange>,
next_memory_range_check: Instant,
Expand Down Expand Up @@ -66,7 +74,7 @@ impl Process {

let pid = process.pid().as_u32() as Pid;

let handle = pid.try_into().context(InvalidHandle)?;
let handle = UnsafeSendSync(pid.try_into().context(InvalidHandle)?);

let now = Instant::now();
Ok(Process {
Expand All @@ -89,7 +97,7 @@ impl Process {

let pid_out = pid as Pid;

let handle = pid_out.try_into().context(InvalidHandle)?;
let handle = UnsafeSendSync(pid_out.try_into().context(InvalidHandle)?);

let now = Instant::now();
Ok(Process {
Expand Down Expand Up @@ -151,7 +159,7 @@ impl Process {
}

pub(super) fn read_mem(&self, address: Address, buf: &mut [u8]) -> io::Result<()> {
self.handle.copy_address(address as usize, buf)
self.handle.0.copy_address(address as usize, buf)
}

pub(super) fn get_memory_range_count(&mut self) -> Result<usize, ModuleError> {
Expand Down
9 changes: 6 additions & 3 deletions crates/livesplit-auto-splitting/src/runtime/api/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
env::consts::{ARCH, OS},
time::Duration,
sync::atomic,
};

use anyhow::{ensure, Result};
Expand Down Expand Up @@ -28,8 +28,11 @@ pub fn bind<T: Timer>(linker: &mut Linker<Context<T>>) -> Result<(), CreationErr
const MAX_DURATION: f64 = u64::MAX as f64;
ensure!(duration < MAX_DURATION, "The tick rate is too small.");

*caller.data_mut().shared_data.tick_rate.lock().unwrap() =
Duration::from_secs_f64(duration);
caller
.data_mut()
.shared_data
.tick_rate
.store(duration.to_bits(), atomic::Ordering::Relaxed);

Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub fn bind<T: Timer>(linker: &mut Linker<Context<T>>) -> Result<(), CreationErr
.func_wrap("env", "settings_map_load", {
|mut caller: Caller<'_, Context<T>>| {
let ctx = caller.data_mut();
let settings_map = ctx.shared_data.settings_map.lock().unwrap().clone();
let settings_map = ctx.shared_data.get_settings_map();
ctx.settings_maps.insert(settings_map).data().as_ffi()
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ pub fn bind<T: Timer>(linker: &mut Linker<Context<T>>) -> Result<(), CreationErr
let key = Arc::<str>::from(get_str(memory, key_ptr, key_len)?);
let description = get_str(memory, description_ptr, description_len)?.into();
let default_value = default_value != 0;
let value_in_map = match context.shared_data.settings_map.lock().unwrap().get(&key)
{
let value_in_map = match context.shared_data.get_settings_map().get(&key) {
Some(settings::Value::Bool(v)) => *v,
_ => default_value,
};
Expand Down
Loading
Loading