Skip to main content

ferro_jtype/
api.rs

1use std::{collections::BTreeSet, sync::Arc};
2
3use crate::ir::parse_and_lower;
4use crate::solver::{analyze_class, analyze_classes};
5use crate::{
6    ClassInference, ClassInferences, Error, FieldSummaryResolver, MethodSummaryResolver,
7    TypeHierarchy,
8};
9
10/// Configuration for a class-file type-inference run.
11///
12/// The default permits diagnostics and runs every analyzed method to a fixed
13/// point without an iteration budget. Use the builder-style methods to opt
14/// into limits for an untrusted input corpus.
15#[derive(Clone)]
16pub struct InferenceConfig {
17    strict: bool,
18    max_block_iterations: usize,
19    max_work_items: usize,
20    unbounded_analysis: bool,
21    use_local_variable_metadata: bool,
22    hierarchy: Option<Arc<dyn TypeHierarchy>>,
23    method_summaries: Option<Arc<dyn MethodSummaryResolver>>,
24    field_summaries: Option<Arc<dyn FieldSummaryResolver>>,
25}
26
27impl std::fmt::Debug for InferenceConfig {
28    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        formatter
30            .debug_struct("InferenceConfig")
31            .field("strict", &self.strict)
32            .field("max_block_iterations", &self.max_block_iterations)
33            .field("max_work_items", &self.max_work_items)
34            .field("unbounded_analysis", &self.unbounded_analysis)
35            .field(
36                "use_local_variable_metadata",
37                &self.use_local_variable_metadata,
38            )
39            .field("has_type_hierarchy", &self.hierarchy.is_some())
40            .field("has_method_summaries", &self.method_summaries.is_some())
41            .field("has_field_summaries", &self.field_summaries.is_some())
42            .finish()
43    }
44}
45
46impl PartialEq for InferenceConfig {
47    fn eq(&self, other: &Self) -> bool {
48        self.strict == other.strict
49            && self.max_block_iterations == other.max_block_iterations
50            && self.max_work_items == other.max_work_items
51            && self.unbounded_analysis == other.unbounded_analysis
52            && self.use_local_variable_metadata == other.use_local_variable_metadata
53            && match (&self.hierarchy, &other.hierarchy) {
54                (Some(left), Some(right)) => Arc::ptr_eq(left, right),
55                (None, None) => true,
56                _ => false,
57            }
58            && match (&self.method_summaries, &other.method_summaries) {
59                (Some(left), Some(right)) => Arc::ptr_eq(left, right),
60                (None, None) => true,
61                _ => false,
62            }
63            && match (&self.field_summaries, &other.field_summaries) {
64                (Some(left), Some(right)) => Arc::ptr_eq(left, right),
65                (None, None) => true,
66                _ => false,
67            }
68    }
69}
70
71impl Eq for InferenceConfig {}
72
73impl Default for InferenceConfig {
74    fn default() -> Self {
75        Self {
76            strict: false,
77            max_block_iterations: 128,
78            max_work_items: 50_000,
79            unbounded_analysis: true,
80            use_local_variable_metadata: false,
81            hierarchy: None,
82            method_summaries: None,
83            field_summaries: None,
84        }
85    }
86}
87
88impl InferenceConfig {
89    /// Returns whether diagnostics other than notes cause analysis to fail.
90    #[must_use]
91    pub const fn strict(&self) -> bool {
92        self.strict
93    }
94
95    /// Returns the maximum number of times a basic block may be processed
96    /// when bounded analysis is enabled.
97    #[must_use]
98    pub const fn max_block_iterations(&self) -> usize {
99        self.max_block_iterations
100    }
101
102    /// Returns the maximum number of work-queue entries processed per method
103    /// when bounded analysis is enabled.
104    ///
105    /// The same budget also bounds automatic class-local method-summary
106    /// revisits after every method has received its initial analysis pass.
107    #[must_use]
108    pub const fn max_work_items(&self) -> usize {
109        self.max_work_items
110    }
111
112    /// Returns whether analysis runs without configured work limits.
113    #[must_use]
114    pub const fn unbounded_analysis(&self) -> bool {
115        self.unbounded_analysis
116    }
117
118    /// Returns whether validated `LocalVariableTable` hints refine integral values.
119    ///
120    /// The default is `false` because debug attributes are optional and can be
121    /// forged without affecting JVM verification.
122    #[must_use]
123    pub const fn uses_local_variable_metadata(&self) -> bool {
124        self.use_local_variable_metadata
125    }
126
127    /// Returns whether optional class-hierarchy refinement is enabled.
128    #[must_use]
129    pub const fn has_type_hierarchy(&self) -> bool {
130        self.hierarchy.is_some()
131    }
132
133    /// Returns whether caller-provided method-return summaries are enabled.
134    #[must_use]
135    pub const fn has_method_summaries(&self) -> bool {
136        self.method_summaries.is_some()
137    }
138
139    /// Returns whether caller-provided static-field summaries are enabled.
140    #[must_use]
141    pub const fn has_field_summaries(&self) -> bool {
142        self.field_summaries.is_some()
143    }
144
145    /// Makes diagnostics other than notes fail with [`Error::StrictAnalysis`].
146    #[must_use]
147    pub const fn with_strict(mut self, strict: bool) -> Self {
148        self.strict = strict;
149        self
150    }
151
152    /// Sets the per-basic-block processing limit and enables bounded analysis.
153    ///
154    /// A value of zero is rejected by [`Inferer::new`].
155    #[must_use]
156    pub const fn with_max_block_iterations(mut self, max_block_iterations: usize) -> Self {
157        self.max_block_iterations = max_block_iterations;
158        self.unbounded_analysis = false;
159        self
160    }
161
162    /// Sets the per-method work-queue processing limit and enables bounded analysis.
163    ///
164    /// The same value bounds automatic class-local method-summary revisits. A
165    /// value of zero is rejected by [`Inferer::new`].
166    #[must_use]
167    pub const fn with_max_work_items(mut self, max_work_items: usize) -> Self {
168        self.max_work_items = max_work_items;
169        self.unbounded_analysis = false;
170        self
171    }
172
173    /// Disables work-item and per-block limits.
174    ///
175    /// This is the default behavior and is useful for deeply flattened control
176    /// flow when completion is more important than a fixed resource budget,
177    /// including class-local method-summary convergence. It never executes Java
178    /// code.
179    #[must_use]
180    pub const fn with_unbounded_analysis(mut self) -> Self {
181        self.unbounded_analysis = true;
182        self
183    }
184
185    /// Chooses whether to use `LocalVariableTable` as additional local-type evidence.
186    ///
187    /// Enabled metadata is checked for valid bytecode ranges, local slots,
188    /// descriptors, and JVM verification categories. It is not a trusted
189    /// source of truth: an obfuscator can forge it while keeping the class
190    /// verifier-valid. The default ignores this attribute.
191    #[must_use]
192    pub const fn with_local_variable_metadata(mut self, use_local_variable_metadata: bool) -> Self {
193        self.use_local_variable_metadata = use_local_variable_metadata;
194        self
195    }
196
197    /// Enables hierarchy-aware reference merges with a caller-provided source.
198    ///
199    /// The supplied hierarchy is consulted only during type merges. It never
200    /// causes the inferer to load classes or execute Java code.
201    /// Use [`crate::ClassHierarchy::insert_jar`] or
202    /// [`crate::ClassHierarchy::insert_jar_file`] to index reference libraries,
203    /// including `rt.jar` and classes exported from `jrt:/`.
204    #[must_use]
205    pub fn with_shared_type_hierarchy(mut self, hierarchy: Arc<dyn TypeHierarchy>) -> Self {
206        self.hierarchy = Some(hierarchy);
207        self
208    }
209
210    /// Enables caller-provided return summaries for resolved member calls.
211    ///
212    /// The resolver is queried using only information already present in the
213    /// class file. It never causes the inferer to load classes or execute Java
214    /// code.
215    #[must_use]
216    pub fn with_shared_method_summaries(
217        mut self,
218        method_summaries: Arc<dyn MethodSummaryResolver>,
219    ) -> Self {
220        self.method_summaries = Some(method_summaries);
221        self
222    }
223
224    /// Enables caller-provided value summaries for resolved `getstatic` calls.
225    ///
226    /// The resolver is queried using only information already present in the
227    /// class file. It never causes the inferer to load classes or execute Java
228    /// code. Instance-field reads continue to use their descriptor type.
229    #[must_use]
230    pub fn with_shared_field_summaries(
231        mut self,
232        field_summaries: Arc<dyn FieldSummaryResolver>,
233    ) -> Self {
234        self.field_summaries = Some(field_summaries);
235        self
236    }
237
238    pub(crate) fn type_hierarchy(&self) -> Option<&dyn TypeHierarchy> {
239        self.hierarchy.as_deref()
240    }
241
242    pub(crate) fn method_summaries(&self) -> Option<&dyn MethodSummaryResolver> {
243        self.method_summaries.as_deref()
244    }
245
246    pub(crate) fn field_summaries(&self) -> Option<&dyn FieldSummaryResolver> {
247        self.field_summaries.as_deref()
248    }
249
250    pub(crate) fn validate(&self) -> Result<(), Error> {
251        if self.max_block_iterations == 0 {
252            return Err(Error::InvalidConfiguration {
253                message: "max_block_iterations must be greater than zero".to_owned(),
254            });
255        }
256        if self.max_work_items == 0 {
257            return Err(Error::InvalidConfiguration {
258                message: "max_work_items must be greater than zero".to_owned(),
259            });
260        }
261        Ok(())
262    }
263}
264
265/// A reusable class-file type inferer.
266///
267/// An inferer owns an [`InferenceConfig`] and can analyze more than one class
268/// file with it.
269#[derive(Debug, Clone)]
270pub struct Inferer {
271    config: InferenceConfig,
272}
273
274impl Default for Inferer {
275    fn default() -> Self {
276        Self::new(InferenceConfig::default()).expect("default inference configuration is valid")
277    }
278}
279
280impl Inferer {
281    /// Creates an inferer using `config`.
282    ///
283    /// Returns [`Error::InvalidConfiguration`] when either configured limit is
284    /// zero.
285    pub fn new(config: InferenceConfig) -> Result<Self, Error> {
286        config.validate()?;
287        Ok(Self { config })
288    }
289
290    /// Returns this inferer's analysis configuration.
291    #[must_use]
292    pub const fn config(&self) -> &InferenceConfig {
293        &self.config
294    }
295
296    /// Infers types from one complete Java class file.
297    ///
298    /// The analysis works from the supplied class-file bytes and does not load
299    /// JDK symbols or resolve an external class hierarchy. `StackMapTable` is
300    /// ignored so missing or forged verification frames cannot affect results.
301    pub fn infer_class(&self, bytes: &[u8]) -> Result<ClassInference, Error> {
302        let class = parse_and_lower(bytes)?;
303        analyze_class(&class, &self.config)
304    }
305
306    /// Infers types from a batch of complete Java class files.
307    ///
308    /// The batch keeps its input order and rejects duplicate JVM internal class
309    /// names. This method never reads a JAR, directory, class loader, JDK, or
310    /// Java runtime; it only analyzes the supplied class-file bytes. Static and
311    /// special calls to another class in the batch automatically consume that
312    /// class's converged return summary. Virtual calls do the same only for a
313    /// `final` class, a `final` method, or a fresh allocation of the member
314    /// owner. Calls without a uniquely provable target keep their
315    /// descriptor-derived return type. Proven returned-parameter relations also
316    /// propagate across deterministic calls, preserving argument types through
317    /// chains of wrapper methods without an external runtime hierarchy.
318    pub fn infer_classes<I, B>(&self, class_files: I) -> Result<ClassInferences, Error>
319    where
320        I: IntoIterator<Item = B>,
321        B: AsRef<[u8]>,
322    {
323        let mut names = BTreeSet::new();
324        let mut classes = Vec::new();
325        for bytes in class_files {
326            let class = parse_and_lower(bytes.as_ref())?;
327            if !names.insert(class.name.clone()) {
328                return Err(Error::DuplicateClass {
329                    class_name: class.name,
330                });
331            }
332            classes.push(class);
333        }
334
335        analyze_classes(&classes, &self.config).map(ClassInferences::new)
336    }
337}
338
339/// Infers types from one complete Java class file using [`InferenceConfig::default`].
340///
341/// Use [`Inferer`] when custom limits or strict diagnostic handling are needed.
342pub fn infer_class(bytes: &[u8]) -> Result<ClassInference, Error> {
343    Inferer::default().infer_class(bytes)
344}
345
346/// Infers types from caller-supplied Java class files using [`InferenceConfig::default`].
347///
348/// Use [`Inferer`] when custom limits, strict diagnostic handling, or shared
349/// summaries are needed.
350pub fn infer_classes<I, B>(class_files: I) -> Result<ClassInferences, Error>
351where
352    I: IntoIterator<Item = B>,
353    B: AsRef<[u8]>,
354{
355    Inferer::default().infer_classes(class_files)
356}