pub struct InferenceConfig { /* private fields */ }Expand description
Configuration for a class-file type-inference run.
The default permits diagnostics and runs every analyzed method to a fixed point without an iteration budget. Use the builder-style methods to opt into limits for an untrusted input corpus.
Implementations§
Source§impl InferenceConfig
impl InferenceConfig
Sourcepub const fn strict(&self) -> bool
pub const fn strict(&self) -> bool
Returns whether diagnostics other than notes cause analysis to fail.
Sourcepub const fn max_block_iterations(&self) -> usize
pub const fn max_block_iterations(&self) -> usize
Returns the maximum number of times a basic block may be processed when bounded analysis is enabled.
Sourcepub const fn max_work_items(&self) -> usize
pub const fn max_work_items(&self) -> usize
Returns the maximum number of work-queue entries processed per method when bounded analysis is enabled.
The same budget also bounds automatic class-local method-summary revisits after every method has received its initial analysis pass.
Sourcepub const fn unbounded_analysis(&self) -> bool
pub const fn unbounded_analysis(&self) -> bool
Returns whether analysis runs without configured work limits.
Sourcepub const fn uses_local_variable_metadata(&self) -> bool
pub const fn uses_local_variable_metadata(&self) -> bool
Returns whether validated LocalVariableTable hints refine integral values.
The default is false because debug attributes are optional and can be
forged without affecting JVM verification.
Sourcepub const fn has_type_hierarchy(&self) -> bool
pub const fn has_type_hierarchy(&self) -> bool
Returns whether optional class-hierarchy refinement is enabled.
Sourcepub const fn has_method_summaries(&self) -> bool
pub const fn has_method_summaries(&self) -> bool
Returns whether caller-provided method-return summaries are enabled.
Sourcepub const fn has_field_summaries(&self) -> bool
pub const fn has_field_summaries(&self) -> bool
Returns whether caller-provided static-field summaries are enabled.
Sourcepub const fn with_strict(self, strict: bool) -> Self
pub const fn with_strict(self, strict: bool) -> Self
Makes diagnostics other than notes fail with Error::StrictAnalysis.
Sourcepub const fn with_max_block_iterations(
self,
max_block_iterations: usize,
) -> Self
pub const fn with_max_block_iterations( self, max_block_iterations: usize, ) -> Self
Sets the per-basic-block processing limit and enables bounded analysis.
A value of zero is rejected by Inferer::new.
Sourcepub const fn with_max_work_items(self, max_work_items: usize) -> Self
pub const fn with_max_work_items(self, max_work_items: usize) -> Self
Sets the per-method work-queue processing limit and enables bounded analysis.
The same value bounds automatic class-local method-summary revisits. A
value of zero is rejected by Inferer::new.
Sourcepub const fn with_unbounded_analysis(self) -> Self
pub const fn with_unbounded_analysis(self) -> Self
Disables work-item and per-block limits.
This is the default behavior and is useful for deeply flattened control flow when completion is more important than a fixed resource budget, including class-local method-summary convergence. It never executes Java code.
Sourcepub const fn with_local_variable_metadata(
self,
use_local_variable_metadata: bool,
) -> Self
pub const fn with_local_variable_metadata( self, use_local_variable_metadata: bool, ) -> Self
Chooses whether to use LocalVariableTable as additional local-type evidence.
Enabled metadata is checked for valid bytecode ranges, local slots, descriptors, and JVM verification categories. It is not a trusted source of truth: an obfuscator can forge it while keeping the class verifier-valid. The default ignores this attribute.
Enables hierarchy-aware reference merges with a caller-provided source.
The supplied hierarchy is consulted only during type merges. It never
causes the inferer to load classes or execute Java code.
Use crate::ClassHierarchy::insert_jar or
crate::ClassHierarchy::insert_jar_file to index reference libraries,
including rt.jar and classes exported from jrt:/.
Examples found in repository?
8fn main() -> Result<(), Box<dyn Error>> {
9 let arguments = env::args_os().skip(1).collect::<Vec<_>>();
10 if arguments.len() != 2 {
11 return Err("usage: cargo run --example infer_jrt -- <class-or-jar> <jdk-java-executable> (JDK 11+)".into());
12 }
13 let classes = read_classes(Path::new(&arguments[0]))?;
14 let mut input_hierarchy = ClassHierarchy::new();
15 for bytes in &classes {
16 input_hierarchy.insert_class(bytes)?;
17 }
18 let without_config =
19 InferenceConfig::default().with_shared_type_hierarchy(Arc::new(input_hierarchy));
20 let without_jrt = Inferer::new(without_config)?.infer_classes(&classes)?;
21 eprintln!("Reading jrt:/ from the selected JDK; target classes are never executed.");
22 let export = Command::new(&arguments[1])
23 .arg(concat!(
24 env!("CARGO_MANIFEST_DIR"),
25 "/examples/support/ExportJrt.java"
26 ))
27 .output()?;
28 if !export.status.success() {
29 return Err(format!(
30 "jrt export failed: {}",
31 String::from_utf8_lossy(&export.stderr)
32 )
33 .into());
34 }
35 let mut hierarchy = ClassHierarchy::new();
36 let reference_count = hierarchy.insert_jar(&export.stdout)?;
37 drop(export);
38 for bytes in &classes {
39 hierarchy.insert_class(bytes)?;
40 }
41 let config = InferenceConfig::default().with_shared_type_hierarchy(Arc::new(hierarchy));
42 let with_jrt = Inferer::new(config)?.infer_classes(&classes)?;
43 println!("JDK reference classes: {reference_count}");
44 println!("Both modes index the input class headers; only the second adds jrt.");
45 comparison::report("without jrt", &without_jrt);
46 comparison::report("with jrt", &with_jrt);
47 comparison::compare(&without_jrt, &with_jrt);
48 if !without_jrt.analysis_complete() || !with_jrt.analysis_complete() {
49 return Err("analysis did not reach a fixed point".into());
50 }
51 Ok(())
52}More examples
5fn main() -> ExitCode {
6 let mut arguments = env::args_os().skip(1);
7 let Some(path) = arguments.next() else {
8 eprintln!("usage: cargo run --example infer -- <class-file> [--reference <jar>]...");
9 return ExitCode::FAILURE;
10 };
11
12 let mut hierarchy = ClassHierarchy::new();
13 while let Some(option) = arguments.next() {
14 if option != "--reference" {
15 eprintln!("unknown option: {}", option.to_string_lossy());
16 return ExitCode::FAILURE;
17 }
18 let Some(reference) = arguments.next() else {
19 eprintln!("--reference requires a JAR path");
20 return ExitCode::FAILURE;
21 };
22 if let Err(error) = hierarchy.insert_jar_file(&reference) {
23 eprintln!("failed to index {}: {error}", reference.to_string_lossy());
24 return ExitCode::FAILURE;
25 }
26 }
27 let mut config = InferenceConfig::default();
28 if !hierarchy.is_empty() {
29 config = config.with_shared_type_hierarchy(Arc::new(hierarchy));
30 }
31 let inferer = match Inferer::new(config) {
32 Ok(inferer) => inferer,
33 Err(error) => {
34 eprintln!("failed to configure inference: {error}");
35 return ExitCode::FAILURE;
36 }
37 };
38
39 let path = Path::new(&path);
40 let bytes = match fs::read(path) {
41 Ok(bytes) => bytes,
42 Err(error) => {
43 eprintln!("failed to read {}: {error}", path.display());
44 return ExitCode::FAILURE;
45 }
46 };
47
48 let inference = match inferer.infer_class(&bytes) {
49 Ok(inference) => inference,
50 Err(error) => {
51 eprintln!("failed to infer {}: {error}", path.display());
52 return ExitCode::FAILURE;
53 }
54 };
55
56 println!("class: {}", inference.class_name().as_str());
57 println!("analysis complete: {}", inference.analysis_complete());
58
59 for method in inference.methods() {
60 println!("\nmethod: {}", method.name());
61 println!(" descriptor: {:?}", method.descriptor());
62 println!(" declared return type: {:?}", method.return_type());
63 println!(
64 " inferred return type: {:?}",
65 method.inferred_return_type()
66 );
67 println!(
68 " returned parameter index: {:?}",
69 method.returned_parameter_index()
70 );
71 println!(" analysis complete: {}", method.analysis_complete());
72 println!(" local types:");
73
74 for (slot, inferred_type) in method.local_types().iter().enumerate() {
75 println!(" {slot}: {inferred_type:?}");
76 }
77
78 for instruction in method.instructions() {
79 if instruction.operand_expectations().is_empty() {
80 continue;
81 }
82 println!(
83 " operand expectations at {}:",
84 instruction.bytecode_offset()
85 );
86 for expectation in instruction.operand_expectations() {
87 println!(
88 " stack[{}]: {:?}",
89 expectation.stack_index(),
90 expectation.constraint()
91 );
92 }
93 }
94 }
95
96 if inference.diagnostics().is_empty() {
97 println!("\ndiagnostics: none");
98 } else {
99 println!("\ndiagnostics:");
100 for diagnostic in inference.diagnostics() {
101 let location = diagnostic.location();
102 println!(
103 " {:?} {:?}: {}",
104 diagnostic.severity(),
105 diagnostic.kind(),
106 diagnostic.message()
107 );
108
109 if let Some(method_name) = location.method_name() {
110 println!(
111 " method: {}{}",
112 method_name,
113 location.method_descriptor().unwrap_or_default()
114 );
115 }
116 if let Some(offset) = location.bytecode_offset() {
117 println!(" bytecode offset: {offset}");
118 }
119 }
120 }
121
122 ExitCode::SUCCESS
123}Enables caller-provided return summaries for resolved member calls.
The resolver is queried using only information already present in the class file. It never causes the inferer to load classes or execute Java code.
Enables caller-provided value summaries for resolved getstatic calls.
The resolver is queried using only information already present in the class file. It never causes the inferer to load classes or execute Java code. Instance-field reads continue to use their descriptor type.
Trait Implementations§
Source§impl Clone for InferenceConfig
impl Clone for InferenceConfig
Source§impl Debug for InferenceConfig
impl Debug for InferenceConfig
Source§impl Default for InferenceConfig
impl Default for InferenceConfig
impl Eq for InferenceConfig
Auto Trait Implementations§
impl !RefUnwindSafe for InferenceConfig
impl !UnwindSafe for InferenceConfig
impl Freeze for InferenceConfig
impl Send for InferenceConfig
impl Sync for InferenceConfig
impl Unpin for InferenceConfig
impl UnsafeUnpin for InferenceConfig
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.