Skip to main content

Environment

Struct Environment 

Source
pub struct Environment { /* private fields */ }
Expand description

UnityPy’s Environment. A cheap handle: clones share one environment.

Implementations§

Source§

impl Environment

Source

pub fn container(&self) -> Result<ContainerItems<'_>, Error>

container: every non-dependency CAB’s container rows, CABs in registry order, after the preload index is built (environment.py:208-226), as an iterator. It walks the registry, as UnityPy walks env.cabs, so a CAB a dependency’s replaced under its key is not listed.

Source

pub fn container_path( &self, obj: &ObjectRef, ) -> Result<Option<ContainerPath>, Error>

obj.container (files/ObjectReader.py:199-204): the container index built first (Self::container’s pass, whose failure is this call’s), then the path the object’s file’s path_dict holds for its path id (crate::container): a row of the file’s own container whose asset is the object, the last such row winning, else the first row whose preload span reached it. The paths live in the file the object was read from, as UnityPy’s live in its assets_file, so a second handle a caller opened on the same bytes holds only its own rows’.

Where a dependency may be evicted (every option but EnvOptions::unitypy’s, EnvOptions::dep_cache_bytes), an object of a dependency’s file is refused with Unsupported::EvictableContainerPath: an eviction drops the paths the preload set in that file and its reopen does not walk again, so the answer would depend on when the LRU evicted (PARITY.md section 19.3). The preload sets no path in such a file.

Source§

impl Environment

Source

pub fn get_cab( &self, name: &RawStr, meter: &Arc<Meter>, ) -> Result<Option<Cab>, Error>

get_cab: the registry under simplify_name(name), an entry parsed now if it was registered lazily. The lowered key a lookup builds is charged to meter while the lookup runs (the meter of the file whose input chose name; a caller’s own string may use Meter::unlimited), and a name already in its simplified form is not copied (Registry::get). A dependency’s CAB may outlive its bundle in the LRU: Self::get_cab_held returns the handle that keeps it. A pool refusal anywhere in the lookup, the key’s charge to a dependency’s meter included, evicts the others and retries once (plan section 3.13).

Source

pub fn get_cab_held( &self, name: &RawStr, meter: &Arc<Meter>, ) -> Result<Option<HeldCab>, Error>

Self::get_cab, with the handle that keeps a dependency’s CAB’s container alive while the caller holds it (HeldCab): an eviction drops only the LRU’s handle, so the CAB’s pointers into its sibling entries keep resolving (rather than failing with DerefError::ContainerDropped).

Source

pub fn find_file( &self, name: &RawStr, is_dependency: bool, meter: &Arc<Meter>, ) -> Result<Option<File>, Error>

find_file(name, is_dependency): what UnityPy’s returns (environment.py:310-354), the file itself, of whatever kind. First the CAB Self::get_cab finds, as the file it is (UnityPy’s cabs hold the file: environment.py:252-264): a SerializedFile, or a raw reader, a bundle entry’s being that entry (crate::files::BundleFile::entry). Else the resolver’s source for name (CabResolver::find_file), loaded: a bundle, a SerializedFile, a raw reader (a WebFile is refused in P1, as Self::load refuses one). With EnvOptions::keep_resolver_loads that load is a FileEntry under the resolved source’s name, never evicted, a dependency as is_dependency says (UnityPy’s default is true, and a dereference’s call takes it): a dependency’s objects are in neither Self::objects nor Self::container. Without it (EnvOptions::batch) the load is an evictable dependency in the LRU only, whatever the flag, so it is in none of Self::files, objects or container, the one way this call differs from UnityPy’s there (PARITY.md section 19.3, “resolver loads under keep_resolver_loads false”). None where the resolver answers none (UnityPy’s None); the resolver’s error where it returns one (UnityPy’s walk’s FileNotFoundError, CabResolver::find_file). meter as for Self::get_cab. A pool refusal in the lookup, in the resolver’s answer (its own, counted as it returns) or in the load evicts the others and retries that step once (plan section 3.13; review round 12: the resolver’s own refusal was returned untried, which a dereference retried). A dependency’s SerializedFile may outlive its bundle in the LRU, as get_cab’s may: Self::get_cab_held returns the handle that keeps it. (Review round 11: a container the resolver loaded was None, the answer a miss gives.)

