Skip to main content

unityrs_core/
config.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/config.py. See THIRD_PARTY_LICENSES.
2//! Fallback retrieval and warning filtering (`config.py:21-40`).
3//! A binding shares one warning state across call sites, and supplies its warning
4//! emitter. Retrieval does not validate version syntax; parsing happens later.
5
6use crate::RawStr;
7use crate::limits::{ChargeError, Meter, MeteredVec};
8use std::fmt;
9use std::sync::Arc;
10use std::sync::Mutex;
11use std::sync::RwLock;
12
13/// Binding settings captured before entering a load. Existing files retain
14/// their parsed versions and tree flags when a subsequent load updates these.
15#[derive(Debug)]
16pub struct RuntimeConfig {
17    values: RwLock<(Option<RawStr>, bool)>,
18    decrypt_key: RwLock<Option<[u8; 16]>>,
19    decrypt_key_source: RwLock<Option<Arc<dyn DecryptKeySource>>>,
20}
21
22/// A binding resolves its mutable global only when an encrypted bundle needs it.
23pub trait DecryptKeySource: Send + Sync + fmt::Debug {
24    /// Convert the current key, without holding a runtime configuration lock.
25    fn key(&self, meter: &Arc<Meter>) -> Result<Option<[u8; 16]>, ChargeError>;
26}
27
28impl Default for RuntimeConfig {
29    fn default() -> Self {
30        Self::unitypy()
31    }
32}
33
34impl RuntimeConfig {
35    /// Initial UnityPy configuration.
36    #[must_use]
37    pub fn unitypy() -> Self {
38        Self {
39            values: RwLock::new((None, true)),
40            decrypt_key: RwLock::new(None),
41            decrypt_key_source: RwLock::new(None),
42        }
43    }
44
45    /// Replace both settings atomically before a binding's next load.
46    pub fn set(&self, fallback: Option<RawStr>, parse_typetree: bool) {
47        *self
48            .values
49            .write()
50            .unwrap_or_else(std::sync::PoisonError::into_inner) = (fallback, parse_typetree);
51    }
52
53    /// Snapshot the fallback and post-read typetree flag.
54    #[must_use]
55    pub fn snapshot(&self) -> (Option<RawStr>, bool) {
56        self.values
57            .read()
58            .unwrap_or_else(std::sync::PoisonError::into_inner)
59            .clone()
60    }
61
62    /// Configure the key used by a binding's subsequent bundle loads.
63    pub fn set_decrypt_key(&self, key: Option<[u8; 16]>) {
64        *self
65            .decrypt_key
66            .write()
67            .unwrap_or_else(std::sync::PoisonError::into_inner) = key;
68    }
69
70    /// Install a lazy binding resolver for subsequent encrypted loads.
71    pub fn set_decrypt_key_source(&self, source: Arc<dyn DecryptKeySource>) {
72        *self
73            .decrypt_key_source
74            .write()
75            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(source);
76    }
77
78    /// Resolve the key on the active input's meter, outside configuration locks.
79    pub fn resolve_decrypt_key(&self, meter: &Arc<Meter>) -> Result<Option<[u8; 16]>, ChargeError> {
80        let source = self
81            .decrypt_key_source
82            .read()
83            .unwrap_or_else(std::sync::PoisonError::into_inner)
84            .clone();
85        if let Some(source) = source {
86            return source.key(meter);
87        }
88        Ok(self.decrypt_key())
89    }
90
91    /// Copy the configured native key without retaining a lock while decoding.
92    #[must_use]
93    pub fn decrypt_key(&self) -> Option<[u8; 16]> {
94        *self
95            .decrypt_key
96            .read()
97            .unwrap_or_else(std::sync::PoisonError::into_inner)
98    }
99}
100
101/// UnityPy's warning category and message, borrowed without allocating.
102#[derive(Debug)]
103pub struct UnityVersionFallbackWarning<'a>(pub &'a RawStr);
104impl UnityVersionFallbackWarning<'_> {
105    /// Python warning category.
106    #[must_use]
107    pub fn category(&self) -> &'static str {
108        "UnityVersionFallbackWarning"
109    }
110}
111impl fmt::Display for UnityVersionFallbackWarning<'_> {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.write_str(
114            "No valid Unity version found, defaulting to UnityPy.config.FALLBACK_UNITY_VERSION (",
115        )?;
116        if let Some(s) = self.0.to_str() {
117            f.write_str(s)?;
118        } else {
119            write!(f, "{}", self.0)?;
120        }
121        f.write_str(")")
122    }
123}
124
125/// A missing string fallback or a refusal to retain the warning's once key.
126#[derive(Debug, thiserror::Error)]
127pub enum UnityVersionFallbackError {
128    /// `None` and non-string values at the binding boundary.
129    #[error(
130        "No valid Unity version found, and the fallback version is not correctly configured. Please explicitly set the value of UnityPy.config.FALLBACK_UNITY_VERSION."
131    )]
132    Unconfigured,
133    /// Warning state could not grow; never silently suppress a warning.
134    #[error(transparent)]
135    Charge(#[from] ChargeError),
136}
137impl UnityVersionFallbackError {
138    /// Python exception category.
139    #[must_use]
140    pub fn python_kind(&self) -> &'static str {
141        match self {
142            Self::Unconfigured => "UnityVersionFallbackError",
143            Self::Charge(_) => "MemoryError",
144        }
145    }
146}
147
148/// The `once` filter's keys: one per distinct fallback message, across call sites.
149#[derive(Debug)]
150pub struct FallbackWarnings {
151    seen: MeteredVec<RawStr>,
152}
153impl FallbackWarnings {
154    /// Warning keys charge `meter` until this state is dropped.
155    #[must_use]
156    pub fn new(meter: &Arc<Meter>) -> Self {
157        Self {
158            seen: MeteredVec::new(meter),
159        }
160    }
161
162    fn first(&mut self, value: &RawStr) -> Result<bool, ChargeError> {
163        let meter = self.seen.charge().meter();
164        for key in self.seen.as_slice() {
165            // One comparison step, plus an upper bound on bytes examined.
166            let bytes = if key.len() == value.len() {
167                key.len()
168            } else {
169                0
170            };
171            meter.count_decode(1_u64.saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX)))?;
172            if key == value {
173                return Ok(false);
174            }
175        }
176        meter.count_decode(u64::try_from(value.len()).unwrap_or(u64::MAX))?;
177        let key = RawStr::charged(value.as_bytes(), meter)?;
178        self.seen.push(key)?;
179        Ok(true)
180    }
181}
182
183/// Warning delivery for version resolution. A Python binding installs its
184/// warning emitter here; native callers can collect or display the same warning.
185pub trait FallbackWarningSink: Send + Sync + fmt::Debug {
186    /// Emit the configured fallback's warning, respecting the sink's filter.
187    fn warn(&self, value: &RawStr) -> Result<(), ChargeError>;
188
189    /// Python rereads its mutable setting after the warning handler returns.
190    /// Native emitters preserve the original value; bindings may return the
191    /// value a reentrant warning handler installed instead.
192    fn warn_value(&self, value: &RawStr) -> Result<RawStr, ChargeError> {
193        self.warn(value)?;
194        Ok(value.clone())
195    }
196
197    /// Bindings keep separate warning registries for BundleFile and
198    /// SerializedFile, where UnityPy resolves their fallback versions.
199    fn warn_value_at(&self, value: &RawStr, _bundle: bool) -> Result<RawStr, ChargeError> {
200        self.warn_value(value)
201    }
202}
203
204/// One `once` registry shared across files and call sites. The callback runs
205/// after releasing the registry lock, so reentrant warning handlers are safe.
206pub struct FilteredWarnings<E> {
207    state: Mutex<FallbackWarnings>,
208    emit: E,
209}
210impl<E> fmt::Debug for FilteredWarnings<E> {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.debug_struct("FilteredWarnings").finish_non_exhaustive()
213    }
214}
215impl<E> FilteredWarnings<E> {
216    /// Create warning state on the caller's meter without allocating.
217    #[must_use]
218    pub fn new(meter: &Arc<Meter>, emit: E) -> Self {
219        Self {
220            state: Mutex::new(FallbackWarnings::new(meter)),
221            emit,
222        }
223    }
224}
225impl<E: Fn(UnityVersionFallbackWarning<'_>) + Send + Sync> FallbackWarningSink
226    for FilteredWarnings<E>
227{
228    fn warn(&self, value: &RawStr) -> Result<(), ChargeError> {
229        let first = self
230            .state
231            .lock()
232            .unwrap_or_else(std::sync::PoisonError::into_inner)
233            .first(value)?;
234        if first {
235            (self.emit)(UnityVersionFallbackWarning(value));
236        }
237        Ok(())
238    }
239}
240
241/// Return any configured string and emit its warning once. `None` represents
242/// any non-string config value, as UnityPy's `isinstance(value, str)` does.
243pub fn get_fallback_version<'a>(
244    value: Option<&'a RawStr>,
245    warnings: &mut FallbackWarnings,
246    mut emit: impl FnMut(UnityVersionFallbackWarning<'_>),
247) -> Result<&'a RawStr, UnityVersionFallbackError> {
248    let value = value.ok_or(UnityVersionFallbackError::Unconfigured)?;
249    if warnings.first(value)? {
250        emit(UnityVersionFallbackWarning(value));
251    }
252    Ok(value)
253}
254
255const _: () = {
256    crate::send_sync::<RuntimeConfig>();
257    crate::send_sync::<dyn DecryptKeySource>();
258    crate::send_sync::<UnityVersionFallbackWarning<'static>>();
259    crate::send_sync::<UnityVersionFallbackError>();
260    crate::send_sync::<FallbackWarnings>();
261    crate::send_sync::<dyn FallbackWarningSink>();
262    crate::send_sync::<FilteredWarnings<fn(UnityVersionFallbackWarning<'_>)>>();
263};