use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use crate::error::Error;
use crate::limits::{Charge, heap_cost};
use crate::raw::RawStr;
mod packed;
mod parse;
pub use packed::Packed;
pub use parse::{LIMB_WORK, MAX_LIMBS};
pub const PY_INT_MAX_STR_DIGITS: usize = 4300;
#[derive(Clone, Debug)]
pub struct UnityVersion {
raw: RawStr,
packed: Packed,
}
impl UnityVersion {
pub fn parse(raw: &RawStr) -> Result<Self, VersionError> {
match parse::parse_packed(raw.as_bytes(), parse::Work::new(None)) {
Ok(Some(packed)) => Ok(Self {
raw: raw.clone(),
packed,
}),
Ok(None) | Err(_) => Err(VersionError::NoMatch(raw.clone())),
}
}
pub(crate) fn parse_charged(
raw: &RawStr,
charge: &mut Charge,
) -> Result<Result<Self, VersionError>, Error> {
Ok(
match parse::parse_packed(raw.as_bytes(), parse::Work::new(Some(charge)))? {
Some(packed) => Ok(Self {
raw: raw.clone(),
packed,
}),
None => Err(VersionError::NoMatch(raw.clone())),
},
)
}
#[must_use]
pub fn from_packed(packed: u64) -> Self {
Self {
raw: RawStr::default(),
packed: Packed::from_u128(u128::from(packed)),
}
}
pub fn raw(&self) -> &RawStr {
&self.raw
}
pub fn packed(&self) -> &Packed {
&self.packed
}
#[must_use]
pub fn heap_bytes(&self) -> usize {
self.packed.heap_bytes()
}
fn heap_charge(&self) -> u64 {
match self.heap_bytes() {
0 => 0,
n => heap_cost(u64::try_from(n).unwrap_or(u64::MAX)),
}
}
pub fn packed_u64(&self) -> Option<u64> {
self.packed.as_u128().and_then(|v| u64::try_from(v).ok())
}
pub fn as_tuple(&self) -> Result<(u16, u16, u16, u8, u8), VersionError> {
let ty = u8::try_from(self.packed.bits(8, 8)).unwrap_or(u8::MAX);
if !(ty <= 5 || ty == 255) {
return Err(VersionError::TypeByte(ty));
}
let field = |shift: u32| u16::try_from(self.packed.bits(shift, 16)).unwrap_or(u16::MAX);
Ok((
field(48),
field(32),
field(16),
ty,
u8::try_from(self.packed.bits(0, 8)).unwrap_or(u8::MAX),
))
}
#[must_use]
pub fn major(&self) -> u16 {
u16::try_from(self.packed.bits(48, 16)).unwrap_or(u16::MAX)
}
pub fn lt_tuple(&self, other: &[u16]) -> Result<bool, VersionError> {
let (major, minor, build, ty, number) = self.as_tuple()?;
let mine = [major, minor, build, u16::from(ty), u16::from(number)];
Ok(mine.as_slice() < other)
}
}
impl PartialEq for UnityVersion {
fn eq(&self, other: &Self) -> bool {
self.packed == other.packed
}
}
impl Eq for UnityVersion {}
impl Hash for UnityVersion {
fn hash<H: Hasher>(&self, state: &mut H) {
self.packed.hash(state);
}
}
impl Ord for UnityVersion {
fn cmp(&self, other: &Self) -> Ordering {
self.packed.cmp(&other.packed)
}
}
impl PartialOrd for UnityVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VersionSource {
Own,
ParentBundle,
Fallback,
Forced,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedVersion {
pub version: UnityVersion,
pub source: VersionSource,
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct VersionPolicy {
pub fallback: Option<RawStr>,
pub fallback_warnings: Option<Arc<dyn crate::config::FallbackWarningSink>>,
pub force_bundle: Option<UnityVersion>,
pub force_serialized: Option<UnityVersion>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FlagsClass {
New,
Old,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum VersionError {
#[error("invalid version string {0}")]
NoMatch(RawStr),
#[error("invalid version type byte {0}")]
TypeByte(u8),
#[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."
)]
NoFallback,
}
pub fn resolve_bundle(
engine: &RawStr,
policy: &VersionPolicy,
charge: &mut Charge,
) -> Result<ResolvedVersion, Error> {
if let Some(v) = &policy.force_bundle {
return forced(v, charge);
}
match UnityVersion::parse_charged(engine, charge)? {
Ok(version) if version.major() != 0 => {
return Ok(ResolvedVersion {
version,
source: VersionSource::Own,
});
}
Ok(dropped) => charge.release(dropped.heap_charge()),
Err(_) => {}
}
fallback(policy, charge, true)
}
fn forced(v: &UnityVersion, charge: &mut Charge) -> Result<ResolvedVersion, Error> {
charge.grow(v.heap_charge())?;
Ok(ResolvedVersion {
version: v.clone(),
source: VersionSource::Forced,
})
}
fn fallback(
policy: &VersionPolicy,
charge: &mut Charge,
bundle: bool,
) -> Result<ResolvedVersion, Error> {
let s = policy.fallback.as_ref().ok_or(VersionError::NoFallback)?;
let s = policy.fallback_warnings.as_ref().map_or_else(
|| Ok(s.clone()),
|warnings| warnings.warn_value_at(s, bundle),
)?;
Ok(ResolvedVersion {
version: UnityVersion::parse_charged(&s, charge)??,
source: VersionSource::Fallback,
})
}
fn unusable(s: &RawStr) -> bool {
s.is_empty() || s.as_bytes() == b"0.0.0"
}
pub fn resolve_serialized(
own: &RawStr,
parent_engine: Option<&RawStr>,
policy: &VersionPolicy,
charge: &mut Charge,
) -> Result<ResolvedVersion, Error> {
if let Some(v) = &policy.force_serialized {
return forced(v, charge);
}
let (mut s, mut source) = (own, VersionSource::Own);
if unusable(s) {
if let Some(parent) = parent_engine {
(s, source) = (parent, VersionSource::ParentBundle);
}
if unusable(s) {
return fallback(policy, charge, false);
}
}
Ok(ResolvedVersion {
version: UnityVersion::parse_charged(s, charge)??,
source,
})
}
pub fn flags_class(engine: &UnityVersion) -> Result<FlagsClass, VersionError> {
let v = engine;
let major = v.as_tuple()?.0;
let old = v.lt_tuple(&[2020])?
|| (major == 2020 && v.lt_tuple(&[2020, 3, 34])?)
|| (major == 2021 && v.lt_tuple(&[2021, 3, 2])?)
|| (major == 2022 && v.lt_tuple(&[2022, 1, 1])?);
Ok(if old {
FlagsClass::Old
} else {
FlagsClass::New
})
}
pub fn uses_block_alignment(format: u32, engine: &UnityVersion) -> Result<bool, VersionError> {
if format >= 7 {
return Ok(true);
}
Ok(engine.as_tuple()?.0 == 2019 && !engine.lt_tuple(&[2019, 4, 15])?)
}
#[cfg(test)]
mod tests;