use crate::RawStr;
use crate::limits::{ChargeError, Meter, MeteredVec};
use std::fmt;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
#[derive(Debug)]
pub struct RuntimeConfig {
values: RwLock<(Option<RawStr>, bool)>,
decrypt_key: RwLock<Option<[u8; 16]>>,
decrypt_key_source: RwLock<Option<Arc<dyn DecryptKeySource>>>,
}
pub trait DecryptKeySource: Send + Sync + fmt::Debug {
fn key(&self, meter: &Arc<Meter>) -> Result<Option<[u8; 16]>, ChargeError>;
}
impl Default for RuntimeConfig {
fn default() -> Self {
Self::unitypy()
}
}
impl RuntimeConfig {
#[must_use]
pub fn unitypy() -> Self {
Self {
values: RwLock::new((None, true)),
decrypt_key: RwLock::new(None),
decrypt_key_source: RwLock::new(None),
}
}
pub fn set(&self, fallback: Option<RawStr>, parse_typetree: bool) {
*self
.values
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = (fallback, parse_typetree);
}
#[must_use]
pub fn snapshot(&self) -> (Option<RawStr>, bool) {
self.values
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub fn set_decrypt_key(&self, key: Option<[u8; 16]>) {
*self
.decrypt_key
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = key;
}
pub fn set_decrypt_key_source(&self, source: Arc<dyn DecryptKeySource>) {
*self
.decrypt_key_source
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(source);
}
pub fn resolve_decrypt_key(&self, meter: &Arc<Meter>) -> Result<Option<[u8; 16]>, ChargeError> {
let source = self
.decrypt_key_source
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
if let Some(source) = source {
return source.key(meter);
}
Ok(self.decrypt_key())
}
#[must_use]
pub fn decrypt_key(&self) -> Option<[u8; 16]> {
*self
.decrypt_key
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
#[derive(Debug)]
pub struct UnityVersionFallbackWarning<'a>(pub &'a RawStr);
impl UnityVersionFallbackWarning<'_> {
#[must_use]
pub fn category(&self) -> &'static str {
"UnityVersionFallbackWarning"
}
}
impl fmt::Display for UnityVersionFallbackWarning<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(
"No valid Unity version found, defaulting to UnityPy.config.FALLBACK_UNITY_VERSION (",
)?;
if let Some(s) = self.0.to_str() {
f.write_str(s)?;
} else {
write!(f, "{}", self.0)?;
}
f.write_str(")")
}
}
#[derive(Debug, thiserror::Error)]
pub enum UnityVersionFallbackError {
#[error(
"No valid Unity version found, and the fallback version is not correctly configured. Please explicitly set the value of UnityPy.config.FALLBACK_UNITY_VERSION."
)]
Unconfigured,
#[error(transparent)]
Charge(#[from] ChargeError),
}
impl UnityVersionFallbackError {
#[must_use]
pub fn python_kind(&self) -> &'static str {
match self {
Self::Unconfigured => "UnityVersionFallbackError",
Self::Charge(_) => "MemoryError",
}
}
}
#[derive(Debug)]
pub struct FallbackWarnings {
seen: MeteredVec<RawStr>,
}
impl FallbackWarnings {
#[must_use]
pub fn new(meter: &Arc<Meter>) -> Self {
Self {
seen: MeteredVec::new(meter),
}
}
fn first(&mut self, value: &RawStr) -> Result<bool, ChargeError> {
let meter = self.seen.charge().meter();
for key in self.seen.as_slice() {
let bytes = if key.len() == value.len() {
key.len()
} else {
0
};
meter.count_decode(1_u64.saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX)))?;
if key == value {
return Ok(false);
}
}
meter.count_decode(u64::try_from(value.len()).unwrap_or(u64::MAX))?;
let key = RawStr::charged(value.as_bytes(), meter)?;
self.seen.push(key)?;
Ok(true)
}
}
pub trait FallbackWarningSink: Send + Sync + fmt::Debug {
fn warn(&self, value: &RawStr) -> Result<(), ChargeError>;
fn warn_value(&self, value: &RawStr) -> Result<RawStr, ChargeError> {
self.warn(value)?;
Ok(value.clone())
}
fn warn_value_at(&self, value: &RawStr, _bundle: bool) -> Result<RawStr, ChargeError> {
self.warn_value(value)
}
}
pub struct FilteredWarnings<E> {
state: Mutex<FallbackWarnings>,
emit: E,
}
impl<E> fmt::Debug for FilteredWarnings<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FilteredWarnings").finish_non_exhaustive()
}
}
impl<E> FilteredWarnings<E> {
#[must_use]
pub fn new(meter: &Arc<Meter>, emit: E) -> Self {
Self {
state: Mutex::new(FallbackWarnings::new(meter)),
emit,
}
}
}
impl<E: Fn(UnityVersionFallbackWarning<'_>) + Send + Sync> FallbackWarningSink
for FilteredWarnings<E>
{
fn warn(&self, value: &RawStr) -> Result<(), ChargeError> {
let first = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.first(value)?;
if first {
(self.emit)(UnityVersionFallbackWarning(value));
}
Ok(())
}
}
pub fn get_fallback_version<'a>(
value: Option<&'a RawStr>,
warnings: &mut FallbackWarnings,
mut emit: impl FnMut(UnityVersionFallbackWarning<'_>),
) -> Result<&'a RawStr, UnityVersionFallbackError> {
let value = value.ok_or(UnityVersionFallbackError::Unconfigured)?;
if warnings.first(value)? {
emit(UnityVersionFallbackWarning(value));
}
Ok(value)
}
const _: () = {
crate::send_sync::<RuntimeConfig>();
crate::send_sync::<dyn DecryptKeySource>();
crate::send_sync::<UnityVersionFallbackWarning<'static>>();
crate::send_sync::<UnityVersionFallbackError>();
crate::send_sync::<FallbackWarnings>();
crate::send_sync::<dyn FallbackWarningSink>();
crate::send_sync::<FilteredWarnings<fn(UnityVersionFallbackWarning<'_>)>>();
};