Source

pub fn deref( &self, from: &Arc<SerializedFile>, pptr: PPtr, ) -> Result<ObjectRef, DerefError>

PPtr.deref from an object in from (classes/PPtr.py:43-90), by the rules of pptr: from’s container is its bundle (crate::files::ParentKind::Bundle’s handle), or, for a file loaded at top level, this Environment, whose Self::files keys the sibling scan compares. from need not have been loaded here (a batch job’s own bundle handle): its bundle siblings come from its parent, every other CAB from this Environment. When from’s bundle has been dropped (its weak handle no longer upgrades) the dereference fails with DerefError::ContainerDropped rather than guess: UnityPy cannot reach that state, since an object keeps its file’s parent alive, so the bindings and a batch engine keep a strong bundle handle beside every SerializedFile they hand out. A pool refusal anywhere in the dereference (reading or looking up from a dependency’s file) evicts the others and retries once, from’s top-level bundle held meanwhile (plan section 3.13; review round 8: it had no retry).

Source

pub fn deref_held( &self, from: &Arc<SerializedFile>, pptr: PPtr, meter: &Meter, ) -> Result<(ObjectRef, Option<File>), DerefError>

Resolve as in Self::deref, retaining the target’s top-level container when available. Hold the returned file to preserve access to the target’s siblings across dependency cache evictions.

Charge the caller’s work meter for the external path and each sibling name examined, including any scan on retry.

Source

pub fn deref_held_reusing( &self, from: &Arc<SerializedFile>, pptr: PPtr, meter: &Meter, reuse: impl FnMut(FileOccurrence) -> Result<Option<ObjectRef>, Error>, ) -> Result<(ObjectRef, Option<File>), DerefError>

Resolve as in Self::deref_held. Before opening a known target, offer its file occurrence to reuse. The callback may return a retained object at the requested path ID in that occurrence. A hit needs no new target container hold, even after a dependency eviction.

Reuse assumes a dependency’s source stays stable across reopens. A resolver alias may load another copy of a dependency.

Source§

impl Environment

Source

pub fn files(&self) -> FileEntries<'_> ⓘ

files, in the order of the keys’ positions (the least load that listed each, listing.rs’s Files), as UnityPy’s dict iterates when the loads are made one after another in the order of their numbers: one entry per caller load, and with EnvOptions::keep_resolver_loads one per file the resolver loaded (module docs), a repeated key replacing the value in place. Each entry is charged to its file’s meter (its share of the list and the indexes, its lowered key, and a resolver load’s key copy, as a registry slot’s are, registry). An iterator, as the other listings are (module docs): it takes the lock briefly per entry and allocates nothing but the entry it yields.

Source

pub fn objects(&self) -> Objects<'_> ⓘ

objects: every object of every non-dependency file of Self::files, in its order, as an iterator (module docs: no allocation per object). A file that fails to load or parse on the way yields its error.

Source§

impl Environment

Source

pub fn load(&self, source: Source) -> Result<File, Error>

load_file: detect, parse, register the CABs, add to files under the source’s name (a repeated name replaces the value in place, as a dict).

Source

pub fn load_dependency(&self, source: Source) -> Result<File, Error>

Loads source as a dependency, as find_file loads one through the resolver: its own meter under crate::budget::Reservation::Dependency (so a refusal names the dependency pool), its CABs registered (lazily under LoadMode::Lazy) without a strong handle, kept in the LRU and evictable, and not added to Self::files (UnityPy has no such call; a batch engine registers its inputs this way). The returned handle is the caller’s: an eviction drops only the LRU’s, so while the caller holds it the slots reach the same open file through their weak handle.

Under LoadMode::Lazy a load that fails publishes nothing: every registration is charged, with the LRU’s entry, before the first is published, so a refusal at any of them leaves the registry as it was (the registry’s module docs, “A failed dependency load”). Under LoadMode::Eager the CABs are registered as they are parsed, as UnityPy’s load_file registers them, so a load that fails keeps those registered before its failure (the partial registration of the module docs).

Source

pub fn load_dependency_with_handle( &self, source: Source, ) -> Result<(File, DependencyFile), Error>

Load a dependency and give the caller an evictable handle to its exact occurrence, even if another dependency registers the same CAB name. Uses the same dependency pool and eviction retry as Self::load_dependency.

Source§

impl Environment

Source

pub fn object_tree( &self, obj: &ObjectRef, nodes: Option<&Arc<Tree>>, ) -> Result<Option<TreeRef>, ParseError>

The tree an object reads with, as UnityPy resolves it (files/ObjectReader.py:285-307): ObjectRef::tree, plus the MonoBehaviour script hook. When the tree came from the provider chain (not nodes, not the type record’s own: UnityPy calls generate_monobehaviour_node only inside if not node:, files/ObjectReader.py:296-304), its root type is MonoBehaviour, and a provider accepts script requests (crate::provider::TypeTreeProvider::accepts_scripts, UnityPy’s env.typetree_generator), the head is read with that tree (check_read off), m_Script is dereferenced through this Environment and parsed, and the provider is asked with its crate::provider::ScriptIdent. As in UnityPy only a ValueError there falls back to the class tree (a null m_Script, a head read that fails with a value error, the provider’s miss); a dereference failure (FileNotFoundError, KeyError, IndexError) is the object’s error. With no such provider nothing is dereferenced (UnityPy raises its ValueError before any deref), so in P1 this equals ObjectRef::tree. Each step that reads a dependency’s object through its meter (the class tree’s compile, for a type record that stores its own tree; the head; the script), when the pool refuses it, evicts the others and retries once, the object’s top-level bundle held from the first step on, as the dereference does (plan section 3.13; review round 8, and round 9: the compile ran outside the retry, so a pool full of an evictable dependency failed every call on an object with an embedded tree). The provider chain’s lookup charges no meter of the core’s.

Source

pub fn generate_monobehaviour_node( &self, obj: &ObjectRef, nodes: Option<&Arc<Tree>>, ) -> Result<TreeRef, MonoBehaviourError>

Explicit generate_monobehaviour_node (files/ObjectReader.py:332-350). Unlike automatic fallback, a missing generator, null script or provider miss is an error. Embedded trees do not suppress this explicit operation.

Source§

impl Environment

Source

pub fn load_file(&self, source: Source) -> Result<Option<File>, Error>

Detect and load one source. ZIPs load their members and return None; other inputs return their File. This is the container-capable companion to the original single-File load/load_dependency interface.

Source

pub fn load_zip_file(&self, source: Source) -> Result<(), Error>

Explicit ZIP/APK loading, independent of filename or byte detection. Members retain their own names (environment.py:162-174).

Source

pub fn load_path(&self, path: &Path) -> Result<(), Error>

Constructor-style local path dispatch: case-sensitive .zip/.apk names explicitly open an archive; every other file uses detection. A path that is neither a file nor a folder is ignored.

Source

pub fn load_files<P: AsRef<Path>>( &self, paths: impl IntoIterator<Item = P>, ) -> Result<(), Error>

load_assets for filesystem paths, merging each split base once per call (environment.py:294-308). A normal path is always read as given.

Source

pub fn load_folder(&self, path: &Path) -> Result<(), Error>

Recursively load a local folder, files before child folders, keeping the filesystem’s order. Walk state and path buffers are metered. Symlink directories inside the walk are opened as files, as fsspec’s walk does; a symlink passed as the root follows its target.

Source§

impl Environment

Source

pub fn load_observed( &self, source: Source, observe: impl FnOnce(&Bytes, &Arc<Meter>) -> Result<(), Error>, ) -> Result<File, Error>

Loads a bounded source and observes the exact immutable bytes that detection and parsing consume, before either starts. Split companions are joined by the source reader first; compressed containers are still compressed here. The observer shares this load’s input meter and may refuse without publishing any files or CAB registrations.

Source

pub fn parse_reader( &self, name: &RawStr, data: Bytes, reader: ReaderKind, ty: FileType, parent_file: Option<&File>, ) -> Result<File, Error>

ImportHelper’s parser selection without detection or a top-level file registration (helpers/ImportHelper.py:127-156). Container constructors still register their child CABs (files/File.py:76-90).

Source

pub fn parse_reader_with_state( &self, name: &RawStr, data: Bytes, reader: ReaderKind, ty: FileType, parent_file: Option<&File>, endian: &mut Option<Endian>, ) -> Result<File, Error>

Self::parse_reader retaining a partial constructor’s endian change.

Source

pub fn load_reader( &self, name: RawStr, data: Bytes, reader: ReaderKind, is_dependency: bool, ) -> Result<Option<File>, Error>

Loads caller-owned bytes by the memory or stream reader’s rules, registers their CABs and lists the file with UnityPy’s dependency flag (environment.py:100-160). ZIP members are loaded and the result is None. The caller’s buffer is not copied or charged; tables, decoded bytes and subsequent reads share this load’s single input meter.

Source

pub fn load_reader_at_position( &self, name: RawStr, data: Bytes, reader: ReaderKind, is_dependency: bool, position: i128, ) -> Result<Option<File>, Error>

Self::load_reader detecting from the caller’s original position before detection resets the reader for construction.

Source§

impl Environment

Source

pub fn resource( &self, from: &Arc<SerializedFile>, path: &RawStr, offset: u64, size: u64, ) -> Result<Bytes, Error>

get_resource_data(path, from, offset, size) (helpers/ResourceReader.py:10-38). The candidate is resolved by UnityPy’s rule (the registry, then dependencies), but each candidate’s slot is first located without being parsed. When the core can tell, without reading anything, that the slot is an entry of from’s own input, the entry is read through from’s bundle and the shared slot is never parsed, so neither the resolution nor the read decodes anything through the shared handle or charges its pool (plan section 3.13): the slot’s open handle is from’s bundle itself, or the slot is a Source::Bytes whose Bytes are from’s bundle’s source (the same allocation and range) at the entry’s directory index. A slot whose source is a Source::Path or Source::Fetch and whose handle is not open (evicted) cannot be compared without opening it again, so it resolves by UnityPy’s rule, through the slot. Which of the two a batch engine’s inputs get is its design (docs/plans/batch.md). The answer is the same entry’s either way. The fallback (the file’s externals and the candidates, loaded when no candidate is registered) loads through the resolver as UnityPy’s load_dependencies does: with EnvOptions::keep_resolver_loads each file it loads is a non-dependency FileEntry under the name asked, whose objects and rows Self::objects and Self::container list, loaded again by a later fallback (module docs); without it, an LRU dependency. path is the object’s string, so the candidates are slices of it (resource::resource_candidates), and each whole name and lowered key a lookup builds is charged to from’s meter while it lives.

A pool refusal (a read or a lookup from a dependency’s file) evicts the others and retries once, from’s top-level bundle held meanwhile: each lookup of the candidates, and each candidate’s name with its fallback load; and every fallback load, an external’s as a candidate’s, listed or not, takes its own retry (Environment::load_resolved), a refusal its fetcher returns included, so a retry never loads again what a load before it loaded (plan section 3.13; review round 8: the read had no retry; review round 12: an external’s load listed under keep_resolver_loads returned its fetcher’s refusal untried).

Source§

impl Environment

Source

pub fn new(options: EnvOptions) -> Self

An empty environment.

Source

pub fn options(&self) -> &EnvOptions

Its options.

Source

pub fn registry(&self) -> &Registry

The CAB registry.

Source

pub fn stats(&self) -> EnvStats

Counters.

Trait Implementations§

Source§

impl Clone for Environment

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Environment

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.