diff --git a/Cargo.lock b/Cargo.lock index 364e024..a1ac432 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,6 +310,7 @@ dependencies = [ "noxis-core", "noxis-structure-check", "regex", + "serde_json", "thiserror", "tracing", ] @@ -355,6 +356,7 @@ dependencies = [ "noxis-core", "noxis-runtime", "noxis-structure-check", + "serde_json", "thiserror", "tracing", ] diff --git a/NOTICE.md b/NOTICE.md index b059baf..7451839 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -1,8 +1,8 @@ -# NOTICE — сторонние компоненты +# NOTICE - сторонние компоненты Проект `noxis` распространяется по лицензии AGPL-3.0-only (см. [`LICENSE`](LICENSE)). -Ниже — компоненты third-party, которые используются напрямую и чьи +Ниже - компоненты third-party, которые используются напрямую и чьи лицензионные условия обязательны к сохранению. ## ristretto_classfile diff --git a/README.md b/README.md index 4d592b6..72b20a2 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ | пассы: rename, resources, strings, constants, noise, debug | ✅ | | верификация: red-паттерны, `java -Xverify:all`, метрики | ✅ | | CLI (`obfuscate` / `analyze` / `patterns`) | ✅ | -| пасс flow (кадры готовы, схем флаттенинга пока нет) | 🚧 | +| пасс flow (кадры готовы, 4 схемы: state-spread, computed-switch, butterfly, exception-goto) | ✅ | Подробности в [`docs/architecture.md`](docs/architecture.md), план в [`todo.md`](todo.md). @@ -50,12 +50,8 @@ cargo run -p noxis -- patterns --input output.jar ``` `obfuscate` по умолчанию включает все готовые пассы. Флаги `--no-rename`, -`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info` -выключают их по отдельности. `--no-flow` честно падает с ошибкой: пасса пока нет. - -Одно `cargo build` уже гоняет проверку структуры кода: `.rs`-файл длиннее -250 строк или директория с больше чем 4 `.rs`-файлами ломают сборку. -Документация (`docs/**`) под это правило не попадает. Правила в [`docs/README.md`](docs/README.md). +`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`, +`--no-flow` выключают их по отдельности. ## Структура diff --git a/crates/noxis-analysis/Cargo.toml b/crates/noxis-analysis/Cargo.toml index 40224a6..4a65dac 100644 --- a/crates/noxis-analysis/Cargo.toml +++ b/crates/noxis-analysis/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true [dependencies] regex = { workspace = true } +serde_json = { workspace = true } noxis-classfile = { workspace = true } noxis-core = { workspace = true } thiserror = { workspace = true } diff --git a/crates/noxis-analysis/src/JdkHierarchy.java b/crates/noxis-analysis/src/JdkHierarchy.java new file mode 100644 index 0000000..65f9707 --- /dev/null +++ b/crates/noxis-analysis/src/JdkHierarchy.java @@ -0,0 +1,34 @@ +import java.util.Scanner; + +/** + * Answers superclass queries from the obfuscator's frame analysis. + * + *

Protocol: one internal class name per line on stdin + * ({@code java/io/BufferedReader}); one line back on stdout - the direct + * superclass as an internal name, or an empty line when unknown + * (missing dependency, interface, primitive, array). A single process + * serves the whole analysis run; EOF on stdin ends it. + */ +public class JdkHierarchy { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + while (in.hasNextLine()) { + String name = in.nextLine().trim().replace('/', '.'); + String sup = ""; + if (!name.isEmpty()) { + try { + Class loaded = + Class.forName(name, false, JdkHierarchy.class.getClassLoader()); + Class parent = loaded.getSuperclass(); + if (parent != null) { + sup = parent.getName().replace('.', '/'); + } + } catch (Throwable ignored) { + // Unknown: not on the JDK classpath, an interface with + // no superclass, a primitive or an array - empty line. + } + } + System.out.println(sup); + } + } +} diff --git a/crates/noxis-analysis/src/entrypoints.rs b/crates/noxis-analysis/src/entrypoints.rs index f559d1f..93349c0 100644 --- a/crates/noxis-analysis/src/entrypoints.rs +++ b/crates/noxis-analysis/src/entrypoints.rs @@ -24,7 +24,7 @@ pub struct Entrypoints { } impl Entrypoints { - /// Собрать entrypoint'ы по программе (без keep-правил — их добавляет [`Self::merge`]). + /// Собрать entrypoint'ы по программе (без keep-правил - их добавляет [`Self::merge`]). pub fn collect(program: &Program) -> Self { let mut out = Self::default(); @@ -101,7 +101,7 @@ fn implements_serializable(program: &Program, start: &str) -> bool { return true; } let Some(class) = program.class(&name) else { - // Внешний предок: считаем, что не знаем — консервативно не keep'им. + // Внешний предок: считаем, что не знаем - консервативно не keep'им. continue; }; if let Some(sup) = &class.super_class { @@ -130,15 +130,15 @@ fn collect_service_interfaces(program: &Program) -> BTreeSet { /// Линейный эвристический поиск имён в рефлексивных API. /// /// Полноценный dataflow не нужен: если рядом с вызовом `Class.forName(...)` / -/// `getMethod(...)` лежит строковый литерал — это имя видно статически, +/// `getMethod(...)` лежит строковый литерал - это имя видно статически, /// значит, его нельзя переименовывать. fn collect_reflective_names(out: &mut Entrypoints, code: &noxis_classfile::Code) { - /// API, чьи аргументы — **имена классов**. + /// API, чьи аргументы - **имена классов**. const CLASS_API: &[(&str, &str)] = &[ ("java/lang/Class", "forName"), ("java/lang/ClassLoader", "loadClass"), ]; - /// API, чьи аргументы — **имена членов** (поле/метод). + /// API, чьи аргументы - **имена членов** (поле/метод). const MEMBER_API: &[(&str, &str)] = &[ ("java/lang/Class", "getMethod"), ("java/lang/Class", "getDeclaredMethod"), diff --git a/crates/noxis-analysis/src/hierarchy.rs b/crates/noxis-analysis/src/hierarchy.rs index 6a57ea1..b982d8f 100644 --- a/crates/noxis-analysis/src/hierarchy.rs +++ b/crates/noxis-analysis/src/hierarchy.rs @@ -40,7 +40,7 @@ impl ClassHierarchy { .and_then(|n| n.super_class.clone()) } - /// Есть ли класс в иерархии (в том числе из внешнего classpath — нет). + /// Есть ли класс в иерархии (в том числе из внешнего classpath - нет). pub fn contains(&self, internal_name: &str) -> bool { self.nodes.contains_key(internal_name) } @@ -57,7 +57,7 @@ impl ClassHierarchy { /// Является ли `child` подклассом `parent` (в пределах программы). /// - /// Неполная иерархия (внешние зависимости не грузим) — это осознанно: + /// Неполная иерархия (внешние зависимости не грузим) - это осознанно: /// обфускатор работает по артефакту, а не по всему classpath. pub fn is_subclass_of(&self, child: &str, parent: &str) -> bool { if child == parent { @@ -137,10 +137,10 @@ pub enum RenameSafety { /// Оценка безопасности переименования метода. /// /// Правила (сознательно консервативные, как в `OBF/InheritanceAnalyzer`): -/// - ``/`` — никогда; -/// - `private`/`static`/`final`/`` внутри финального класса — можно; +/// - ``/`` - никогда; +/// - `private`/`static`/`final`/`` внутри финального класса - можно; /// - `public`/`protected`/`package-private`, если класс не `final` и есть -/// наследники (внутри артефакта или нет) — нельзя, пока нет доказательства. +/// наследники (внутри артефакта или нет) - нельзя, пока нет доказательства. pub fn method_rename_safety( program: &Program, hierarchy: &ClassHierarchy, diff --git a/crates/noxis-analysis/src/jdk.rs b/crates/noxis-analysis/src/jdk.rs new file mode 100644 index 0000000..1e10d95 --- /dev/null +++ b/crates/noxis-analysis/src/jdk.rs @@ -0,0 +1,195 @@ +//! JDK superclass fallback for frame merging. +//! +//! [`ClassHierarchy`] only knows program classes - deliberately so: rename +//! safety must stay conservative outside the program. Frame merging has the +//! opposite need: joins over JDK types (`Reader`/`BufferedReader`, a +//! multi-catch over `NoSuchMethodException`/`SecurityException`) degrade to +//! `Object` without the true superclass chain, and the verifier rejects the +//! poisoned frame at the first typed use (`putfield Reader`, a `Throwable` +//! parameter). This wrapper answers program classes from the built +//! hierarchy and asks the running JDK about the rest: one `java` process +//! (single-file launch, no `javac` needed), a line protocol, answers cached. +//! Without `java` every answer is `None` - exactly the old behaviour. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::io::{BufRead, BufReader, BufWriter, Write}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; + +use noxis_classfile::Hierarchy; + +use super::hierarchy::ClassHierarchy; + +const HELPER: &str = include_str!("JdkHierarchy.java"); + +/// Frame-time hierarchy: program first, running JDK second. +pub struct JdkHierarchy<'a> { + inner: &'a ClassHierarchy, + shared: RefCell, +} + +#[derive(Default)] +struct Shared { + cache: HashMap>, + child: Option, + dead: bool, +} + +struct Pipes { + rx: BufReader, + tx: BufWriter, + proc: Child, +} + +impl<'a> JdkHierarchy<'a> { + /// Wrap a built program hierarchy (spawns nothing yet). + pub fn wrap(inner: &'a ClassHierarchy) -> Self { + Self { + inner, + shared: RefCell::new(Shared::default()), + } + } + + fn jdk_superclass(&self, name: &str) -> Option { + let mut shared = self.shared.borrow_mut(); + if let Some(cached) = shared.cache.get(name) { + return cached.clone(); + } + if shared.dead { + return None; + } + if shared.child.is_none() { + match spawn_helper() { + Some(pipes) => shared.child = Some(pipes), + None => { + shared.dead = true; + return None; + } + } + } + let answer = match query(shared.child.as_mut(), name) { + // Transport broke: stop spawning, keep the old behaviour. + None => { + shared.dead = true; + return None; + } + Some(answer) => answer, + }; + shared.cache.insert(name.to_string(), answer.clone()); + answer + } +} + +impl Hierarchy for JdkHierarchy<'_> { + fn superclass(&self, class: &str) -> Option { + match self.inner.superclass(class) { + Some(known) => Some(known), + None => self.jdk_superclass(class), + } + } +} + +impl Drop for JdkHierarchy<'_> { + fn drop(&mut self) { + if let Ok(mut shared) = self.shared.try_borrow_mut() + && let Some(mut pipes) = shared.child.take() + { + let _ = pipes.proc.kill(); + let _ = pipes.proc.wait(); + } + } +} + +/// Whether a `java` runtime exists for the helper. +fn java_available() -> bool { + Command::new("java") + .arg("-version") + .output() + .is_ok_and(|out| out.status.success()) +} + +/// Write the helper next to itself atomically-ish (every writer emits +/// identical bytes) and launch it; a handshake query proves it runs. +fn spawn_helper() -> Option { + if !java_available() { + return None; + } + let path = std::env::temp_dir().join("noxis-jdk-hierarchy.java"); + let staging = path.with_extension(format!("java.{}", std::process::id())); + std::fs::write(&staging, HELPER).ok()?; + std::fs::rename(&staging, &path).ok()?; + let mut proc = Command::new("java") + .arg(&path) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let rx = BufReader::new(proc.stdout.take()?); + let tx = BufWriter::new(proc.stdin.take()?); + let mut pipes = Pipes { rx, tx, proc }; + // Handshake: `Object` has no superclass; any answer at all means a wrong + // runtime (or no source-launch support) - stay silent instead. + match query(Some(&mut pipes), "java/lang/Object") { + // The child must still be alive: EOF also reads as an empty line. + Some(None) if pipes.proc.try_wait().is_ok_and(|exit| exit.is_none()) => Some(pipes), + _ => None, + } +} + +/// One round trip: `None` - dead transport (child reaped); +/// `Some(answer)` - the reply, empty string for unknown superclasses. +fn query(pipes: Option<&mut Pipes>, name: &str) -> Option> { + let pipes = pipes?; + if writeln!(pipes.tx, "{name}").is_err() || pipes.tx.flush().is_err() { + kill(pipes); + return None; + } + let mut line = String::new(); + if pipes.rx.read_line(&mut line).is_err() { + kill(pipes); + return None; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + return Some(None); + } + Some(Some(trimmed.to_string())) +} + +fn kill(pipes: &mut Pipes) { + let _ = pipes.proc.kill(); + let _ = pipes.proc.wait(); +} + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used, clippy::unwrap_used)] + + use noxis_classfile::Program; + + use super::*; + + #[test] + fn jdk_superclasses_come_from_the_runtime() { + if !java_available() { + eprintln!("SKIP: no java"); + return; + } + let program = Program::default(); + let base = ClassHierarchy::build(&program); + let jdk = JdkHierarchy::wrap(&base); + // Real, stable JDK facts (unchanged for decades). + assert_eq!( + jdk.superclass("java/io/BufferedReader"), + Some("java/io/Reader".to_string()) + ); + assert_eq!( + jdk.superclass("java/lang/NoSuchMethodException"), + Some("java/lang/ReflectiveOperationException".to_string()) + ); + assert_eq!(jdk.superclass("java/lang/Object"), None); + // Outside the JDK: honest miss, like before. + assert_eq!(jdk.superclass("demo/Nope"), None); + } +} diff --git a/crates/noxis-analysis/src/keep/dispatch.rs b/crates/noxis-analysis/src/keep/dispatch.rs new file mode 100644 index 0000000..22e3c57 --- /dev/null +++ b/crates/noxis-analysis/src/keep/dispatch.rs @@ -0,0 +1,86 @@ +//! Внешний диспатч: семейства методов, которые программный код зовёт через +//! внешние интерфейсы/классы (не из артефакта). Их нельзя переименовывать - +//! внешний вызывающий код не переписать, и JVM получит `AbstractMethodError`. + +use std::collections::{BTreeSet, HashSet}; + +use noxis_classfile::{Insn, InvokeKind, Program}; + +use crate::hierarchy::ClassHierarchy; + +/// Семейства `(name, params)`, которые нельзя переименовывать: программа +/// вызывает их виртуально/интерфейсно на внешнем владельце, а некоторый +/// класс в предках этого владельца (внутри артефакта) объявляет то же +/// `(name, params)`. Переименование разорвало бы диспатч через внешний +/// интерфейс/класс - JVM упала бы с `AbstractMethodError ... is abstract` +/// (реальный случай: шадоуed gson `LinkedTreeMap$EntrySet$1`, который +/// JDK `Map.forEach` зовёт через `invokeinterface Iterator.hasNext`). +pub fn external_dispatch_families( + program: &Program, + hierarchy: &ClassHierarchy, +) -> BTreeSet<(String, String)> { + let in_program: HashSet<&str> = program + .classes + .iter() + .map(|c| c.this_class.as_str()) + .collect(); + + // Виртуальные/интерфейсные вызовы на внешнем владельце (дедуплицированно). + let mut external_calls: BTreeSet<(String, String, String)> = BTreeSet::new(); + for class in &program.classes { + for method in &class.methods { + let Some(code) = &method.code else { continue }; + for insn in &code.insns { + if let Insn::Invoke { + kind, + owner, + name, + descriptor, + .. + } = insn + && matches!(kind, InvokeKind::Virtual | InvokeKind::Interface) + && !in_program.contains(owner.as_str()) + && let Some(params) = params_part(descriptor) + { + external_calls.insert((owner.clone(), name.clone(), params.to_string())); + } + } + } + } + if external_calls.is_empty() { + return BTreeSet::new(); + } + + // Для каждого класса - внешние предки, достижимые сквозь внутренние + // суперклассы/интерфейсы (цепочка обрывается на внешнем узле). + let mut locked: BTreeSet<(String, String)> = BTreeSet::new(); + for class in &program.classes { + let mut externals: HashSet = HashSet::new(); + let mut seen: HashSet = HashSet::new(); + let mut stack = hierarchy.parents(&class.this_class); + while let Some(name) = stack.pop() { + if in_program.contains(name.as_str()) { + if seen.insert(name.clone()) { + stack.extend(hierarchy.parents(&name)); + } + } else { + externals.insert(name); + } + } + for (owner, name, params) in &external_calls { + if externals.contains(owner) { + locked.insert((name.clone(), params.clone())); + } + } + } + locked +} + +/// `()` → `()`, или `None` при кривом дескрипторе. +fn params_part(descriptor: &str) -> Option<&str> { + let close = descriptor.find(')')?; + if !descriptor.starts_with('(') { + return None; + } + Some(&descriptor[..=close]) +} diff --git a/crates/noxis-analysis/src/keep.rs b/crates/noxis-analysis/src/keep/mod.rs similarity index 51% rename from crates/noxis-analysis/src/keep.rs rename to crates/noxis-analysis/src/keep/mod.rs index bdb9ad2..498b9b5 100644 --- a/crates/noxis-analysis/src/keep.rs +++ b/crates/noxis-analysis/src/keep/mod.rs @@ -1,12 +1,19 @@ -//! Keep-правила: что нельзя переименовывать (glob-паттерны + entrypoint'ы). +//! Keep rules: what must not be renamed (glob patterns + entrypoints). -use noxis_classfile::{Attribute, Const, Program}; +use std::collections::BTreeSet; + +use noxis_classfile::Program; use regex::Regex; use crate::entrypoints::Entrypoints; use noxis_core::Config; -/// Скомпилированный glob: `*` — любые символы кроме `/`, `**` — всё, `?` — один. +mod dispatch; +mod scans; + +pub use dispatch::external_dispatch_families; + +/// Compiled glob: `*` - anything but `/`, `**` - anything, `?` - one char. fn compile(pattern: &str) -> Result { let mut out = String::from("^"); let chars: Vec = pattern.chars().collect(); @@ -36,19 +43,19 @@ fn compile(pattern: &str) -> Result { Regex::new(&out) } -/// Правила «не трогать»: явные паттерны конфига + entrypoint'ы. +/// "Do not touch" rules: explicit config patterns + entrypoints. #[derive(Debug, Default, Clone)] pub struct KeepRules { class_patterns: Vec, resource_patterns: Vec, - /// Точные имена, которые нельзя трогать (entrypoint'ы, рефлексия, ...). - fixed: std::collections::BTreeSet, - /// Имена членов, защищённые рефлексией. - fixed_members: std::collections::BTreeSet, + /// Exact names to keep (entrypoints, reflection, ...). + fixed: BTreeSet, + /// Member names protected by reflection. + fixed_members: BTreeSet, } impl KeepRules { - /// Собрать правила из конфига. + /// Build the rules from the config. pub fn from_config(config: &Config) -> Result { let mut class_patterns = Vec::with_capacity(config.keep.len()); for pattern in &config.keep { @@ -67,22 +74,22 @@ impl KeepRules { Ok(Self { class_patterns, resource_patterns, - fixed: std::collections::BTreeSet::new(), - fixed_members: std::collections::BTreeSet::new(), + fixed: BTreeSet::new(), + fixed_members: BTreeSet::new(), }) } - /// Запретить переименование члена с таким именем (в любом классе). + /// Forbid renaming a member with this name (in any class). pub fn keep_member(&mut self, name: impl Into) { self.fixed_members.insert(name.into()); } - /// Добавить точное имя класса (из анализа программы). + /// Add an exact class name (from program analysis). pub fn keep_exact(&mut self, internal_name: impl Into) { self.fixed.insert(internal_name.into()); } - /// Объединить с найденными entrypoint'ами. + /// Absorb found entrypoints. pub fn absorb(&mut self, entrypoints: &Entrypoints) { for name in &entrypoints.main_classes { self.keep_exact(name.clone()); @@ -104,30 +111,7 @@ impl KeepRules { } } - /// Методы, на которые ссылаются `BootstrapMethods` (`invokedynamic`). - /// - /// Переименование такого метода без правки bootstrap-записи ломает класс, - /// а правка — задача P2 (см. `todo.md`): пока просто не трогаем имена. - pub fn absorb_bootstrap(&mut self, program: &Program) { - for class in &program.classes { - for method in &class.methods { - for attr in &method.attributes { - if let Attribute::BootstrapMethods(methods) = attr { - for bsm in methods { - self.keep_member(bsm.name.clone()); - for arg in &bsm.args { - if let Const::MethodHandle { name, .. } = arg { - self.keep_member(name.clone()); - } - } - } - } - } - } - } - } - - /// Нужно ли оставить класс с данным внутренним именем. + /// Whether the class with this internal name stays. pub fn keeps_class(&self, internal_name: &str) -> bool { self.fixed.contains(internal_name) || self @@ -136,17 +120,17 @@ impl KeepRules { .any(|re| re.is_match(internal_name)) } - /// Нужно ли оставить член с таким именем (не переименовывать). + /// Whether a member with this name stays (is not renamed). pub fn keeps_member(&self, name: &str) -> bool { self.fixed_members.contains(name) } - /// Нужно ли оставить ресурс с данным путём. + /// Whether the resource at this path stays unrewritten. pub fn keeps_resource(&self, path: &str) -> bool { self.resource_patterns.iter().any(|re| re.is_match(path)) } - /// Число правил (для отчёта). + /// Rule count (for the report). pub fn len(&self) -> usize { self.class_patterns.len() + self.resource_patterns.len() @@ -154,35 +138,37 @@ impl KeepRules { + self.fixed_members.len() } - /// Есть ли вообще правила. + /// Whether there are any rules at all. pub fn is_empty(&self) -> bool { self.len() == 0 } } -/// Ошибка компиляции паттерна. +/// A pattern compilation error. #[derive(Debug, thiserror::Error)] pub enum RuleError { - #[error("некорректный паттерн `{pattern}`: {msg}")] + #[error("malformed pattern `{pattern}`: {msg}")] Pattern { pattern: String, msg: String }, } -/// Полный анализ перед обфускацией. +/// The full pre-obfuscation analysis. #[derive(Debug, Clone)] pub struct Analysis { pub entrypoints: Entrypoints, pub keep: KeepRules, - /// Классы, которые не переименовываются. - pub locked_classes: std::collections::BTreeSet, + /// Classes that are not renamed. + pub locked_classes: BTreeSet, } impl Analysis { - /// Прогнать весь анализ по программе. + /// Run the whole analysis over the program. pub fn run(program: &Program, config: &Config) -> Result { let entrypoints = Entrypoints::collect(program); let mut keep = KeepRules::from_config(config)?; keep.absorb(&entrypoints); keep.absorb_bootstrap(program); + keep.absorb_databind(program); + keep.absorb_mixins(program); let locked_classes = program .classes @@ -198,40 +184,8 @@ impl Analysis { }) } - /// Класс запрещено переименовывать. + /// Renaming this class is forbidden. pub fn is_locked(&self, internal_name: &str) -> bool { self.locked_classes.contains(internal_name) } } - -#[cfg(test)] -mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] - use super::*; - - #[test] - fn glob_semantics() { - let rules = KeepRules { - class_patterns: vec![ - compile("com/example/*").unwrap(), - compile("**/internal/**").unwrap(), - ], - resource_patterns: vec![compile("META-INF/services/*").unwrap()], - fixed: std::collections::BTreeSet::new(), - fixed_members: std::collections::BTreeSet::new(), - }; - assert!(rules.keeps_class("com/example/Main")); - assert!(!rules.keeps_class("com/example/sub/Main")); - assert!(rules.keeps_class("x/internal/y/Z")); - assert!(rules.keeps_resource("META-INF/services/a.b.C")); - assert!(!rules.keeps_resource("assets/mc/mod.json")); - } - - #[test] - fn exact_names_win() { - let mut rules = KeepRules::default(); - rules.keep_exact("app/Main"); - assert!(rules.keeps_class("app/Main")); - assert!(!rules.keeps_class("app/Other")); - } -} diff --git a/crates/noxis-analysis/src/keep/scans.rs b/crates/noxis-analysis/src/keep/scans.rs new file mode 100644 index 0000000..0ce16a6 --- /dev/null +++ b/crates/noxis-analysis/src/keep/scans.rs @@ -0,0 +1,204 @@ +//! Program scans feeding keep rules: bootstrap methods, databind literals, mixins. + +use noxis_classfile::{Attribute, Const, Insn, Program}; + +use super::KeepRules; + +impl KeepRules { + /// Methods referenced by `BootstrapMethods` (`invokedynamic`). + /// + /// Renaming such a method without patching the bootstrap record breaks + /// the class, and patching is a P2 task (see `todo.md`): keep the names. + pub fn absorb_bootstrap(&mut self, program: &Program) { + for class in &program.classes { + for method in &class.methods { + for attr in &method.attributes { + if let Attribute::BootstrapMethods(methods) = attr { + for bsm in methods { + self.keep_member(bsm.name.clone()); + for arg in &bsm.args { + if let Const::MethodHandle { name, .. } = arg { + self.keep_member(name.clone()); + } + } + } + } + } + } + } + } + + /// Lock every Mixin class (and the plugin) listed in the configs. + /// + /// The Mixin framework resolves mixin classes and their members by name + /// at runtime, so renaming them breaks the mod at startup. Locking the + /// class also freezes its members (locked classes skip member renaming + /// entirely), which the `@Accessor`/`@Invoker`/`@Overwrite` name lookups + /// and `IMixinConfigPlugin.shouldApplyMixin` string sets both need. + /// + /// Renaming mixins and patching the config was tried and reverted: when + /// obfuscated packages are randomized per class the config patcher writes + /// an empty `package`, and Fabric/Mixin drops every mixin as "orphaned" + /// (real case: injected-interface cast fails with `ClassCastException`). + /// Entries use simple names relative to `package`, which generic text + /// patching can never see - locking is the only sound answer. Mixin + /// configs are found two ways: any resource ending in `mixins.json`, + /// plus whatever `fabric.mod.json` lists. + pub fn absorb_mixins(&mut self, program: &Program) { + let mut listed: Vec = Vec::new(); + for resource in &program.resources { + if !resource.path.ends_with("fabric.mod.json") { + continue; + } + if let Ok(text) = std::str::from_utf8(&resource.data) { + listed.extend(mixin_config_names(text)); + } + } + for resource in &program.resources { + let is_mixins = resource.path.ends_with("mixins.json"); + let is_listed = listed.iter().any(|name| resource.path.ends_with(name)); + if !is_mixins && !is_listed { + continue; + } + if let Ok(text) = std::str::from_utf8(&resource.data) { + for class in mixin_classes(text) { + if program.class(&class).is_some() { + self.keep_exact(class); + } + } + } + } + } + + /// Lock every field of every class passed as an `X.class` literal to a + /// databinding call. Gson/Jackson bind fields by reflection from the + /// literal; renaming them silently breaks deserialization, while the + /// class itself (never named in JSON) still renames freely. + pub fn absorb_databind(&mut self, program: &Program) { + for class in &program.classes { + for method in &class.methods { + let Some(code) = method.code.as_ref() else { + continue; + }; + for (index, insn) in code.insns.iter().enumerate() { + let Insn::Invoke { owner, name, .. } = insn else { + continue; + }; + if !is_databind_call(owner, name) { + continue; + } + if let Some(dto) = nearest_class_literal(&code.insns[..index]) + && let Some(dto_class) = program.class(&dto) + { + for field in &dto_class.fields { + self.keep_member(field.name.clone()); + } + } + } + } + } + } +} + +/// Databinding entry points: `(owner, method names)` taking a `Class` literal. +/// Gson, Jackson, fastjson2 and Moshi bind DTO fields by reflection from +/// `X.class`, with no field-name string for the string-based detection. +const DATABIND_CALLS: [(&str, &[&str]); 5] = [ + ("com/google/gson/Gson", &["fromJson"]), + ( + "com/fasterxml/jackson/databind/ObjectMapper", + &["readValue", "readValues", "convertValue"], + ), + ( + "com/fasterxml/jackson/databind/ObjectReader", + &["readValue", "readValues"], + ), + ("com/alibaba/fastjson2/JSON", &["parseObject"]), + ("com/squareup/moshi/Moshi", &["adapter"]), +]; + +/// How far back an `X.class` literal may sit before the databind call. +/// Argument setup is straight-line: a few loads between the literal and the +/// call at most. +const CLASS_LITERAL_WINDOW: usize = 10; + +/// Whether an invoke is a databinding call taking a `Class` literal. +fn is_databind_call(owner: &str, name: &str) -> bool { + DATABIND_CALLS + .iter() + .any(|(candidate, names)| *candidate == owner && names.contains(&name)) +} + +/// The nearest `X.class` literal before a call site (control-flow +/// boundaries stop the search: argument setup is straight-line). +fn nearest_class_literal(before: &[Insn]) -> Option { + let start = before.len().saturating_sub(CLASS_LITERAL_WINDOW); + for insn in before[start..].iter().rev() { + match insn { + Insn::Const(Const::Class(name)) => return Some(name.clone()), + Insn::Branch(..) + | Insn::Goto(_) + | Insn::TableSwitch { .. } + | Insn::LookupSwitch { .. } + | Insn::Jsr(_) + | Insn::Ret(_) + | Insn::Return(_) + | Insn::AReturn + | Insn::AThrow => return None, + _ => {} + } + } + None +} + +/// Filenames from a `fabric.mod.json` "mixins" array. +fn mixin_config_names(text: &str) -> Vec { + let Ok(json) = serde_json::from_str::(text) else { + return Vec::new(); + }; + json.get("mixins") + .and_then(|value| value.as_array()) + .map(|items| { + items + .iter() + .filter_map(|item| item.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +/// Mixin classes (internal names) from one mixins config. +/// +/// Entries may be simple (relative to `package`) or already qualified; +/// both spellings are returned and the caller keeps whichever exists. +/// The `plugin` class is included the same way. +fn mixin_classes(text: &str) -> Vec { + let Ok(json) = serde_json::from_str::(text) else { + return Vec::new(); + }; + let package = json + .get("package") + .and_then(|value| value.as_str()) + .unwrap_or("") + .replace('.', "/"); + let mut out = Vec::new(); + let push = |entry: &str, out: &mut Vec| { + out.push(entry.replace('.', "/")); + if !package.is_empty() { + out.push(format!("{package}/{}", entry.replace('.', "/"))); + } + }; + for key in ["mixins", "client", "server"] { + if let Some(items) = json.get(key).and_then(|value| value.as_array()) { + for item in items { + if let Some(entry) = item.as_str() { + push(entry, &mut out); + } + } + } + } + if let Some(plugin) = json.get("plugin").and_then(|value| value.as_str()) { + push(plugin, &mut out); + } + out +} diff --git a/crates/noxis-analysis/src/lib.rs b/crates/noxis-analysis/src/lib.rs index fb6fac5..21d9318 100644 --- a/crates/noxis-analysis/src/lib.rs +++ b/crates/noxis-analysis/src/lib.rs @@ -5,13 +5,15 @@ //! //! Из этих данных пасс переименования узнаёт, **что** трогать нельзя. //! Урок из `info/evo-weaknesses.md`: у EvoVis рефлексия по имени была -//! открытым текстом, а entrypoint'ы — в `fabric.mod.json`; здесь они +//! открытым текстом, а entrypoint'ы - в `fabric.mod.json`; здесь они //! обязаны попадать в keep-набор автоматически. pub mod entrypoints; pub mod hierarchy; +pub mod jdk; pub mod keep; pub use entrypoints::Entrypoints; pub use hierarchy::{ClassHierarchy, RenameSafety, method_rename_safety}; -pub use keep::{Analysis, KeepRules, RuleError}; +pub use jdk::JdkHierarchy; +pub use keep::{Analysis, KeepRules, RuleError, external_dispatch_families}; diff --git a/crates/noxis-analysis/tests/dto.rs b/crates/noxis-analysis/tests/dto.rs new file mode 100644 index 0000000..ac399f4 --- /dev/null +++ b/crates/noxis-analysis/tests/dto.rs @@ -0,0 +1,70 @@ +//! Databinding keep: `X.class` passed to Gson/Jackson locks the fields of `X`. +//! +//! JSON libraries bind fields by reflection from a `Class` literal, with no +//! field-name string in the bytecode for the existing string-based detection +//! to catch. Renaming such a field silently breaks deserialization, so every +//! field of the literal's class stays. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use noxis_analysis::Analysis; +use noxis_classfile::{ClassBuilder, Code, Const, Field, Insn, InvokeKind, Program, Version}; +use noxis_core::Config; + +/// `gson.fromJson(reader, State.class)`: `State` has a private field. +fn sample() -> Program { + let caller = Code { + max_stack: 3, + max_locals: 2, + insns: vec![ + Insn::Load { + slot: 1, + kind: noxis_classfile::SlotKind::Ref, + }, + Insn::Const(Const::Class("demo/State".to_string())), + Insn::Invoke { + kind: InvokeKind::Virtual, + owner: "com/google/gson/Gson".to_string(), + name: "fromJson".to_string(), + descriptor: "(Ljava/io/Reader;Ljava/lang/Class;)Ljava/lang/Object;".to_string(), + itf: false, + }, + Insn::Pop, + Insn::Return(None), + ], + exception_table: Vec::new(), + frames: Vec::new(), + attributes: Vec::new(), + }; + let mut state = ClassBuilder::new("demo/State", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(); + state.fields.push(Field { + access_flags: 0x0002, + name: "nickname".to_string(), + descriptor: "Ljava/lang/String;".to_string(), + attributes: Vec::new(), + }); + let app = ClassBuilder::new("demo/App", Some("java/lang/Object")) + .version(Version::JAVA_21) + .method_with_code(0x0009, "load", "()V", caller) + .build(); + Program { + classes: vec![state, app], + resources: Vec::new(), + } +} + +#[test] +fn databind_class_literal_locks_fields() { + let program = sample(); + let analysis = Analysis::run(&program, &Config::default()).expect("analysis"); + assert!( + analysis.keep.keeps_member("nickname"), + "DTO field must survive renaming" + ); + assert!( + !analysis.keep.keeps_member("load"), + "unrelated members must still rename" + ); +} diff --git a/crates/noxis-analysis/tests/keep.rs b/crates/noxis-analysis/tests/keep.rs new file mode 100644 index 0000000..ecc8354 --- /dev/null +++ b/crates/noxis-analysis/tests/keep.rs @@ -0,0 +1,33 @@ +//! Keep-rule unit tests: globs and exact names. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use noxis_analysis::KeepRules; +use noxis_core::Config; + +fn rules_with_patterns() -> KeepRules { + KeepRules::from_config(&Config { + keep: vec!["com/example/*".to_string(), "**/internal/**".to_string()], + keep_resources: vec!["META-INF/services/*".to_string()], + ..Config::default() + }) + .expect("patterns") +} + +#[test] +fn glob_semantics() { + let rules = rules_with_patterns(); + assert!(rules.keeps_class("com/example/Main")); + assert!(!rules.keeps_class("com/example/sub/Main")); + assert!(rules.keeps_class("x/internal/y/Z")); + assert!(rules.keeps_resource("META-INF/services/a.b.C")); + assert!(!rules.keeps_resource("assets/mc/mod.json")); +} + +#[test] +fn exact_names_win() { + let mut rules = KeepRules::default(); + rules.keep_exact("app/Main"); + assert!(rules.keeps_class("app/Main")); + assert!(!rules.keeps_class("app/Other")); +} diff --git a/crates/noxis-analysis/tests/mixins.rs b/crates/noxis-analysis/tests/mixins.rs new file mode 100644 index 0000000..898786b --- /dev/null +++ b/crates/noxis-analysis/tests/mixins.rs @@ -0,0 +1,93 @@ +//! Mixin keep: classes listed in `*.mixins.json` are locked, not renamed. +//! +//! Real-world proof (LoVisual, 2026-10-13): renaming mixin classes and +//! patching the config breaks the mod at runtime. Two independent failures: +//! 1. When obf packages are randomized per class, the config patcher writes +//! `package: ""`, and Fabric/Mixin then drops *every* mixin as "orphaned" +//! (`RenderPipelineMixin implements IRenderPipeline` never applies, so the +//! injected-interface cast fails with `ClassCastException`). +//! 2. `IMixinConfigPlugin.shouldApplyMixin` compares the runtime mixin class +//! name against string literals (`Set.of("dev.loki...Mixin")`); renaming +//! the mixins desyncs those sets and optional mixins get applied when the +//! target mod is absent. +//! +//! So mixin classes and their plugin stay under their original names, and +//! locking the class freezes its members too - which `@Accessor`/`@Invoker`/ +//! `@Overwrite` name lookups require. Other program classes still rename, and +//! calls from locked mixin bytecode are rewritten consistently. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use noxis_analysis::Analysis; +use noxis_classfile::{ClassBuilder, Program, Resource, Version}; +use noxis_core::Config; + +const MIXINS: &str = r#"{ + "package": "demo.mixin", + "plugin": "demo.mixin.Plugin", + "mixins": ["TargetMixin", "other.Helper"], + "client": ["ClientMixin"] +}"#; + +const FABRIC: &str = r#"{ + "id": "demo", + "mixins": ["demo.mixins.json"] +}"#; + +fn sample() -> Program { + let mut program = Program { + classes: vec![ + ClassBuilder::new("demo/mixin/TargetMixin", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(), + ClassBuilder::new("demo/mixin/other/Helper", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(), + ClassBuilder::new("demo/mixin/ClientMixin", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(), + ClassBuilder::new("demo/mixin/Plugin", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(), + ClassBuilder::new("demo/App", Some("java/lang/Object")) + .version(Version::JAVA_21) + .build(), + ], + resources: Vec::new(), + }; + program.resources.push(Resource { + path: "demo.mixins.json".into(), + data: MIXINS.as_bytes().to_vec(), + }); + program.resources.push(Resource { + path: "fabric.mod.json".into(), + data: FABRIC.as_bytes().to_vec(), + }); + program +} + +#[test] +fn mixin_classes_and_plugin_are_locked() { + let program = sample(); + let analysis = Analysis::run(&program, &Config::default()).expect("analysis"); + + // Mixin entry points and the config plugin are resolved by name at + // runtime and must keep their names (and, being locked, their members). + for locked in [ + "demo/mixin/TargetMixin", + "demo/mixin/other/Helper", + "demo/mixin/ClientMixin", + "demo/mixin/Plugin", + ] { + assert!(analysis.is_locked(locked), "{locked} should be locked"); + } +} + +#[test] +fn non_mixin_classes_stay_renameable() { + let program = sample(); + let analysis = Analysis::run(&program, &Config::default()).expect("analysis"); + + // Plain program classes are not named by any mixin config. + assert!(!analysis.is_locked("demo/App")); +} diff --git a/crates/noxis-classfile/src/error.rs b/crates/noxis-classfile/src/error.rs index 28f9689..9066044 100644 --- a/crates/noxis-classfile/src/error.rs +++ b/crates/noxis-classfile/src/error.rs @@ -1,6 +1,6 @@ -//! Ошибки разбора/записи классовых файлов. +//! Errors from class-file parsing/writing. -/// Ошибка на уровне одного классового файла. +/// An error at the level of a single class file. #[derive(Debug, thiserror::Error)] pub enum ClassfileError { #[error("не удалось разобрать классовый файл: {0}")] diff --git a/crates/noxis-classfile/src/format/frames/emit.rs b/crates/noxis-classfile/src/format/frames/emit.rs index 3715578..5a95bec 100644 --- a/crates/noxis-classfile/src/format/frames/emit.rs +++ b/crates/noxis-classfile/src/format/frames/emit.rs @@ -1,8 +1,9 @@ -//! Эмиссия компактных кадров в точках, где их ждёт верификатор. +//! Emitting compact frames at the points where the verifier expects them. //! -//! Вид кадра выбирается сравнением с предыдущим кадром (`Same`/`Append`/ -//! `Chop`/`SameLocals`, иначе `Full`) — как у `javac`. Хвостовые `Top` -//! при сравнении и записи отрезаются: пустой слот — не тип. +//! A frame's kind is chosen by comparing with the previous frame +//! (`Same`/`Append`/`Chop`/`SameLocals`, otherwise `Full`) - like `javac`. +//! Trailing `Top`s are trimmed both when comparing and when writing: an empty +//! slot is not a type. use std::collections::BTreeSet; @@ -11,10 +12,10 @@ use super::xfer::State; use super::{StackMapFrame, VerificationType}; use crate::error::ClassfileError; -/// Кадры во всех точках `targets` (отсортированы — дельты по порядку). +/// Frames at every point in `targets` (sorted - deltas in order). /// -/// Дельты — в номерах инструкций (как backend после чтения); writer сам -/// пересчитает их в байты. +/// Deltas are in instruction numbers (like the backend after reading); the writer +/// recomputes them into bytes itself. pub(super) fn emit_frames( states: &[Option], targets: &BTreeSet, @@ -34,7 +35,7 @@ pub(super) fn emit_frames( Some(previous) => target .checked_sub(previous) .and_then(|delta| delta.checked_sub(1)) - .ok_or_else(|| merger.invalid("кадры не по порядку"))?, + .ok_or_else(|| merger.invalid("frames out of order"))?, }; out.push(select(delta, &state.locals, &previous_locals, &state.stack)); previous_locals = state.locals.clone(); @@ -49,17 +50,21 @@ fn select( previous: &[VerificationType], stack: &[VerificationType], ) -> StackMapFrame { - // Сравнение — на гранулярности переменных (`long` — одна запись, - // как у `javac`): иначе половины пар дают `Append{[Top, Long]}`. + // Comparison is at variable granularity (`long` - one entry, like `javac`); + // otherwise halves would produce `Append{[Top, Long]}`. let current = vars(locals); let base = vars(previous); + // The operand stack needs the same collapsing: a `long`/`double` is one + // entry (`javac` writes `[Double, Integer]`, not `[Double, Top, Integer]`); + // an explicit half without its value is rejected by HotSpot. + let stack = stack_vars(stack); if current == base { if stack.is_empty() { return StackMapFrame::Same { offset_delta: delta, }; } - if let [local] = stack { + if let [local] = stack.as_slice() { return StackMapFrame::SameLocals { offset_delta: delta, local: local.clone(), @@ -93,10 +98,34 @@ fn select( } } -/// Слоты → переменные: `[Long, Top]` — одна запись; хвостовые `Top` — прочь. +/// Stack entries → values: `[Double, Top]` - one entry (like `javac`). /// -/// Одиночные `Top` внутри (дыры) сохраняются: в `Full` это легальный тип, -/// а в `Append` мы их не пускаем (см. `select`). +/// Unlike [`vars`], no trailing-`Top` trimming: every stack entry is live by +/// construction, and dropping one would corrupt the depth. +fn stack_vars(stack: &[VerificationType]) -> Vec { + let mut out = Vec::with_capacity(stack.len()); + let mut index = 0; + while index < stack.len() { + match &stack[index] { + VerificationType::Long | VerificationType::Double + if stack.get(index + 1) == Some(&VerificationType::Top) => + { + out.push(stack[index].clone()); + index += 2; + } + other => { + out.push(other.clone()); + index += 1; + } + } + } + out +} + +/// Slots → variables: `[Long, Top]` - one entry; trailing `Top`s - gone. +/// +/// Single `Top`s inside (holes) are kept: in `Full` they are a legal type, and we +/// don't allow them in `Append` (see `select`). fn vars(locals: &[VerificationType]) -> Vec { let mut out = Vec::with_capacity(locals.len()); let mut index = 0; diff --git a/crates/noxis-classfile/src/format/frames/flow.rs b/crates/noxis-classfile/src/format/frames/flow.rs index 7a10222..2c98496 100644 --- a/crates/noxis-classfile/src/format/frames/flow.rs +++ b/crates/noxis-classfile/src/format/frames/flow.rs @@ -1,4 +1,4 @@ -//! CFG тела метода: метки, рёбра, точки кадров, диапазоны handler'ов. +//! A method body's CFG: labels, edges, frame points, handler ranges. use std::collections::{BTreeMap, BTreeSet}; @@ -7,7 +7,7 @@ use crate::error::ClassfileError; use crate::insn::{Insn, Label}; use crate::model::ExceptionHandler; -/// Метки → номера инструкций без маркеров. +/// Labels → instruction numbers, without the markers. pub(super) fn strip_marks<'a>( insns: &'a [Insn], merger: &Merger<'_>, @@ -31,7 +31,7 @@ pub(super) fn strip_marks<'a>( Ok((labels, bare)) } -/// Рёбра CFG без исключений: продолжение + цели переходов. +/// CFG edges without exceptions: fallthrough + branch targets. pub(super) fn successors( insn: &Insn, index: u32, @@ -40,8 +40,8 @@ pub(super) fn successors( merger: &Merger<'_>, ) -> Result, ClassfileError> { let mut out = Vec::new(); - // Без продолжения: переходы без возврата и выходы из метода. - // `Jsr`/`Ret` сюда не доходят (их отвергает `transfer`), но рёбра есть. + // No fallthrough: jumps that don't return and method exits. + // `Jsr`/`Ret` never reach here (rejected by `transfer`), but the edges exist. let terminal = matches!( insn, Insn::Goto(..) @@ -67,7 +67,7 @@ pub(super) fn successors( Ok(out) } -/// Точки, где верификатор требует кадры: цели переходов + входы handler'ов. +/// Points where the verifier requires frames: branch targets + handler entries. pub(super) fn frame_targets( bare: &[&Insn], labels: &BTreeMap, @@ -91,12 +91,12 @@ pub(super) fn frame_targets( Ok(targets) } -/// Точка handler'а в номерах инструкций: `(start, end, handler, тип перехвата)`. +/// A handler point in instruction numbers: `(start, end, handler, catch type)`. /// -/// Диапазоны полуоткрытые `[start, end)`, как в JVMS. +/// Ranges are half-open `[start, end)`, as in the JVMS. pub(super) type HandlerRange = (u32, u32, u32, Option); -/// Handler'ы в номерах инструкций для рёбер исключений. +/// Handlers in instruction numbers, for exception edges. pub(super) fn handler_ranges( table: &[ExceptionHandler], labels: &BTreeMap, diff --git a/crates/noxis-classfile/src/format/frames/merge/descs.rs b/crates/noxis-classfile/src/format/frames/merge/descs.rs index dd9c243..e978c7b 100644 --- a/crates/noxis-classfile/src/format/frames/merge/descs.rs +++ b/crates/noxis-classfile/src/format/frames/merge/descs.rs @@ -1,12 +1,12 @@ -//! Разбор дескрипторов типов (`(...)V`, `[L...;`). +//! Descriptor parsing (`(...)V`, `[L...;`). use super::super::VerificationType; -/// Ошибка разбора дескриптора (контекст добавляет вызывающий код). +/// Descriptor parse error (context is added by the caller). #[derive(Debug)] pub(crate) struct DescError(pub String); -/// Уложить слоты значения в locals с позиции; вернуть следующую позицию. +/// Write value slots into `locals` at position; return next position. pub(crate) fn write_local( locals: &mut [VerificationType], slot: usize, @@ -22,7 +22,7 @@ pub(crate) fn write_local( Ok(slot + width) } -/// Разобрать дескриптор массива на (глубина, элемент без `;`). +/// Parse an array descriptor into (depth, element without `;`). pub(crate) fn split_array(descriptor: &str) -> Option<(usize, &str)> { let dims = descriptor.bytes().take_while(|&b| b == b'[').count(); if dims == 0 { @@ -31,7 +31,7 @@ pub(crate) fn split_array(descriptor: &str) -> Option<(usize, &str)> { Some((dims, descriptor[dims..].trim_end_matches(';'))) } -/// Слоты одного полевого дескриптора (`long`/`double` — парой с `Top`). +/// Slots for a single field descriptor (`long`/`double` - pair with `Top`). pub(crate) fn field_slots(descriptor: &str) -> Result, DescError> { let mut chars = descriptor.chars(); match chars.next() { @@ -57,10 +57,10 @@ pub(crate) fn field_slots(descriptor: &str) -> Result, Des } } -/// Слоты параметров и возврата (`None` — `void`). +/// Parameter and return slots (`None` - `void`). type MethodSlots = (Vec>, Option>); -/// Дескриптор метода: слоты параметров и слоты возврата (`None` — `void`). +/// Method descriptor: parameter slots and return slots (`None` - `void`). pub(crate) fn method_slots(descriptor: &str) -> Result { let (params, ret) = descriptor .split_once('(') @@ -128,24 +128,43 @@ pub(crate) fn method_slots(descriptor: &str) -> Result { Ok((out, ret)) } -/// Тип элемента по дескриптору массива в стеке. +/// Element type from an array descriptor on the stack. +/// +/// A `Null` arrayref throws (`NullPointerException`) - no value flows from +/// it, so `Null` (bottom) is the precise answer for reference loads. +/// Yielding `Object` instead poisons downstream joins permanently: the +/// poison arrives through transient worklist states (before upstream slots +/// refine) and `lub(Object, X)` can never narrow back. Primitive loads stay +/// exact: the opcode determines the result regardless of the arrayref. pub(crate) fn array_element( array: &VerificationType, kind: crate::insn::ArrayKind, ) -> VerificationType { + use crate::format::VerificationType::Null; use crate::insn::ArrayKind::{Boolean, Byte, Char, Double, Float, Int, Long, Reference, Short}; + if *array == Null && kind == Reference { + return Null; + } if let VerificationType::Object(descriptor) = array && let Some((dims, elem)) = split_array(descriptor) { if dims > 1 { return VerificationType::Object(descriptor[1..].to_string()); } + // `split_array` keeps the `L` prefix and trims `;`: a one-dimensional + // reference array yields its element as an internal name. Returning + // the array itself here poisoned every downstream join (the reported + // `... is not assignable to [;` family). return match elem { "Z" | "B" | "C" | "S" | "I" => VerificationType::Integer, "J" => VerificationType::Long, "F" => VerificationType::Float, "D" => VerificationType::Double, - _ => VerificationType::Object(format!("[{elem};")), + _ => VerificationType::Object( + elem.strip_prefix('L') + .unwrap_or("java/lang/Object") + .to_string(), + ), }; } match kind { diff --git a/crates/noxis-classfile/src/format/frames/merge/mod.rs b/crates/noxis-classfile/src/format/frames/merge/mod.rs index 28c3c20..fc82fc4 100644 --- a/crates/noxis-classfile/src/format/frames/merge/mod.rs +++ b/crates/noxis-classfile/src/format/frames/merge/mod.rs @@ -1,12 +1,12 @@ -//! Слияние типов (LUB) и разбор дескрипторов. +//! Type merging (LUB) and descriptor parsing. //! -//! Решётка: `Top` — «пусто» (берётся сосед), `Null` впитывается в ссылку, -//! одинаковые — сами в себя, ссылки — наименьший общий предок по иерархии. -//! Несочетаемые инициализированные типы (`int` vs ссылка после `astore` -//! в handler'е) дают `Top`, как обрезанные кадры `javac`: `Top` в кадре -//! принимает любое фактическое значение, поэтому это всегда sound. -//! Исключение — неинициализированные типы: их слияние означает сломанный -//! поток конструирования, здесь честная ошибка, а не молчаливый `Top`. +//! The lattice: `Top` absorbs (a slot unwritten on any inflow stays `Top`, +//! like `javac` - a precise type would reject the inflow that never wrote +//! it). `Null` is absorbed into a reference, equal types map to themselves, +//! references take the least upper bound over the hierarchy. Incompatible +//! initialized types (`int` vs a reference) yield `Top`. The exception is +//! uninitialized types: merging them means a broken construction flow - +//! here an honest error, not a silent `Top`. pub(super) mod descs; @@ -17,13 +17,13 @@ use crate::model::Method; use descs::write_local; -/// Иерархия классов для LUB: достаточно цепочки суперклассов. +/// The class hierarchy for LUB: the superclass chain is enough. pub trait Hierarchy { - /// Прямой суперкласс (`None` — `java/lang/Object` или неизвестный). + /// The direct superclass (`None` - `java/lang/Object` or unknown). fn superclass(&self, class: &str) -> Option; } -/// Контекст слияния: имена для ошибок + иерархия для LCA. +/// Merge context: names for errors + hierarchy for LCA. pub(super) struct Merger<'h> { pub class: String, pub method: String, @@ -38,7 +38,7 @@ impl Merger<'_> { } } - /// Влить входящее состояние; `true` — слот изменился. + /// Merge an incoming state; `true` - the slot changed. pub fn merge_into( &self, slot: &mut Option, @@ -61,7 +61,7 @@ impl Merger<'_> { } } - /// Начальное состояние: параметры (+ `this`) поверх `Top`. + /// The initial state: parameters (+ `this`) over `Top`. pub fn initial(&self, method: &Method, max_locals: u16) -> Result { let is_static = method.access_flags & 0x0008 != 0; let (params, _) = @@ -75,11 +75,11 @@ impl Merger<'_> { VerificationType::Object(self.class.clone()) }; slot = write_local(&mut locals, slot, vec![this]) - .map_err(|_| self.invalid("параметры не влезают в locals"))?; + .map_err(|_| self.invalid("parameters do not fit into locals"))?; } for param in params { slot = write_local(&mut locals, slot, param) - .map_err(|_| self.invalid("параметры не влезают в locals"))?; + .map_err(|_| self.invalid("parameters do not fit into locals"))?; } Ok(State { locals, @@ -89,10 +89,10 @@ impl Merger<'_> { fn lub_states(&self, first: &State, second: &State) -> Result { if first.locals.len() != second.locals.len() { - return Err(self.invalid("разная длина locals при слиянии")); + return Err(self.invalid("locals length differs across the merge")); } if first.stack.len() != second.stack.len() { - return Err(self.invalid("разная глубина стека при слиянии")); + return Err(self.invalid("stack depth differs across the merge")); } Ok(State { locals: first @@ -120,26 +120,31 @@ impl Merger<'_> { return Ok(first.clone()); } match (first, second) { - (Top, other) | (other, Top) => Ok(other.clone()), + // A slot unwritten on any inflow stays `Top` (like `javac`): the + // frame keeps accepting every inflow, while a precise type would + // reject the one that never wrote the slot. + (Top, _) | (_, Top) => Ok(Top), (Null, other @ Object(_)) | (other @ Object(_), Null) => Ok(other.clone()), (Null, Null) => Ok(Null), (Integer, Integer) | (Float, Float) | (Long, Long) | (Double, Double) => { Ok(first.clone()) } (Object(a), Object(b)) => Ok(Object(self.common_superclass(a, b))), - // Одинаковые уже разобраны выше; здесь неинициализированные - // всегда разные — это сломанный поток конструирования. + // Equal ones are handled above; here uninitialized are always + // different - that's a broken construction flow. (VerificationType::UninitializedThis | VerificationType::Uninitialized(_), _) | (_, VerificationType::UninitializedThis | VerificationType::Uninitialized(_)) => { - Err(self.invalid("слияние неинициализированных типов")) + Err(self.invalid(&format!( + "merging uninitialized types ({first:?} with {second:?})" + ))) } - // Несочетаемые инициализированные (например, `int` из тела `try` - // и `Throwable` из handler'а в одном слоте): `Top`, как у `javac`. + // Incompatible initialized (e.g. `int` from the `try` body and + // `Throwable` from a handler in one slot): `Top`, like `javac`. _ => Ok(Top), } } - /// Наименьший общий предок: подъём по цепочкам, запасной — `Object`. + /// Least common ancestor: climb the chains, fallback - `Object`. fn common_superclass(&self, first: &str, second: &str) -> String { if first == second { return first.to_string(); @@ -176,7 +181,7 @@ impl Merger<'_> { "java/lang/Object".to_string() } - /// LCA массивов: та же размерность + LCA элементов, иначе `Object`. + /// Arrays' LCA: same dimensionality + element LCA, otherwise `Object`. fn array_lca(&self, first: &str, second: &str) -> String { let (dims_a, elem_a) = descs::split_array(first).unwrap_or((0, first)); let (dims_b, elem_b) = descs::split_array(second).unwrap_or((0, second)); diff --git a/crates/noxis-classfile/src/format/frames/mod.rs b/crates/noxis-classfile/src/format/frames/mod.rs index 07eec95..5953722 100644 --- a/crates/noxis-classfile/src/format/frames/mod.rs +++ b/crates/noxis-classfile/src/format/frames/mod.rs @@ -1,12 +1,12 @@ -//! `StackMapTable`: представление фреймов и вычисление после трансформаций. +//! `StackMapTable`: frame representation and computation after transformations. //! -//! Фреймы — самая дорогая часть любого обфускатора на Rust: JVM-верификатор -//! (class version ≥ 50) требует точного `StackMapTable`, иначе класс не грузится. -//! Варианты реализации и их цены — `docs/stack.md`. +//! Frames are the most expensive part of any Rust obfuscator: the JVM verifier +//! (class version ≥ 50) demands an exact `StackMapTable`, or the class won't load. +//! Implementation options and their costs - `docs/stack.md`. //! -//! Метод: CFG по меткам → worklist с типами (`xfer`) → слияние LUB (`merge`) -//! → эмиссия компактных кадров (`emit`). Байтовые смещения берутся тем же -//! преобразованием, что использует writer, — иначе кадры разъедутся с байтами. +//! Method: CFG over labels → worklist with types (`xfer`) → LUB merge (`merge`) +//! → emit compact frames (`emit`). Byte offsets come from the same encoding the +//! writer uses - otherwise frames would drift apart from the bytes. mod emit; mod flow; @@ -27,7 +27,7 @@ pub use merge::Hierarchy; use merge::Merger; use xfer::{State, transfer}; -/// Тип верификации из JVMS §4.10.1. +/// A verification type from JVMS §4.10.1. #[derive(Debug, Clone, PartialEq)] pub enum VerificationType { Top, @@ -37,14 +37,14 @@ pub enum VerificationType { Long, Null, UninitializedThis, - /// Внутреннее имя класса (`java/lang/Object`) или дескриптор массива. + /// The class's internal name (`java/lang/Object`) or an array descriptor. Object(String), - /// Байтовое смещение инструкции `new`. + /// The byte offset of the `new` instruction. Uninitialized(u16), } impl VerificationType { - /// Тип, соответствующий примитиву. + /// The type matching a primitive. pub fn of_prim(p: Prim) -> Self { match p { Prim::Int => VerificationType::Integer, @@ -55,7 +55,7 @@ impl VerificationType { } } -/// Запись `StackMapTable` (JVMS §4.7.4). +/// A `StackMapTable` entry (JVMS §4.7.4). #[derive(Debug, Clone, PartialEq)] pub enum StackMapFrame { Same { @@ -80,10 +80,11 @@ pub enum StackMapFrame { }, } -/// Вычислить фреймы для тела метода после всех трансформаций. +/// Compute the frames for a method body after all transformations. /// -/// Кадры нужны только классам версии ≥ 50; `jsr`/`ret` отвергаются (такие -/// классы старше и кадры им не нужны). Иерархия — для LUB ссылочных типов. +/// Frames are needed only for version ≥ 50 classes; `jsr`/`ret` are rejected +/// (such classes are older and need no frames). The hierarchy is for the LUB of +/// reference types. pub fn compute_frames( class: &str, method: &Method, @@ -112,7 +113,7 @@ pub fn compute_frames( emit::emit_frames(&states, &targets, &initial.locals, &merger) } -/// Байтовое смещение каждой инструкции — тем же кодированием, что в writer'е. +/// The byte offset of each instruction - using the same encoding as the writer. fn layout( bare: &[&Insn], labels: &BTreeMap, @@ -144,7 +145,7 @@ fn layout( .collect() } -/// Основной цикл: состояния текут по рёбрам CFG до неподвижной точки. +/// Main loop: states flow along CFG edges to a fixed point. fn run_worklist( merger: &Merger<'_>, bare: &[&Insn], @@ -187,7 +188,7 @@ fn run_worklist( Ok(()) } -/// Влить состояние в инструкцию; `true` — изменилось, продолжить обход. +/// Merge a state into an instruction; `true` - changed, keep walking. fn flow_into( merger: &Merger<'_>, states: &mut [Option], @@ -218,8 +219,8 @@ fn flow_into( Ok(()) } -/// Рёбра CFG без исключений: продолжение + цели переходов. -/// Тип исключения на входе в handler (`catch-all` — любое throwable). +/// CFG edges without exceptions: fallthrough + branch targets. +/// The exception type at a handler's entry (`catch-all` - any throwable). fn catch_type(catch: &Option) -> VerificationType { match catch { Some(name) => VerificationType::Object(name.clone()), diff --git a/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs b/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs new file mode 100644 index 0000000..773ea67 --- /dev/null +++ b/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs @@ -0,0 +1,155 @@ +//! Join-shape tests: loop heads, wide array loads, nested construction. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use super::super::super::{StackMapFrame, VerificationType, compute_frames}; +use super::super::{NoHierarchy, code_method, load_ref, store_ref}; +use crate::insn::{ArrayKind, BranchCond, Cond, Const, Insn}; +#[test] +fn anewarray_of_array_keeps_descriptor() { + let method = code_method( + "make", + "()Ljava/lang/Object;", + 2, + 1, + vec![ + Insn::Mark(0), + Insn::Const(Const::Int(3)), + Insn::ANewArray("[B".to_string()), + store_ref(0), + load_ref(0), + Insn::Branch(BranchCond::Null { is_null: false }, 1), + Insn::AconstNull, + store_ref(0), + Insn::Goto(2), + Insn::Mark(1), + Insn::Mark(2), + load_ref(0), + Insn::AReturn, + ], + vec![], + ); + let frames = compute_frames("demo/Make", &method, &NoHierarchy).expect("frames"); + assert_eq!( + frames, + vec![StackMapFrame::Append { + offset_delta: 8, + locals: vec![VerificationType::Object("[[B".to_string())], + },] + ); +} + +/// A loop head keeps `Top` for a slot written only inside the loop. +/// +/// Inflows: entry (never wrote it) and back edge (wrote `Integer`). Like +/// `javac`, the join declares `Top`: a precise type would reject the inflow +/// that never wrote the slot (`Type top is not assignable`). +/// `aaload` on a one-dimensional reference array yields the element type. +/// +/// Real-world shape (`V8ValueObject.bind` family): one join inflow carries +/// the loaded element (`Method`), the other the array itself (`Method[]`). +/// The join must declare their LUB (`Object`); declaring the array rejects +/// the element inflow (`Type ... is not assignable to ...`). +#[test] +fn aaload_on_ref_array_yields_element() { + let method = code_method( + "pick", + "([Ljava/lang/reflect/Method;)Ljava/lang/Object;", + 2, + 2, + vec![ + Insn::Mark(0), + Insn::Const(Const::Int(0)), + Insn::Branch(BranchCond::Zero(Cond::Eq), 1), + load_ref(0), + Insn::Const(Const::Int(0)), + Insn::ArrayLoad(ArrayKind::Reference), + store_ref(1), + Insn::Goto(2), + Insn::Mark(1), + load_ref(0), + store_ref(1), + Insn::Mark(2), + load_ref(1), + Insn::AReturn, + ], + vec![], + ); + let frames = compute_frames("demo/Pick", &method, &NoHierarchy).expect("frames"); + // The join declares locals[1]; whatever the frame kind, it must be the + // LUB (`Object`), never the array the other inflow carried. + let mut saw_join = false; + for frame in &frames { + let locals: Vec = match frame { + StackMapFrame::SameLocals { local, .. } => vec![local.clone()], + StackMapFrame::Append { locals, .. } | StackMapFrame::Full { locals, .. } => { + locals.clone() + } + StackMapFrame::Same { .. } | StackMapFrame::Chop { .. } => vec![], + }; + for local in &locals { + assert_ne!( + local, + &VerificationType::Object("[Ljava/lang/reflect/Method;".to_string()) + ); + if local == &VerificationType::Object("java/lang/Object".to_string()) { + saw_join = true; + } + } + } + assert!(saw_join, "expected the join LUB in {frames:?}"); +} + +/// `aaload` on a `Null` arrayref yields `Null`, not `Object`. +/// +/// The `Null` path throws (`NullPointerException`) - no value flows from it, +/// so `Null` (bottom) is the precise answer. Yielding `Object` poisons the +/// join permanently: `lub(Object, String)` stays `Object`, while the true +/// merge (`lub(Null, String)`) is `String`. Worse, the poison arrives +/// through *transient* worklist states (before upstream slots refine) and +/// can never leave - the transfer is non-monotone in the arrayref. +#[test] +fn aaload_on_null_yields_null() { + let method = code_method( + "pick", + "(Ljava/lang/String;)Ljava/lang/Object;", + 2, + 2, + vec![ + Insn::Mark(0), + Insn::AconstNull, + store_ref(1), + Insn::Const(Const::Int(0)), + Insn::Branch(BranchCond::Zero(Cond::Eq), 1), + load_ref(1), + Insn::Const(Const::Int(0)), + Insn::ArrayLoad(ArrayKind::Reference), + Insn::Goto(2), + Insn::Mark(1), + load_ref(0), + Insn::Mark(2), + Insn::AReturn, + ], + vec![], + ); + let frames = compute_frames("demo/Pick", &method, &NoHierarchy).expect("frames"); + let mut saw_string = false; + for frame in &frames { + let stack: Vec = match frame { + StackMapFrame::SameLocals { local, .. } => vec![local.clone()], + StackMapFrame::Full { stack, .. } => stack.clone(), + _ => vec![], + }; + for item in &stack { + assert_ne!( + item, + &VerificationType::Object("java/lang/Object".to_string()), + "poisoned join in {frames:?}" + ); + if item == &VerificationType::Object("java/lang/String".to_string()) { + saw_string = true; + } + } + } + assert!(saw_string, "expected the String join in {frames:?}"); +} diff --git a/crates/noxis-classfile/src/format/frames/tests/joins/mod.rs b/crates/noxis-classfile/src/format/frames/tests/joins/mod.rs new file mode 100644 index 0000000..ea82b9f --- /dev/null +++ b/crates/noxis-classfile/src/format/frames/tests/joins/mod.rs @@ -0,0 +1,151 @@ +//! Join-shape tests: loop heads, wide array loads, nested construction. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use super::super::{StackMapFrame, VerificationType, compute_frames}; + +use super::{NoHierarchy, code_method, load, load_ref, store, store_ref}; +use crate::insn::{BranchCond, Cond, Const, Insn, Prim}; + +mod arrays; +#[test] +fn loop_head_keeps_top_for_loop_local() { + let method = code_method( + "sum", + "()I", + 2, + 3, + vec![ + Insn::Mark(0), + Insn::Const(Const::Int(0)), + store(0), + Insn::Const(Const::Int(0)), + store(1), + Insn::Mark(1), + load(1), + Insn::Const(Const::Int(10)), + Insn::Branch(BranchCond::Int(Cond::Ge), 2), + load(1), + store(2), + load(2), + store(0), + Insn::Iinc { index: 1, delta: 1 }, + Insn::Goto(1), + Insn::Mark(2), + load(0), + Insn::Return(Some(Prim::Int)), + ], + vec![], + ); + let frames = compute_frames("demo/Sum", &method, &NoHierarchy).expect("frames"); + assert_eq!( + frames, + vec![ + StackMapFrame::Append { + offset_delta: 4, + locals: vec![VerificationType::Integer, VerificationType::Integer], + }, + StackMapFrame::Same { offset_delta: 8 }, + ] + ); +} + +/// A nested construction (`new Outer(new Inner())`) initializes only the +/// inner object: the outer `Uninitialized` survives with its own offset, so +/// a later join still sees it instead of a clobbered `Object(Inner)`. +#[test] +fn nested_construction_keeps_outer_uninitialized() { + let method = code_method( + "make", + "()I", + 4, + 1, + vec![ + Insn::Mark(0), + Insn::New("demo/Outer".to_string()), + Insn::Dup, + Insn::New("demo/Inner".to_string()), + Insn::Dup, + Insn::Invoke { + kind: crate::insn::InvokeKind::Special, + owner: "demo/Inner".to_string(), + name: "".to_string(), + descriptor: "()V".to_string(), + itf: false, + }, + Insn::Invoke { + kind: crate::insn::InvokeKind::Special, + owner: "demo/Outer".to_string(), + name: "".to_string(), + descriptor: "(Ldemo/Inner;)V".to_string(), + itf: false, + }, + store_ref(0), + load_ref(0), + Insn::Branch(BranchCond::Null { is_null: false }, 1), + Insn::Const(Const::Int(0)), + Insn::Goto(2), + Insn::Mark(1), + Insn::Const(Const::Int(1)), + Insn::Mark(2), + Insn::Return(Some(Prim::Int)), + ], + vec![], + ); + let frames = compute_frames("demo/Make", &method, &NoHierarchy).expect("frames"); + assert_eq!( + frames, + vec![ + StackMapFrame::Append { + offset_delta: 11, + locals: vec![VerificationType::Object("demo/Outer".to_string())], + }, + StackMapFrame::SameLocals { + offset_delta: 0, + local: VerificationType::Integer, + }, + ] + ); +} + +/// `laload` pushes a pair (`long` + `Top`): a following `lcmp` needs four +/// entries and must not underflow. +#[test] +fn array_load_wide_pushes_pair() { + let method = code_method( + "get", + "([JI)J", + 4, + 2, + vec![ + Insn::Mark(0), + load_ref(0), + load(1), + Insn::ArrayLoad(crate::insn::ArrayKind::Long), + Insn::Const(Const::Long(0)), + Insn::Cmp { + prim: Prim::Long, + nan_great: false, + }, + Insn::Branch(BranchCond::Zero(Cond::Ne), 1), + Insn::Const(Const::Long(1)), + Insn::Goto(2), + Insn::Mark(1), + Insn::Const(Const::Long(0)), + Insn::Mark(2), + Insn::Return(Some(Prim::Long)), + ], + vec![], + ); + let frames = compute_frames("demo/Wide", &method, &NoHierarchy).expect("frames"); + assert_eq!( + frames, + vec![ + StackMapFrame::Same { offset_delta: 8 }, + StackMapFrame::SameLocals { + offset_delta: 0, + local: VerificationType::Long, + }, + ] + ); +} diff --git a/crates/noxis-classfile/src/format/frames/tests.rs b/crates/noxis-classfile/src/format/frames/tests/mod.rs similarity index 79% rename from crates/noxis-classfile/src/format/frames/tests.rs rename to crates/noxis-classfile/src/format/frames/tests/mod.rs index 7e3bcad..41d623d 100644 --- a/crates/noxis-classfile/src/format/frames/tests.rs +++ b/crates/noxis-classfile/src/format/frames/tests/mod.rs @@ -1,4 +1,4 @@ -//! Unit-тесты `compute_frames` на синтезированном IR. +//! Unit tests for `compute_frames` on synthesized IR. #![allow(clippy::expect_used, clippy::unwrap_used)] @@ -7,8 +7,8 @@ use crate::Hierarchy; use crate::insn::{BranchCond, Cond, Const, Insn, Prim, SlotKind}; use crate::model::{Code, ExceptionHandler, Method}; -/// Пустая иерархия: всё неизвестное — наследники `Object` (для LUB хватает). -struct NoHierarchy; +/// Empty hierarchy: everything unknown descends from `Object` (enough for LUB). +pub(super) struct NoHierarchy; impl Hierarchy for NoHierarchy { fn superclass(&self, _class: &str) -> Option { @@ -16,7 +16,7 @@ impl Hierarchy for NoHierarchy { } } -fn code_method( +pub(super) fn code_method( name: &str, descriptor: &str, max_stack: u16, @@ -40,7 +40,7 @@ fn code_method( } } -/// Ветвь → два кадра (`Same`, `SameLocals`). +/// A branch emits two frames (`Same`, `SameLocals`). #[test] fn branch_emits_same_frames() { let mut method = code_method( @@ -76,7 +76,11 @@ fn branch_emits_same_frames() { ); } -/// `try/catch`: handler получает `Full`, продолжение — `Append`. +/// `try/catch`: the handler gets `Full`, the continuation - `Same`. +/// +/// Slot 1 is written only inside the handler, so the join keeps `Top` there +/// (like `javac`): a precise type would reject the inflow that never wrote +/// it (`Type top is not assignable`). #[test] fn handler_emits_full_frame() { let method = code_method( @@ -115,15 +119,12 @@ fn handler_emits_full_frame() { locals: vec![VerificationType::Integer], stack: vec![VerificationType::Object("java/lang/Exception".to_string())], }, - StackMapFrame::Append { - offset_delta: 2, - locals: vec![VerificationType::Object("java/lang/Exception".to_string())], - }, + StackMapFrame::Same { offset_delta: 2 }, ] ); } -/// Два `new` на разных ветвях нельзя слить — честная ошибка, не `Top`. +/// Two `new` on different branches cannot merge - an honest error, not `Top`. #[test] fn uninitialized_merge_is_rejected() { let method = code_method( @@ -150,28 +151,37 @@ fn uninitialized_merge_is_rejected() { ], vec![], ); - let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("слияние"); + let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("merge"); assert!( - err.to_string().contains("неинициализированных"), - "не тот текст: {err}" + err.to_string().contains("uninitialized"), + "wrong message: {err}" ); } -fn load(slot: u16) -> Insn { +mod joins; + +pub(super) fn load(slot: u16) -> Insn { Insn::Load { slot, kind: SlotKind::Int, } } -fn store(slot: u16) -> Insn { +pub(super) fn load_ref(slot: u16) -> Insn { + Insn::Load { + slot, + kind: SlotKind::Ref, + } +} + +pub(super) fn store(slot: u16) -> Insn { Insn::Store { slot, kind: SlotKind::Int, } } -fn store_ref(slot: u16) -> Insn { +pub(super) fn store_ref(slot: u16) -> Insn { Insn::Store { slot, kind: SlotKind::Ref, diff --git a/crates/noxis-classfile/src/format/frames/xfer/calls.rs b/crates/noxis-classfile/src/format/frames/xfer/calls.rs index 98f4950..d25de8c 100644 --- a/crates/noxis-classfile/src/format/frames/xfer/calls.rs +++ b/crates/noxis-classfile/src/format/frames/xfer/calls.rs @@ -1,4 +1,4 @@ -//! Вызовы и константы: дескрипторы, ``, слоты значений. +//! Calls and constants: descriptors, ``, value slots. use super::super::VerificationType; use super::super::merge::descs::{DescError, field_slots, method_slots}; @@ -34,18 +34,12 @@ pub(super) fn invoke( descriptor: &str, ) -> Result<(), ClassfileError> { let (params, ret) = method_slots(descriptor).map_err(|e| context(class, method, e))?; - super::stack::pop_slots( - state, - count_slots(¶ms), - class, - method, - "аргументы вызова", - )?; + super::stack::pop_slots(state, count_slots(¶ms), class, method, "call arguments")?; let mut receiver = None; if kind != InvokeKind::Static { receiver = super::stack::pop_slots(state, 1, class, method, "objectref")?.pop(); } - // `` инициализирует получателя во ВСЕХ его копиях. + // `` initializes the receiver in ALL its copies. if name == "" { match receiver { Some(VerificationType::UninitializedThis) => { @@ -55,9 +49,11 @@ pub(super) fn invoke( &initialized(class), ); } - Some(VerificationType::Uninitialized(_)) => { + // Only the receiver's own allocation site: an enclosing `new` + // whose `` has not run yet must stay uninitialized. + Some(VerificationType::Uninitialized(offset)) => { let fresh = VerificationType::Object(owner.to_string()); - replace_uninit(state, &fresh); + replace(state, &VerificationType::Uninitialized(offset), &fresh); } _ => {} } @@ -68,12 +64,12 @@ pub(super) fn invoke( Ok(()) } -/// Число слотов всех параметров. +/// Slot count across all parameters. pub(super) fn count_slots(params: &[Vec]) -> usize { params.iter().map(Vec::len).sum() } -/// Заменить все вхождения типа новым (инициализация через ``). +/// Replace every occurrence of a type with a new one (init via ``). fn replace(state: &mut State, from: &VerificationType, to: &VerificationType) { for slot in state.locals.iter_mut().chain(state.stack.iter_mut()) { if slot == from { @@ -82,15 +78,6 @@ fn replace(state: &mut State, from: &VerificationType, to: &VerificationType) { } } -/// Любой `Uninitialized` (кроме `this`) → тип владельца (созданный `new`). -fn replace_uninit(state: &mut State, to: &VerificationType) { - for slot in state.locals.iter_mut().chain(state.stack.iter_mut()) { - if matches!(slot, VerificationType::Uninitialized(_)) { - *slot = to.clone(); - } - } -} - fn initialized(class: &str) -> VerificationType { VerificationType::Object(class.to_string()) } @@ -115,7 +102,7 @@ pub(super) fn prim_push(prim: Prim) -> Vec { } } -/// `(слоты аргумента, примитив результата)` для конверсии. +/// `(argument slots, result primitive)` for a conversion. pub(super) fn convert_shapes(op: Convert) -> (usize, Prim) { use Convert::{D2F, D2I, D2L, F2D, F2I, F2L, I2B, I2C, I2D, I2F, I2L, I2S, L2D, L2F, L2I}; use Prim::{Double, Float, Int, Long}; diff --git a/crates/noxis-classfile/src/format/frames/xfer/mod.rs b/crates/noxis-classfile/src/format/frames/xfer/mod.rs index 1814794..44279c8 100644 --- a/crates/noxis-classfile/src/format/frames/xfer/mod.rs +++ b/crates/noxis-classfile/src/format/frames/xfer/mod.rs @@ -1,8 +1,8 @@ -//! Состояние типов и transfer-функции инструкций. +//! Type states and per-instruction transfer functions. //! -//! Стек растёт вправо (`push` — в конец). `long`/`double` занимают два слота: -//! значение + `Top`. Проверяется только ФОРМА (глубина, категории), не -//! соответствие типов — неверные типы честно упадут на верификаторе JVM. +//! The stack grows right (`push` appends). `long`/`double` take two slots: +//! value + `Top`. Only the SHAPE is checked (depth, categories), not +//! type agreement - wrong types honestly fail on the JVM verifier. pub(super) mod calls; pub(super) mod stack; @@ -15,14 +15,14 @@ use crate::insn::{Arith, ArrayKind, BranchCond, Insn, SlotKind}; use calls::{const_slots, context, convert_shapes, count_slots, invoke, prim_push, prim_slots}; use stack::{dup, dup2, local_get, pop_slots, push, store_local, wide_push}; -/// Типы locals + operand stack в одной точке программы. +/// Local types plus the operand stack at one program point. #[derive(Debug, Clone, Default, PartialEq)] pub(super) struct State { pub locals: Vec, pub stack: Vec, } -/// Применить инструкцию к состоянию (на месте). +/// Apply one instruction to the state (in place). pub(super) fn transfer( class: &str, method: &str, @@ -31,7 +31,11 @@ pub(super) fn transfer( state: &mut State, ) -> Result<(), ClassfileError> { match insn { - Insn::Mark(label) => Err(invalid(class, method, &format!("маркер {label} не снят"))), + Insn::Mark(label) => Err(invalid( + class, + method, + &format!("marker {label} was not stripped"), + )), Insn::Nop => Ok(()), Insn::AconstNull => push(state, vec![VerificationType::Null]), Insn::Const(value) => { @@ -51,29 +55,29 @@ pub(super) fn transfer( Insn::Iinc { index, .. } => { let current = local_get(state, *index, class, method)?; if current != VerificationType::Integer { - return Err(invalid(class, method, "iinc не по int")); + return Err(invalid(class, method, "iinc over a non-int")); } Ok(()) } Insn::ArrayLoad(kind) => { - pop_slots(state, 1, class, method, "индекс массива")?; - let array = pop_slots(state, 1, class, method, "массив")?.remove(0); - push(state, vec![array_element(&array, *kind)]) + pop_slots(state, 1, class, method, "array index")?; + let array = pop_slots(state, 1, class, method, "array")?.remove(0); + push(state, wide_push(array_element(&array, *kind))) } Insn::ArrayStore(kind) => { let count = match kind { ArrayKind::Long | ArrayKind::Double => 2, _ => 1, }; - pop_slots(state, count, class, method, "значение")?; - pop_slots(state, 1, class, method, "индекс массива")?; - pop_slots(state, 1, class, method, "массив")?; + pop_slots(state, count, class, method, "value")?; + pop_slots(state, 1, class, method, "array index")?; + pop_slots(state, 1, class, method, "array")?; Ok(()) } Insn::Pop => { let top = pop_slots(state, 1, class, method, "pop")?.remove(0); if top == VerificationType::Top { - return Err(invalid(class, method, "pop половины long/double")); + return Err(invalid(class, method, "pop of a long/double half")); } Ok(()) } @@ -90,7 +94,7 @@ pub(super) fn transfer( Insn::Swap => { let mut taken = pop_slots(state, 2, class, method, "swap")?; if taken.contains(&VerificationType::Top) { - return Err(invalid(class, method, "swap с половиной")); + return Err(invalid(class, method, "swap with a half")); } taken.reverse(); push(state, taken) @@ -100,7 +104,7 @@ pub(super) fn transfer( if *op == Arith::Neg { pop_slots(state, slots as usize, class, method, "neg")?; } else if matches!(op, Arith::Shl | Arith::Shr | Arith::Ushr) { - // Сдвиг берёт (значение, int), а не два значения. + // A shift takes (value, int), not two values. pop_slots(state, slots as usize + 1, class, method, "shift")?; } else { pop_slots(state, 2 * slots as usize, class, method, "arith")?; @@ -128,7 +132,7 @@ pub(super) fn transfer( Insn::Jsr(_) | Insn::Ret(_) => Err(invalid( class, method, - "подпрограммы jsr/ret не поддерживаются", + "jsr/ret subroutines are not supported", )), Insn::TableSwitch { .. } | Insn::LookupSwitch { .. } => { pop_slots(state, 1, class, method, "switch")?; @@ -192,7 +196,7 @@ pub(super) fn transfer( ArrayKind::Int => "[I", ArrayKind::Long => "[J", ArrayKind::Reference => { - return Err(invalid(class, method, "newarray ссылочного типа")); + return Err(invalid(class, method, "newarray of a reference type")); } }; push( @@ -202,7 +206,16 @@ pub(super) fn transfer( } Insn::ANewArray(name) => { pop_slots(state, 1, class, method, "anewarray")?; - push(state, vec![VerificationType::Object(format!("[L{name};"))]) + // `anewarray` adds one dimension: a plain class becomes + // `[L...;`, an already-array operand (`anewarray [B` for a + // partially bound multi-dim) gains one more `[`. Wrapping an + // array operand in `L...;` (`[L[B;`) is not a class. + let descriptor = if name.starts_with('[') { + format!("[{name}") + } else { + format!("[L{name};") + }; + push(state, vec![VerificationType::Object(descriptor)]) } Insn::MultiANewArray { descriptor, dims } => { pop_slots(state, *dims as usize, class, method, "multianewarray")?; diff --git a/crates/noxis-classfile/src/format/frames/xfer/stack.rs b/crates/noxis-classfile/src/format/frames/xfer/stack.rs index 0481536..f9c6744 100644 --- a/crates/noxis-classfile/src/format/frames/xfer/stack.rs +++ b/crates/noxis-classfile/src/format/frames/xfer/stack.rs @@ -5,7 +5,7 @@ use super::State; use crate::error::ClassfileError; use crate::insn::SlotKind; -/// Запись в local с учётом ширины (`long`/`double` — парой с `Top`). +/// Запись в local с учётом ширины (`long`/`double` - парой с `Top`). pub(super) fn store_local( state: &mut State, slot: u16, @@ -38,7 +38,7 @@ pub(super) fn push(state: &mut State, slots: Vec) -> Result<() Ok(()) } -/// Снять `n` слотов (снизу вверх); нехватка — честная ошибка. +/// Снять `n` слотов (снизу вверх); нехватка - честная ошибка. pub(super) fn pop_slots( state: &mut State, n: usize, @@ -84,7 +84,7 @@ pub(super) fn local_set( Ok(()) } -/// Значение local'а целиком: `long`/`double` — парой с `Top`. +/// Значение local'а целиком: `long`/`double` - парой с `Top`. pub(super) fn wide_push(value: VerificationType) -> Vec { match value { VerificationType::Long | VerificationType::Double => vec![value, VerificationType::Top], @@ -112,7 +112,7 @@ pub(super) fn dup( push(state, out) } -/// `dup2*`: форма выбирается по вершине (`Top` — вторая половина `long`). +/// `dup2*`: форма выбирается по вершине (`Top` - вторая половина `long`). pub(super) fn dup2( state: &mut State, class: &str, diff --git a/crates/noxis-classfile/src/format/mod.rs b/crates/noxis-classfile/src/format/mod.rs index 36826d1..7b692e9 100644 --- a/crates/noxis-classfile/src/format/mod.rs +++ b/crates/noxis-classfile/src/format/mod.rs @@ -1,5 +1,6 @@ -//! Чтение/запись бинарного формата `.class` (JVMS §4) через backend -//! `ristretto_classfile`: обзор кандидатов и решение — `docs/stack.md`. +//! Reading/writing the binary `.class` format (JVMS §4) through the +//! `ristretto_classfile` backend: candidate review and decision in +//! `docs/stack.md`. mod frames; mod parse; @@ -10,20 +11,21 @@ pub use frames::{Hierarchy, StackMapFrame, VerificationType, compute_frames}; use crate::error::ClassfileError; use crate::model::ClassFile; -/// Разобрать один `.class` в [`ClassFile`]. +/// Parse one `.class` into a [`ClassFile`]. pub fn parse(bytes: &[u8]) -> Result { parse::class::parse_class(bytes) } -/// Записать [`ClassFile`] в байты, включая пересчёт `Code`/`StackMapTable`. +/// Write a [`ClassFile`] to bytes, including `Code`/`StackMapTable` recompute. pub fn write(class: &ClassFile) -> Result, ClassfileError> { write::write_class(class) } -/// Классы, которые не изменялись, должны уезжать в выходной архив «как есть». +/// Classes that were not modified must go to the output archive "as-is". /// -/// Это дешевле и безопаснее, чем round-trip через наш IR: нет риска потерять -/// неизвестный атрибут. Реализация зависит от решения по backend (P1). +/// This is cheaper and safer than a round-trip through our IR: no risk of +/// losing an unknown attribute. The implementation depends on the backend +/// decision (P1). pub fn passthrough_needed(class: &ClassFile) -> bool { class.methods.is_empty() && class.fields.is_empty() } diff --git a/crates/noxis-classfile/src/format/parse/annos/mod.rs b/crates/noxis-classfile/src/format/parse/annos/mod.rs new file mode 100644 index 0000000..a365c07 --- /dev/null +++ b/crates/noxis-classfile/src/format/parse/annos/mod.rs @@ -0,0 +1,179 @@ +//! Annotation attributes → IR: names instead of pool indices. +//! +//! Split out of `pool.rs`: these structures carry pool references that go +//! stale the moment the writer rebuilds the pool, so every one of them is +//! modeled (raw bytes made ASM die with `ArrayIndexOutOfBoundsException`). + +use ristretto_classfile::ConstantPool; + +use super::pool::{const_from, utf8}; +use crate::error::ClassfileError; +use crate::insn::Const; +use crate::model::{Annotation, AnnotationValue, TypeAnnotation}; + +/// A list of `annotation` structures (`RuntimeVisibleAnnotations`). +pub(super) fn annos( + pool: &ConstantPool<'_>, + list: &[ristretto_classfile::attributes::Annotation], +) -> Result, ClassfileError> { + list.iter().map(|anno| annotation(pool, anno)).collect() +} + +/// Per-parameter annotation lists (`RuntimeVisibleParameterAnnotations`). +pub(super) fn params( + pool: &ConstantPool<'_>, + list: &[ristretto_classfile::attributes::ParameterAnnotation], +) -> Result>, ClassfileError> { + list.iter() + .map(|param| { + param + .annotations + .iter() + .map(|anno| annotation(pool, anno)) + .collect() + }) + .collect() +} + +/// A list of `type_annotation` structures (`RuntimeVisibleTypeAnnotations`). +pub(super) fn type_annos( + pool: &ConstantPool<'_>, + list: &[ristretto_classfile::attributes::TypeAnnotation], +) -> Result, ClassfileError> { + list.iter() + .map(|anno| type_annotation(pool, anno)) + .collect() +} + +/// One `element_value` → IR, keeping the tag (HotSpot checks it). +pub(super) fn element_value( + pool: &ConstantPool<'_>, + value: &ristretto_classfile::attributes::AnnotationElement, +) -> Result { + use ristretto_classfile::attributes::AnnotationElement as E; + Ok(match value { + E::Byte { const_value_index } => { + AnnotationValue::Byte(const_int(pool, *const_value_index)?) + } + E::Char { const_value_index } => { + AnnotationValue::Char(const_int(pool, *const_value_index)?) + } + E::Short { const_value_index } => { + AnnotationValue::Short(const_int(pool, *const_value_index)?) + } + E::Boolean { const_value_index } => { + AnnotationValue::Boolean(const_int(pool, *const_value_index)?) + } + E::Int { const_value_index } => AnnotationValue::Int(const_int(pool, *const_value_index)?), + E::Long { const_value_index } => { + AnnotationValue::Long(const_long(pool, *const_value_index)?) + } + E::Float { const_value_index } => { + AnnotationValue::Float(const_float(pool, *const_value_index)?) + } + E::Double { const_value_index } => { + AnnotationValue::Double(const_double(pool, *const_value_index)?) + } + E::String { const_value_index } => AnnotationValue::String(utf8(pool, *const_value_index)?), + E::Enum { + type_name_index, + const_name_index, + } => AnnotationValue::Enum { + descriptor: utf8(pool, *type_name_index)?, + name: utf8(pool, *const_name_index)?, + }, + E::Class { class_info_index } => AnnotationValue::Class(utf8(pool, *class_info_index)?), + E::Annotation { annotation: nested } => { + AnnotationValue::Nested(Box::new(annotation(pool, nested)?)) + } + E::Array { values } => AnnotationValue::Array( + values + .iter() + .map(|value| element_value(pool, value)) + .collect::>()?, + ), + }) +} + +/// One `annotation` structure → IR (names, not pool indices). +fn annotation( + pool: &ConstantPool<'_>, + anno: &ristretto_classfile::attributes::Annotation, +) -> Result { + Ok(Annotation { + descriptor: utf8(pool, anno.type_index)?, + elements: anno + .elements + .iter() + .map(|pair| { + Ok(( + utf8(pool, pair.name_index)?, + element_value(pool, &pair.value)?, + )) + }) + .collect::>()?, + }) +} + +/// One `type_annotation` structure → IR: the annotated type by name, +/// `target_info` + `type_path` as raw bytes (JVMS §4.7.20.1-2 carry no +/// pool references, so they survive the rebuild verbatim). +fn type_annotation( + pool: &ConstantPool<'_>, + anno: &ristretto_classfile::attributes::TypeAnnotation, +) -> Result { + let mut target = Vec::new(); + anno.target_type + .to_bytes(&mut target) + .map_err(|e| ClassfileError::Parse(e.to_string()))?; + let path_len = u8::try_from(anno.type_path.len()) + .map_err(|_| ClassfileError::Parse("слишком длинный type_path".into()))?; + target.push(path_len); + for path in &anno.type_path { + path.to_bytes(&mut target) + .map_err(|e| ClassfileError::Parse(e.to_string()))?; + } + Ok(TypeAnnotation { + target, + descriptor: utf8(pool, anno.type_index)?, + elements: anno + .elements + .iter() + .map(|pair| { + Ok(( + utf8(pool, pair.name_index)?, + element_value(pool, &pair.value)?, + )) + }) + .collect::>()?, + }) +} + +/// The `CONSTANT_Integer` behind a `B`/`C`/`S`/`Z`/`I` element. +fn const_int(pool: &ConstantPool<'_>, index: u16) -> Result { + match const_from(pool, index)? { + Const::Int(v) => Ok(v), + _ => Err(ClassfileError::Parse("не Integer".into())), + } +} + +fn const_long(pool: &ConstantPool<'_>, index: u16) -> Result { + match const_from(pool, index)? { + Const::Long(v) => Ok(v), + _ => Err(ClassfileError::Parse("не Long".into())), + } +} + +fn const_float(pool: &ConstantPool<'_>, index: u16) -> Result { + match const_from(pool, index)? { + Const::Float(v) => Ok(v), + _ => Err(ClassfileError::Parse("не Float".into())), + } +} + +fn const_double(pool: &ConstantPool<'_>, index: u16) -> Result { + match const_from(pool, index)? { + Const::Double(v) => Ok(v), + _ => Err(ClassfileError::Parse("не Double".into())), + } +} diff --git a/crates/noxis-classfile/src/format/parse/attrs.rs b/crates/noxis-classfile/src/format/parse/attrs.rs index 8dc3c94..c3eb382 100644 --- a/crates/noxis-classfile/src/format/parse/attrs.rs +++ b/crates/noxis-classfile/src/format/parse/attrs.rs @@ -1,21 +1,22 @@ -//! Атрибуты backend'а → атрибуты нашего IR. +//! Backend attributes → our IR attributes. //! -//! `BootstrapMethods`, `EnclosingMethod`, `MethodParameters` и `ConstantValue` -//! моделируются явно (в них лежат ссылки пула, переживающие пересборку); -//! остальное структурированное, но нам ненужное, уезжает в `Raw` как есть. -//! `Code` и `StackMapTable` здесь не обрабатываются — их разбирает вызывающий -//! код метода (см. `super::class`). +//! `BootstrapMethods`, `EnclosingMethod`, `MethodParameters` and `ConstantValue` +//! are modeled explicitly (they hold pool references that survive rebuilding); +//! everything else that is structured but unneeded by us goes to `Raw` as-is. +//! `Code` and `StackMapTable` are not handled here - the calling method code +//! parses them (see `super::class`). use ristretto_classfile::ConstantPool; use ristretto_classfile::attributes::Attribute as RtAttr; +use super::annos::{annos, element_value, params, type_annos}; use super::pool::{ class_name, const_from, is_interface, kind_code, name_and_type, ref_parts, utf8, }; use crate::error::ClassfileError; use crate::model::{Attribute, BootstrapMethod, InnerClass, MethodParameter, RecordComponent}; -/// Один атрибут backend'а → наш атрибут (кроме `Code`/`StackMapTable`). +/// One backend attribute → our attribute (except `Code`/`StackMapTable`). pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result { Ok(match attr { RtAttr::SourceFile { @@ -47,6 +48,12 @@ pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result>()?, ), + RtAttr::PermittedSubclasses { class_indexes, .. } => Attribute::PermittedSubclasses( + class_indexes + .iter() + .map(|index| class_name(pool, *index)) + .collect::>()?, + ), RtAttr::EnclosingMethod { class_index, method_index, @@ -101,11 +108,34 @@ pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result { + Attribute::RuntimeVisibleAnnotations(annos(pool, annotations)?) + } + RtAttr::RuntimeInvisibleAnnotations { annotations, .. } => { + Attribute::RuntimeInvisibleAnnotations(annos(pool, annotations)?) + } + RtAttr::RuntimeVisibleParameterAnnotations { + parameter_annotations, + .. + } => Attribute::RuntimeVisibleParameterAnnotations(params(pool, parameter_annotations)?), + RtAttr::RuntimeInvisibleParameterAnnotations { + parameter_annotations, + .. + } => Attribute::RuntimeInvisibleParameterAnnotations(params(pool, parameter_annotations)?), + RtAttr::RuntimeVisibleTypeAnnotations { + type_annotations, .. + } => Attribute::RuntimeVisibleTypeAnnotations(type_annos(pool, type_annotations)?), + RtAttr::RuntimeInvisibleTypeAnnotations { + type_annotations, .. + } => Attribute::RuntimeInvisibleTypeAnnotations(type_annos(pool, type_annotations)?), + RtAttr::AnnotationDefault { element, .. } => { + Attribute::AnnotationDefault(element_value(pool, element)?) + } other => raw(other)?, }) } -/// Несмоделированный атрибут → `Raw`: имя + байты `info` (без заголовка). +/// An unmodeled attribute → `Raw`: name + `info` bytes (without the header). pub(super) fn raw(attr: &RtAttr) -> Result { let mut bytes = Vec::new(); attr.to_bytes(&mut bytes) @@ -131,7 +161,7 @@ fn inner( }) } -/// Метод объемлющего класса (`0` — только класс, без метода). +/// The enclosing class's method (`0` - class only, no method). fn enclosing_method( pool: &ConstantPool<'_>, index: u16, @@ -194,7 +224,7 @@ fn bootstrap( }) } -/// Индекс пула, где `0` означает отсутствие значения. +/// A pool index where `0` means the value is absent. fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result, ClassfileError> { if index == 0 { Ok(None) @@ -203,7 +233,7 @@ fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result, } } -/// Индекс `CONSTANT_Utf8`, где `0` означает отсутствие значения. +/// A `CONSTANT_Utf8` index where `0` means the value is absent. fn optional_utf8(pool: &ConstantPool<'_>, index: u16) -> Result, ClassfileError> { if index == 0 { Ok(None) diff --git a/crates/noxis-classfile/src/format/parse/class.rs b/crates/noxis-classfile/src/format/parse/class.rs index 8a629e7..2e6ee58 100644 --- a/crates/noxis-classfile/src/format/parse/class.rs +++ b/crates/noxis-classfile/src/format/parse/class.rs @@ -1,4 +1,4 @@ -//! Класс целиком: backend `ClassFile` → наш [`ClassFile`](crate::model::ClassFile). +//! The whole class: backend `ClassFile` → our [`ClassFile`](crate::model::ClassFile). use ristretto_classfile::attributes::Attribute as RtAttr; use ristretto_classfile::{ @@ -11,7 +11,22 @@ use super::pool::{class_name, utf8}; use crate::error::ClassfileError; use crate::model::{Attribute, ClassFile, Code, Field, Method, Version}; -/// Разобрать байты `.class` в наш IR. +/// JVMS 4.1: an interface implies `ABSTRACT` and ignores `SUPER`. Some +/// compilers emit a bare `0x200` that HotSpot tolerates, but the strict +/// backend verifier rejects it on write (after widening, as `0x201`) - so +/// normalize once on parse. Interfaces are abstract by definition: no +/// behaviour changes. +fn normalize_class_flags(flags: u16) -> u16 { + const INTERFACE: u16 = 0x0200; + const SUPER: u16 = 0x0020; + const ABSTRACT: u16 = 0x0400; + if flags & INTERFACE == 0 { + return flags; + } + (flags | ABSTRACT) & !SUPER +} + +/// Parse `.class` bytes into our IR. pub(crate) fn parse_class(bytes: &[u8]) -> Result { let rt = RtClass::from_bytes(bytes).map_err(|e| ClassfileError::Parse(e.to_string()))?; let pool = &rt.constant_pool; @@ -25,7 +40,7 @@ pub(crate) fn parse_class(bytes: &[u8]) -> Result { minor: rt.version.minor(), major: rt.version.major(), }, - access_flags: rt.access_flags.bits(), + access_flags: normalize_class_flags(rt.access_flags.bits()), this_class: class_name(pool, rt.this_class)?, super_class: optional_class(pool, rt.super_class)?, interfaces, @@ -99,7 +114,7 @@ fn convert_attrs( .collect() } -/// Индекс суперкласса, где `0` — его отсутствие (`java/lang/Object`). +/// The superclass index, where `0` means absent (`java/lang/Object`). fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result, ClassfileError> { if index == 0 { Ok(None) diff --git a/crates/noxis-classfile/src/format/parse/code/frames.rs b/crates/noxis-classfile/src/format/parse/code/frames.rs index 09a6ab3..422e8fe 100644 --- a/crates/noxis-classfile/src/format/parse/code/frames.rs +++ b/crates/noxis-classfile/src/format/parse/code/frames.rs @@ -1,7 +1,8 @@ -//! Кадры `StackMapTable` при чтении: вариант в вариант, дельты как есть. +//! `StackMapTable` frames on read: variant to variant, deltas as-is. //! -//! Backend хранит кадры в номерах инструкций (см. `from_bytes_code_attributes`), -//! наш IR — тоже: writer сам пересчитает их в байты при `to_bytes`. +//! The backend stores frames in instruction indices (see +//! `from_bytes_code_attributes`), and so does our IR: the writer recomputes them +//! into bytes on `to_bytes`. use ristretto_classfile::ConstantPool; use ristretto_classfile::attributes::{StackFrame, VerificationType as RtType}; @@ -10,7 +11,7 @@ use super::super::pool::class_name; use crate::error::ClassfileError; use crate::format::{StackMapFrame, VerificationType}; -/// Кадры backend'а → наши (индексные дельты — как есть). +/// Backend frames → ours (index deltas - as-is). pub(super) fn to_frames( frames: &[StackFrame], pool: &ConstantPool<'_>, @@ -66,7 +67,7 @@ fn to_frame(frame: &StackFrame, pool: &ConstantPool<'_>) -> Result) -> Result { let mut types = types(stack, pool)?.into_iter(); match (types.next(), types.next()) { @@ -84,7 +85,7 @@ fn types( values.iter().map(|value| vtype(value, pool)).collect() } -/// Тип верификации backend'а → наш тип (имя класса берётся из constant pool). +/// Backend verification type → our type (the class name comes from the constant pool). fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result { Ok(match value { RtType::Top => VerificationType::Top, @@ -99,7 +100,7 @@ fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result, index: u16, diff --git a/crates/noxis-classfile/src/format/parse/code/labels.rs b/crates/noxis-classfile/src/format/parse/code/labels.rs index 0352a8b..f877044 100644 --- a/crates/noxis-classfile/src/format/parse/code/labels.rs +++ b/crates/noxis-classfile/src/format/parse/code/labels.rs @@ -1,7 +1,7 @@ -//! Метки тела метода: где обязаны стоять и как резолвятся. +//! Method-body labels: where they must stand and how they resolve. //! -//! Backend нумерует инструкции по порядку — метки ставятся прямо на номера, -//! без байтовых смещений. +//! The backend numbers instructions in order - labels are placed directly on the +//! numbers, without byte offsets. use std::collections::{BTreeMap, BTreeSet}; @@ -11,10 +11,10 @@ use ristretto_classfile::attributes::{ExceptionTableEntry, Instruction}; use crate::error::ClassfileError; use crate::insn::Label; -/// Номера инструкций, на которых обязана стоять метка. +/// Instruction numbers that must carry a label. /// -/// `extra` — позиции отладочных таблиц (уже номерами): вставки пассов -/// не должны оставлять их без меток. +/// `extra` - debug-table positions (already as numbers): pass insertions must +/// not leave them without a label. pub(super) fn label_indexes( code: &[Instruction], exception_table: &[ExceptionTableEntry], @@ -36,7 +36,7 @@ pub(super) fn label_indexes( Ok(indexes) } -/// Цели ветвлений backend'а: для `if*`/`goto` — абсолютный номер, для `switch` — дельта. +/// Backend branch targets: for `if*`/`goto` an absolute number, for `switch` a delta. fn branch_indexes(instruction: &Instruction, index: u16) -> Vec { let base = i32::from(index); match instruction { @@ -73,7 +73,7 @@ fn once(value: i32) -> std::iter::Once { std::iter::once(value) } -/// Превратить отсортированный набор номеров в последовательные метки. +/// Turn a sorted set of numbers into sequential labels. pub(super) fn assign(indexes: &BTreeSet) -> BTreeMap { indexes .iter() @@ -82,7 +82,7 @@ pub(super) fn assign(indexes: &BTreeSet) -> BTreeMap { .collect() } -/// Метка для номера инструкции. +/// The label for an instruction number. pub(super) fn lookup(labels: &BTreeMap, index: u16) -> Result { labels .get(&u32::from(index)) @@ -90,7 +90,7 @@ pub(super) fn lookup(labels: &BTreeMap, index: u16) -> Result Result { starts .iter() @@ -131,7 +131,7 @@ pub(super) fn byte_to_index(starts: &[u16], byte: u16) -> Result, starts: &[u16], @@ -161,7 +161,7 @@ pub(super) fn resolve_byte( .ok_or_else(|| ClassfileError::Parse(format!("нет метки для смещения {byte}"))) } -/// Метка конца диапазона отладочной таблицы. +/// The end label of a debug table's range. pub(super) fn resolve_end( labels: &BTreeMap, starts: &[u16], diff --git a/crates/noxis-classfile/src/format/parse/code/mod.rs b/crates/noxis-classfile/src/format/parse/code/mod.rs index c6c4ebd..f0e472f 100644 --- a/crates/noxis-classfile/src/format/parse/code/mod.rs +++ b/crates/noxis-classfile/src/format/parse/code/mod.rs @@ -1,10 +1,10 @@ -//! `Code` backend'а → тело метода нашего IR: метки, исключения, кадры. +//! Backend `Code` → our IR method body: labels, exceptions, frames. //! -//! Backend уже перевёл байтовые смещения в номера инструкций — конвертеры -//! работают прямо с ними: метки ставятся на целях переходов, границах -//! try-блоков и позициях отладочных таблиц; кадры переносятся как есть -//! (индексные дельты). Позиции `LineNumberTable`/`LocalVariableTable` — -//! тоже метки, поэтому вставки пассов их не ломают (байты досчитает writer). +//! The backend already turned byte offsets into instruction indices - the +//! converters work directly with them: labels are placed on branch targets, +//! try-block boundaries and debug-table positions; frames are carried over as-is +//! (index deltas). `LineNumberTable`/`LocalVariableTable` positions are labels +//! too, so pass insertions don't break them (the writer recomputes the bytes). mod frames; mod labels; @@ -27,7 +27,7 @@ use crate::model::{ use frames::{catch_type, to_frames}; use labels::{assign, collect_debug_labels, label_indexes, lookup, resolve_byte, resolve_end}; -/// Тело метода целиком: backend `Code` → наш [`Code`]. +/// The whole method body: backend `Code` → our [`Code`]. pub(super) fn convert_code( max_stack: u16, max_locals: u16, @@ -150,7 +150,7 @@ pub(super) fn convert_code( }) } -/// Байтовые смещения инструкций и длина тела метода. +/// Instruction byte offsets and the method body length. fn layout(code: &[Instruction]) -> Result<(Vec, u16), ClassfileError> { let mut cursor = Cursor::new(Vec::new()); let mut offsets = Vec::with_capacity(code.len()); diff --git a/crates/noxis-classfile/src/format/parse/insns/basic.rs b/crates/noxis-classfile/src/format/parse/insns/basic.rs index f1f7025..eb1d91a 100644 --- a/crates/noxis-classfile/src/format/parse/insns/basic.rs +++ b/crates/noxis-classfile/src/format/parse/insns/basic.rs @@ -1,4 +1,4 @@ -//! Простые инструкции без ссылок на пул (кроме `ldc`) и без ветвлений. +//! Simple instructions with no pool references (except `ldc`) and no branches. use ristretto_classfile::ConstantPool; use ristretto_classfile::attributes::Instruction; @@ -7,7 +7,7 @@ use super::super::pool::const_from; use crate::error::ClassfileError; use crate::insn::{Arith, ArrayKind, Const, Convert, Insn, Prim, SlotKind}; -/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. +/// `Some` - the instruction is covered; `None` - hand it to the next converters. pub(super) fn convert_basic( instruction: &Instruction, pool: &ConstantPool<'_>, diff --git a/crates/noxis-classfile/src/format/parse/insns/flow.rs b/crates/noxis-classfile/src/format/parse/insns/flow.rs index cfb3249..7d3b65b 100644 --- a/crates/noxis-classfile/src/format/parse/insns/flow.rs +++ b/crates/noxis-classfile/src/format/parse/insns/flow.rs @@ -1,4 +1,4 @@ -//! Ветвления, `switch` и возвраты: абсолютные/относительные цели → метки. +//! Branches, `switch` and returns: absolute/relative targets → labels. use ristretto_classfile::attributes::{Instruction, LookupSwitch, TableSwitch}; @@ -6,7 +6,7 @@ use super::Resolver; use crate::error::ClassfileError; use crate::insn::{BranchCond, Cond, Insn, Label, Prim}; -/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. +/// `Some` - the instruction is covered; `None` - hand it to the next converters. pub(super) fn convert_flow( instruction: &Instruction, index: u16, @@ -52,7 +52,7 @@ fn branch(cond: BranchCond, target: u16, resolve: &Resolver<'_>) -> Result) -> Result { let absolute = i32::from(index) .checked_add(delta) diff --git a/crates/noxis-classfile/src/format/parse/insns/mod.rs b/crates/noxis-classfile/src/format/parse/insns/mod.rs index 93e9efc..c5291f6 100644 --- a/crates/noxis-classfile/src/format/parse/insns/mod.rs +++ b/crates/noxis-classfile/src/format/parse/insns/mod.rs @@ -1,9 +1,8 @@ -//! `Instruction` backend'а → [`Insn`](crate::insn::Insn) нашего IR. +//! Backend `Instruction` → [`Insn`](crate::insn::Insn) of our IR. //! -//! Смещения ветвлений приходят из backend'а (абсолютные для `if*`/`goto`, -//! относительные от начала инструкции для `switch`), поэтому конвертация -//! принимает резолвер смещения в [`Label`](crate::insn::Label) — метки -//! назначает вызывающий код. +//! Branch offsets come from the backend (absolute for `if*`/`goto`, relative to +//! the instruction start for `switch`), so conversion takes a resolver from an +//! offset to a [`Label`](crate::insn::Label) - the calling code assigns labels. mod basic; mod flow; @@ -15,10 +14,10 @@ use ristretto_classfile::attributes::Instruction; use crate::error::ClassfileError; use crate::insn::{Insn, Label}; -/// Резолвит абсолютное смещение байткода в метку. +/// Resolves an absolute bytecode offset into a label. pub(super) type Resolver<'a> = dyn Fn(u16) -> Result + 'a; -/// Конвертировать одну инструкцию. `index` — её номер в теле метода (нужно `switch`). +/// Convert one instruction. `index` - its number in the method body (`switch` needs it). pub(super) fn convert( instruction: &Instruction, index: u16, diff --git a/crates/noxis-classfile/src/format/parse/insns/refs.rs b/crates/noxis-classfile/src/format/parse/insns/refs.rs index de2dc67..f5623fe 100644 --- a/crates/noxis-classfile/src/format/parse/insns/refs.rs +++ b/crates/noxis-classfile/src/format/parse/insns/refs.rs @@ -1,4 +1,4 @@ -//! Поля, вызовы и создание объектов: индексы пула → строки IR. +//! Fields, calls and object creation: pool indices → IR strings. use ristretto_classfile::ConstantPool; use ristretto_classfile::attributes::{ArrayType, Instruction}; @@ -7,7 +7,7 @@ use super::super::pool::{class_name, dynamic_parts, expect_kind, is_interface, r use crate::error::ClassfileError; use crate::insn::{ArrayKind, Insn, InvokeKind}; -/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. +/// `Some` - the instruction is covered; `None` - hand it to the next converters. pub(super) fn convert_ref( instruction: &Instruction, pool: &ConstantPool<'_>, diff --git a/crates/noxis-classfile/src/format/parse/mod.rs b/crates/noxis-classfile/src/format/parse/mod.rs index d103e9b..38927ad 100644 --- a/crates/noxis-classfile/src/format/parse/mod.rs +++ b/crates/noxis-classfile/src/format/parse/mod.rs @@ -1,10 +1,11 @@ -//! Backend `ristretto_classfile` → наш IR: пул, инструкции, тела методов. +//! Backend `ristretto_classfile` → our IR: pool, instructions, method bodies. //! -//! Пока ниоткуда не подключён (P1): `format` вернёт `Unimplemented`, пока не -//! будут готовы `parse`/`write` классового уровня поверх этих конвертеров. -//! Дерево уже разбито по ответственностям, чтобы подключение было одним -//! `mod parse` без рефакторинга. +//! Not wired in from anywhere yet (P1): `format` returns `Unimplemented` until +//! class-level `parse`/`write` are ready on top of these converters. The tree +//! is already split by responsibility so wiring is a single `mod parse` with no +//! refactoring. +pub(super) mod annos; pub(super) mod attrs; pub(super) mod class; pub(super) mod code; diff --git a/crates/noxis-classfile/src/format/parse/pool.rs b/crates/noxis-classfile/src/format/parse/pool.rs index dd8c538..8908611 100644 --- a/crates/noxis-classfile/src/format/parse/pool.rs +++ b/crates/noxis-classfile/src/format/parse/pool.rs @@ -1,11 +1,11 @@ -//! Разрешение индексов constant pool в строки нашего IR. +//! Resolving constant-pool indices into strings of our IR. use ristretto_classfile::{Constant, ConstantPool, ReferenceKind}; use crate::error::ClassfileError; use crate::insn::{Const, InvokeKind}; -/// Имя класса по `CONSTANT_Class`. +/// The class name from a `CONSTANT_Class`. pub(super) fn class_name(pool: &ConstantPool<'_>, index: u16) -> Result { let name = pool .try_get_class(index) @@ -13,7 +13,7 @@ pub(super) fn class_name(pool: &ConstantPool<'_>, index: u16) -> Result, index: u16, @@ -45,7 +45,7 @@ pub(super) fn ref_parts( Ok((owner, name, descriptor)) } -/// `(name, descriptor)` для `CONSTANT_NameAndType`. +/// `(name, descriptor)` for a `CONSTANT_NameAndType`. pub(super) fn name_and_type( pool: &ConstantPool<'_>, index: u16, @@ -58,7 +58,7 @@ pub(super) fn name_and_type( Ok((name, descriptor)) } -/// Строка из `CONSTANT_Utf8`. +/// The string from a `CONSTANT_Utf8`. pub(super) fn utf8(pool: &ConstantPool<'_>, index: u16) -> Result { let value = pool .try_get_utf8(index) @@ -66,7 +66,7 @@ pub(super) fn utf8(pool: &ConstantPool<'_>, index: u16) -> Result, index: u16) -> Result { let constant = pool .try_get(index) @@ -111,7 +111,7 @@ pub(super) fn const_from(pool: &ConstantPool<'_>, index: u16) -> Result, index: u16, @@ -134,12 +134,12 @@ pub(super) fn dynamic_parts( Ok((name, descriptor, bootstrap)) } -/// Вид вызова по индексу ссылки: интерфейсная или обычная. +/// Call kind by reference index: interface or regular. pub(super) fn is_interface(pool: &ConstantPool<'_>, index: u16) -> bool { matches!(pool.try_get(index), Ok(Constant::InterfaceMethodRef { .. })) } -/// JVMS §5.4.3.5: номер `reference_kind` для `CONSTANT_MethodHandle`. +/// JVMS §5.4.3.5: the `reference_kind` number for a `CONSTANT_MethodHandle`. pub(super) fn kind_code(kind: &ReferenceKind) -> u8 { match kind { ReferenceKind::GetField => 1, @@ -154,11 +154,11 @@ pub(super) fn kind_code(kind: &ReferenceKind) -> u8 { } } -/// Проверка, что `Invoke` действительно ссылается на ожидаемый вид. +/// Checks that an `Invoke` really refers to the expected kind. /// -/// JVM принимает `Methodref` и `InterfaceMethodref` для всех видов вызова, -/// кроме `invokeinterface` (там только интерфейсная); строгость сверх JVM -/// ломает чтение реальных классов (статические методы интерфейсов). +/// The JVM accepts both `Methodref` and `InterfaceMethodref` for every call +/// kind except `invokeinterface` (interface reference only there); being +/// stricter than the JVM breaks reading real classes (interface static methods). pub(super) fn expect_kind( pool: &ConstantPool<'_>, index: u16, diff --git a/crates/noxis-classfile/src/format/write/annotations.rs b/crates/noxis-classfile/src/format/write/annotations.rs new file mode 100644 index 0000000..e62fc39 --- /dev/null +++ b/crates/noxis-classfile/src/format/write/annotations.rs @@ -0,0 +1,149 @@ +//! Runtime-visible/invisible annotations: IR → backend structures. + +use ristretto_classfile::attributes::{ + Annotation as RtAnno, AnnotationElement as RtElem, AnnotationValuePair as RtPair, + ParameterAnnotation as RtParamAnno, TargetPath as RtPath, TargetType as RtTarget, + TypeAnnotation as RtTypeAnno, +}; +use ristretto_classfile::byte_reader::ByteReader; + +use super::pool::Pool; +use crate::error::ClassfileError; +use crate::insn::Const; +use crate::model::{Annotation, AnnotationValue, TypeAnnotation}; +/// The `annotations` list of a visible/invisible annotation attribute. +pub(super) fn list(annos: &[Annotation], pool: &mut Pool) -> Result, ClassfileError> { + annos.iter().map(|anno| annotation(anno, pool)).collect() +} + +/// The per-parameter lists of a parameter-annotation attribute. +pub(super) fn parameters( + params: &[Vec], + pool: &mut Pool, +) -> Result, ClassfileError> { + params + .iter() + .map(|param| { + Ok(RtParamAnno { + annotations: list(param, pool)?, + }) + }) + .collect() +} + +/// The `type_annotations` list of a type-annotation attribute. +pub(super) fn type_list( + annos: &[TypeAnnotation], + pool: &mut Pool, +) -> Result, ClassfileError> { + annos + .iter() + .map(|anno| type_annotation(anno, pool)) + .collect() +} + +/// One IR annotation → backend structure (fresh pool indices). +pub(super) fn annotation(anno: &Annotation, pool: &mut Pool) -> Result { + Ok(RtAnno { + type_index: pool.utf8(&anno.descriptor)?, + elements: anno + .elements + .iter() + .map(|(name, value)| { + Ok(RtPair { + name_index: pool.utf8(name)?, + value: element(value, pool)?, + }) + }) + .collect::>()?, + }) +} + +/// One IR type annotation → backend structure (fresh pool indices). The +/// opaque `target` bytes (`target_info` + `type_path`) carry no pool +/// references and are re-deserialized into backend structs verbatim. +pub(super) fn type_annotation( + anno: &TypeAnnotation, + pool: &mut Pool, +) -> Result { + let mut reader = ByteReader::new(&anno.target); + let target_type = RtTarget::from_bytes(&mut reader) + .map_err(|e| ClassfileError::Write(format!("битый target_info: {e}")))?; + let path_len = reader + .read_u8() + .map_err(|e| ClassfileError::Write(format!("битый type_path: {e}")))?; + let mut type_path = Vec::with_capacity(path_len as usize); + for _ in 0..path_len { + type_path.push( + RtPath::from_bytes(&mut reader) + .map_err(|e| ClassfileError::Write(format!("битый type_path: {e}")))?, + ); + } + Ok(RtTypeAnno { + target_type, + type_path, + type_index: pool.utf8(&anno.descriptor)?, + elements: anno + .elements + .iter() + .map(|(name, value)| { + Ok(RtPair { + name_index: pool.utf8(name)?, + value: element(value, pool)?, + }) + }) + .collect::>()?, + }) +} + +/// One IR element value → backend structure, tag preserved. +pub(super) fn element(value: &AnnotationValue, pool: &mut Pool) -> Result { + fn int(v: i32, pool: &mut Pool) -> Result { + pool.constant(&Const::Int(v)) + } + Ok(match value { + AnnotationValue::Byte(v) => RtElem::Byte { + const_value_index: int(*v, pool)?, + }, + AnnotationValue::Char(v) => RtElem::Char { + const_value_index: int(*v, pool)?, + }, + AnnotationValue::Short(v) => RtElem::Short { + const_value_index: int(*v, pool)?, + }, + AnnotationValue::Boolean(v) => RtElem::Boolean { + const_value_index: int(*v, pool)?, + }, + AnnotationValue::Int(v) => RtElem::Int { + const_value_index: int(*v, pool)?, + }, + AnnotationValue::Long(v) => RtElem::Long { + const_value_index: pool.constant(&Const::Long(*v))?, + }, + AnnotationValue::Float(v) => RtElem::Float { + const_value_index: pool.constant(&Const::Float(*v))?, + }, + AnnotationValue::Double(v) => RtElem::Double { + const_value_index: pool.constant(&Const::Double(*v))?, + }, + AnnotationValue::String(v) => RtElem::String { + const_value_index: pool.utf8(v)?, + }, + AnnotationValue::Enum { descriptor, name } => RtElem::Enum { + type_name_index: pool.utf8(descriptor)?, + const_name_index: pool.utf8(name)?, + }, + AnnotationValue::Class(desc) => RtElem::Class { + class_info_index: pool.utf8(desc)?, + }, + AnnotationValue::Nested(nested) => RtElem::Annotation { + annotation: annotation(nested, pool)?, + }, + AnnotationValue::Array(values) => RtElem::Array { + values: values + .iter() + .map(|value| element(value, pool)) + .collect::>()?, + }, + }) +} diff --git a/crates/noxis-classfile/src/format/write/attrs.rs b/crates/noxis-classfile/src/format/write/attrs.rs index aa45119..8418b47 100644 --- a/crates/noxis-classfile/src/format/write/attrs.rs +++ b/crates/noxis-classfile/src/format/write/attrs.rs @@ -1,26 +1,27 @@ -//! Атрибуты нашего IR → атрибуты backend'а. +//! Our IR attributes → backend attributes. //! -//! Имена атрибутов (`SourceFile`, …) интернируются в пул здесь же — backend -//! хранит только `name_index`, строка восстанавливается при чтении. +//! Attribute names (`SourceFile`, …) are interned into the pool right here - the +//! backend stores only `name_index`, and the string is recovered on read. use ristretto_classfile::attributes::{ Attribute as RtAttr, LineNumber as RtLine, LocalVariableTable as RtLocal, LocalVariableTypeTable as RtLocalType, Record as RtRecord, }; +use super::annotations; use super::helpers; use super::pool::Pool; use crate::error::ClassfileError; use crate::insn::Label; use crate::model::{Attribute, LineNumber, LocalVariable, LocalVariableType}; -/// Позиции таблиц кода: метки → байты текущего layout. +/// Code-table positions: labels → bytes of the current layout. pub(super) struct Positions<'a> { pub resolve: &'a dyn Fn(Label) -> Result, pub byte_of: &'a dyn Fn(u32) -> Result, } -/// `LineNumberTable`: backend хранит номера инструкций и маппит сам. +/// `LineNumberTable`: the backend stores instruction numbers and maps them itself. pub(super) fn line_number_table( lines: &[LineNumber], pool: &mut Pool, @@ -43,7 +44,7 @@ pub(super) fn line_number_table( }) } -/// `LocalVariableTable`/`TypeTable` с пересчётом диапазона. +/// `LocalVariableTable`/`TypeTable` with the range recomputed. pub(super) fn local_table( vars: &[LocalVariable], pool: &mut Pool, @@ -66,7 +67,7 @@ pub(super) fn local_table( .collect::>()?, }) } -/// Та же таблица для типов (`signature` вместо дескриптора). +/// The same table for types (`signature` instead of a descriptor). pub(super) fn local_type_table( vars: &[LocalVariableType], pool: &mut Pool, @@ -103,7 +104,7 @@ fn range( Ok((first, length)) } -/// Один наш атрибут → атрибут backend'а. +/// One of our attributes → a backend attribute. pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result { Ok(match attr { Attribute::SourceFile(name) => RtAttr::SourceFile { @@ -145,6 +146,13 @@ pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result>()?, }, + Attribute::PermittedSubclasses(classes) => RtAttr::PermittedSubclasses { + name_index: pool.utf8("PermittedSubclasses")?, + class_indexes: classes + .iter() + .map(|name| pool.class(name)) + .collect::>()?, + }, Attribute::ConstantValue(value) => RtAttr::ConstantValue { name_index: pool.utf8("ConstantValue")?, constant_value_index: pool.constant(value)?, @@ -171,6 +179,40 @@ pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result>()?, }, + Attribute::RuntimeVisibleAnnotations(annos) => RtAttr::RuntimeVisibleAnnotations { + name_index: pool.utf8("RuntimeVisibleAnnotations")?, + annotations: annotations::list(annos, pool)?, + }, + Attribute::RuntimeInvisibleAnnotations(annos) => RtAttr::RuntimeInvisibleAnnotations { + name_index: pool.utf8("RuntimeInvisibleAnnotations")?, + annotations: annotations::list(annos, pool)?, + }, + Attribute::RuntimeVisibleParameterAnnotations(params) => { + RtAttr::RuntimeVisibleParameterAnnotations { + name_index: pool.utf8("RuntimeVisibleParameterAnnotations")?, + parameter_annotations: annotations::parameters(params, pool)?, + } + } + Attribute::RuntimeInvisibleParameterAnnotations(params) => { + RtAttr::RuntimeInvisibleParameterAnnotations { + name_index: pool.utf8("RuntimeInvisibleParameterAnnotations")?, + parameter_annotations: annotations::parameters(params, pool)?, + } + } + Attribute::RuntimeVisibleTypeAnnotations(annos) => RtAttr::RuntimeVisibleTypeAnnotations { + name_index: pool.utf8("RuntimeVisibleTypeAnnotations")?, + type_annotations: annotations::type_list(annos, pool)?, + }, + Attribute::RuntimeInvisibleTypeAnnotations(annos) => { + RtAttr::RuntimeInvisibleTypeAnnotations { + name_index: pool.utf8("RuntimeInvisibleTypeAnnotations")?, + type_annotations: annotations::type_list(annos, pool)?, + } + } + Attribute::AnnotationDefault(value) => RtAttr::AnnotationDefault { + name_index: pool.utf8("AnnotationDefault")?, + element: annotations::element(value, pool)?, + }, Attribute::Raw { name, data } => RtAttr::Unknown { name_index: pool.utf8(name)?, info: data.clone(), diff --git a/crates/noxis-classfile/src/format/write/code/frames.rs b/crates/noxis-classfile/src/format/write/code/frames.rs index 20f5c7a..7cd6abe 100644 --- a/crates/noxis-classfile/src/format/write/code/frames.rs +++ b/crates/noxis-classfile/src/format/write/code/frames.rs @@ -1,9 +1,9 @@ -//! Кадры `StackMapTable` при записи: вариант в вариант, дельты по инструкциям. +//! `StackMapTable` frames on write: variant to variant, deltas per instruction. //! -//! Наш IR хранит `offset_delta` в номерах инструкций; backend при `to_bytes` -//! сам пересчитает их в байты. Компактный формат (`Same`/`SameLocals`) годен -//! только когда **байтовая** дельта ≤ 63 — иначе нужен расширенный вариант. -//! Выбор делаем по байтовой дельте: байты считаются от layout текущего метода. +//! Our IR stores `offset_delta` in instruction numbers; the backend recomputes +//! them into bytes on `to_bytes`. The compact form (`Same`/`SameLocals`) is valid +//! only when the **byte** delta is ≤ 63 - otherwise the extended form is needed. +//! We choose by the byte delta: bytes are computed from the current method's layout. use ristretto_classfile::attributes::{StackFrame as RtFrame, VerificationType as RtType}; @@ -11,10 +11,10 @@ use super::super::pool::Pool; use crate::error::ClassfileError; use crate::format::{StackMapFrame, VerificationType}; -/// Байтовое смещение начала инструкции (для расчёта дельт кадров). +/// The byte offset of an instruction's start (for computing frame deltas). type ByteOf<'a> = &'a (dyn Fn(u32) -> Result + 'a); -/// Кадры IR → кадры backend'а (индексные дельты — как есть). +/// IR frames → backend frames (index deltas - as-is). pub(super) fn convert_frames( frames: &[StackMapFrame], pool: &mut Pool, @@ -32,7 +32,7 @@ pub(super) fn convert_frames( last_instruction + delta + 1 }; let byte = byte_of(instruction)?; - // Байтовая дельта относительно конца предыдущего кадра. + // Byte delta relative to the end of the previous frame. let byte_delta = if first { byte } else { @@ -48,7 +48,7 @@ pub(super) fn convert_frames( Ok(out) } -/// `byte_delta` — истинная байтовая дельта; компактный вид годен лишь при ≤ 63. +/// `byte_delta` is the true byte delta; the compact form is valid only when ≤ 63. fn build_frame( frame: &StackMapFrame, pool: &mut Pool, @@ -60,8 +60,8 @@ fn build_frame( Ok(match frame { StackMapFrame::Same { .. } => { if byte_delta <= 63 { - // Backend при verify()/to_bytes читает frame_type как дельту по - // ИНСТРУКЦИЯМ и сам пересчитает её в байты (≤ 63 — влезает). + // The backend, in verify()/to_bytes, reads frame_type as a delta by + // INSTRUCTION and recomputes it into bytes itself (≤ 63 fits). RtFrame::SameFrame { frame_type: delta as u8, } @@ -97,7 +97,7 @@ fn build_frame( })?; if !(1..=3).contains(&count) { return Err(ClassfileError::Write(format!( - "append-кадр на {count} local'ов (нужно 1–3)" + "append-кадр на {count} local'ов (нужно 1-3)" ))); } RtFrame::AppendFrame { diff --git a/crates/noxis-classfile/src/format/write/code/insns.rs b/crates/noxis-classfile/src/format/write/code/insns.rs index 031682a..e7781b1 100644 --- a/crates/noxis-classfile/src/format/write/code/insns.rs +++ b/crates/noxis-classfile/src/format/write/code/insns.rs @@ -1,8 +1,8 @@ -//! Наш [`Insn`](crate::insn::Insn) → `Instruction` backend'а. +//! Our [`Insn`](crate::insn::Insn) → the backend's `Instruction`. //! -//! Обратная сторона `super::super::parse::insns`: метки резолвятся в -//! абсолютные номера инструкций (`switch` — в дельты от себя), константы -//! и ссылки уходят в пул через [`Pool`](super::super::pool::Pool). +//! The reverse side of `super::super::parse::insns`: labels resolve into +//! absolute instruction numbers (`switch` - into deltas from itself), constants +//! and references go to the pool via [`Pool`](super::super::pool::Pool). use indexmap::IndexMap; use ristretto_classfile::attributes::{Instruction as RtInsn, LookupSwitch, TableSwitch}; @@ -13,9 +13,9 @@ use super::{branch, delta, fit_index, ret_op}; use crate::error::ClassfileError; use crate::insn::{Insn, Label, SlotKind}; -/// Одна инструкция IR → инструкция backend'а (`None` — маркер метки). +/// One IR instruction → a backend instruction (`None` - a label marker). /// -/// `index` — номер инструкции в методе (нужен `switch`-дельтам). +/// `index` - the instruction's number in the method (needed for `switch` deltas). pub(crate) fn convert( insn: &Insn, index: u32, @@ -96,8 +96,9 @@ pub(crate) fn convert( owner, name, descriptor, + itf, .. - } => invoke(*kind, owner, name, descriptor, pool)?, + } => invoke(*kind, owner, name, descriptor, *itf, pool)?, Insn::InvokeDynamic { name, descriptor, @@ -178,7 +179,7 @@ fn store(slot: u16, kind: SlotKind) -> RtInsn { } } -/// Короткая форма при слоте ≤255, иначе `wide`-форма. +/// The short form when the slot is ≤255, otherwise the `wide` form. fn narrow(slot: u16, short: fn(u8) -> RtInsn, wide: fn(u16) -> RtInsn) -> RtInsn { u8::try_from(slot).map(short).unwrap_or_else(|_| wide(slot)) } diff --git a/crates/noxis-classfile/src/format/write/code/mod.rs b/crates/noxis-classfile/src/format/write/code/mod.rs index d621396..fa9b671 100644 --- a/crates/noxis-classfile/src/format/write/code/mod.rs +++ b/crates/noxis-classfile/src/format/write/code/mod.rs @@ -1,7 +1,7 @@ -//! Тело метода нашего IR → атрибут `Code` backend'а. +//! Our IR method body → the backend `Code` attribute. //! -//! Метки резолвятся в номера инструкций один раз здесь; дальше backend сам -//! пересчитывает номера в байтовые смещения при `to_bytes`. +//! Labels resolve into instruction numbers once, here; then the backend +//! recomputes numbers into byte offsets on `to_bytes`. mod frames; pub(crate) mod insns; @@ -22,8 +22,15 @@ use crate::model::{Attribute, Code, ExceptionHandler}; use frames::convert_frames; -/// Тело метода → готовый атрибут `Code` (с логическими номерами инструкций). -pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result { +/// Method body → a ready `Code` attribute (with logical instruction numbers). +/// +/// `emit_frames` is false for class-file versions below 50 (Java 6): those use +/// the type-inference verifier and must not carry a `StackMapTable`. +pub(super) fn convert_code( + code: &Code, + pool: &mut Pool, + emit_frames: bool, +) -> Result { let (labels, bare) = split_marks(&code.insns)?; let resolve = |label: Label| -> Result { labels @@ -55,11 +62,15 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result attrs::line_number_table(lines, pool, &positions)?, Attribute::LocalVariableTable(vars) => attrs::local_table(vars, pool, &positions)?, Attribute::LocalVariableTypeTable(vars) => { @@ -68,7 +79,7 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result attrs::convert(other, pool)?, }); } - if !frames.is_empty() { + if emit_frames && !frames.is_empty() { attributes.push(RtAttr::StackMapTable { name_index: pool.utf8("StackMapTable")?, frames, @@ -84,7 +95,7 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result Result<(BTreeMap, Vec<&Insn>), ClassfileError> { let mut labels = BTreeMap::new(); let mut bare = Vec::with_capacity(insns.len()); @@ -108,10 +119,10 @@ fn split_marks(insns: &[Insn]) -> Result<(BTreeMap, Vec<&Insn>), Cla Ok((labels, bare)) } -/// Номер инструкции → байтовое смещение (замер с заглушками целей). +/// Instruction number → byte offset (measured with placeholder targets). /// -/// В карту входит и конец кода (`len` → длина): концы диапазонов указывают -/// за последнюю инструкцию. +/// The map also includes the code end (`len` → length): range ends point past +/// the last instruction. pub(crate) fn measure(insns: &[RtInsn]) -> Result, ClassfileError> { let mut map = BTreeMap::new(); let mut cursor = Cursor::new(Vec::new()); @@ -132,7 +143,7 @@ pub(crate) fn measure(insns: &[RtInsn]) -> Result, ClassfileE Ok(map) } -/// Цели ветвлений не влияют на размер — подменяем текущей позицией для замера. +/// Branch targets don't affect size - substitute the current position for sizing. fn smash_targets(insn: &mut RtInsn, position: u16) { match insn { RtInsn::Ifeq(target) @@ -178,7 +189,7 @@ fn entry( }) } -/// Условный переход IR → `if*` backend'а. +/// An IR conditional branch → the backend's `if*`. fn branch(cond: BranchCond, target: u32) -> Result { let target = fit_index(target)?; Ok(match cond { @@ -211,13 +222,13 @@ fn ret_op(prim: Option) -> RtInsn { } } -/// Номер инструкции обязан влезать в `u16` (метод < 64 КБ кода). +/// The instruction number must fit in `u16` (method < 64 KB of code). fn fit_index(index: u32) -> Result { u16::try_from(index) .map_err(|_| ClassfileError::Write(format!("номер инструкции {index} вне u16"))) } -/// Дельта `switch`: цель минус позиция самого `switch`. +/// A `switch` delta: the target minus the `switch` instruction's own position. fn delta(index: u32, target: u32) -> Result { let (index, target) = (to_i32(index)?, to_i32(target)?); target diff --git a/crates/noxis-classfile/src/format/write/code/ops.rs b/crates/noxis-classfile/src/format/write/code/ops.rs index ef57be7..f8566c6 100644 --- a/crates/noxis-classfile/src/format/write/code/ops.rs +++ b/crates/noxis-classfile/src/format/write/code/ops.rs @@ -1,4 +1,4 @@ -//! Операнды: константы, арифметика, массивы, вызовы. +//! Operands: constants, arithmetic, arrays, calls. use ristretto_classfile::attributes::{ArrayType, Instruction as RtInsn}; @@ -6,7 +6,7 @@ use super::super::pool::Pool; use crate::error::ClassfileError; use crate::insn::{Arith, ArrayKind, Const, Convert, InvokeKind, Prim}; -/// Константа: короткие формы (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` через пул. +/// A constant: short forms (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` through the pool. pub(super) fn int_const(value: &Const, pool: &mut Pool) -> Result { Ok(match value { Const::Int(v) => match *v { @@ -166,29 +166,34 @@ pub(super) fn convert_op(op: Convert) -> RtInsn { } } +/// `invoke*` family: the `itf` flag is authoritative (a Static/Special +/// call may still target an interface method - `List.of`), so the pool +/// entry kind follows it, not the opcode alone. pub(super) fn invoke( kind: InvokeKind, owner: &str, name: &str, descriptor: &str, + itf: bool, pool: &mut Pool, ) -> Result { + let itf = itf || matches!(kind, InvokeKind::Interface); Ok(match kind { InvokeKind::Virtual => { - RtInsn::Invokevirtual(pool.method_ref(owner, name, descriptor, kind)?) + RtInsn::Invokevirtual(pool.method_ref(owner, name, descriptor, itf)?) } InvokeKind::Special => { - RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, kind)?) + RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, itf)?) } - InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, kind)?), + InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, itf)?), InvokeKind::Interface => { - let index = pool.method_ref(owner, name, descriptor, kind)?; + let index = pool.method_ref(owner, name, descriptor, itf)?; RtInsn::Invokeinterface(index, arg_count(descriptor)?) } }) } -/// Байт `count` для `invokeinterface`: слоты аргументов + `objectref`. +/// The `count` byte for `invokeinterface`: argument slots + `objectref`. fn arg_count(descriptor: &str) -> Result { let params = descriptor .split_once('(') @@ -229,7 +234,7 @@ fn arg_count(descriptor: &str) -> Result { .map_err(|_| ClassfileError::Write(format!("слишком много аргументов в {descriptor}"))) } -/// Пропустить символы до разделителя (включительно); `false` — строка кончилась. +/// Skip characters up to the separator (inclusive); `false` - the string ended. fn skip_to(chars: &mut std::str::Chars<'_>, end: char) -> bool { for char in chars { if char == end { diff --git a/crates/noxis-classfile/src/format/write/helpers.rs b/crates/noxis-classfile/src/format/write/helpers.rs index f314cf1..5768a7e 100644 --- a/crates/noxis-classfile/src/format/write/helpers.rs +++ b/crates/noxis-classfile/src/format/write/helpers.rs @@ -1,8 +1,9 @@ -//! Хелперы сборки `InnerClasses`/`BootstrapMethods`/`MethodParameters`. +//! Helpers building `InnerClasses`/`BootstrapMethods`/`MethodParameters`. //! -//! Вынесены из `attrs`, чтобы тот держался в лимите 250 строк; логика не -//! изменилась — только место. Каждый строит запись backend'а из элемента IR, -//! интернируя имена/дескрипторы и резолвя индексы `CONSTANT_Class` через пул. +//! Moved out of `attrs` so it stays within the 250-line limit; the logic is +//! unchanged - only the location. Each builds a backend entry from an IR +//! element, interning names/descriptors and resolving `CONSTANT_Class` indices +//! through the pool. use ristretto_classfile::MethodAccessFlags; use ristretto_classfile::attributes::{ @@ -50,7 +51,7 @@ pub(super) fn bootstrap( }) } -/// Аргумент bootstrap-метода: те же константы, что в `ldc`, плюс `Dynamic`. +/// A bootstrap-method argument: the same constants as in `ldc`, plus `Dynamic`. fn bootstrap_arg(arg: &Const, pool: &mut Pool) -> Result { match arg { Const::Dynamic { diff --git a/crates/noxis-classfile/src/format/write/mod.rs b/crates/noxis-classfile/src/format/write/mod.rs index 3561059..8419aec 100644 --- a/crates/noxis-classfile/src/format/write/mod.rs +++ b/crates/noxis-classfile/src/format/write/mod.rs @@ -1,8 +1,9 @@ -//! Наш IR → байты `.class` через backend `ristretto_classfile`. +//! Our IR → `.class` bytes through the `ristretto_classfile` backend. //! -//! Пул собирается с нуля детерминированным обходом; backend сам пересчитывает -//! номера инструкций в байтовые смещения и проверяет результат (`verify`). +//! The pool is built from scratch by a deterministic walk; the backend recomputes +//! instruction numbers into byte offsets and verifies the result (`verify`). +mod annotations; mod attrs; pub(crate) mod code; mod helpers; @@ -16,11 +17,16 @@ use ristretto_classfile::{ use crate::error::ClassfileError; use crate::model::{ClassFile, Field, Method}; -/// Класс нашего IR → байты `.class`. +/// Our IR class → `.class` bytes. pub(crate) fn write_class(class: &ClassFile) -> Result, ClassfileError> { let mut pool = pool::Pool::new(); let version = RtVersion::from(class.version.major, class.version.minor) .map_err(|e| ClassfileError::Write(e.to_string()))?; + // `StackMapTable` is only legal from class-file version 50 (Java 6). Older + // classes use the type-inference verifier; emitting the attribute makes + // ASM/Paper reject the file ("Class versions V1_5 or less must use + // F_NEW frames"). Real case: the string-decoder is built at major 49. + let emit_frames = class.version.major >= 50; let this_class = pool.class(&class.this_class)?; let super_class = match &class.super_class { None => 0, @@ -36,7 +42,7 @@ pub(crate) fn write_class(class: &ClassFile) -> Result, ClassfileError> } let mut methods = Vec::with_capacity(class.methods.len()); for method in &class.methods { - methods.push(convert_method(method, &mut pool)?); + methods.push(convert_method(method, &mut pool, emit_frames)?); } let mut attributes = Vec::with_capacity(class.attributes.len()); for attr in &class.attributes { @@ -77,13 +83,17 @@ fn convert_field(field: &Field, pool: &mut pool::Pool) -> Result Result { +fn convert_method( + method: &Method, + pool: &mut pool::Pool, + emit_frames: bool, +) -> Result { let mut attributes = Vec::with_capacity(method.attributes.len() + 1); for attr in &method.attributes { attributes.push(attrs::convert(attr, pool)?); } if let Some(code) = &method.code { - attributes.push(code::convert_code(code, pool)?); + attributes.push(code::convert_code(code, pool, emit_frames)?); } Ok(RtMethod { access_flags: MethodAccessFlags::from_bits_truncate(method.access_flags), diff --git a/crates/noxis-classfile/src/format/write/pool/mod.rs b/crates/noxis-classfile/src/format/write/pool/mod.rs index 27cccc1..2900d0e 100644 --- a/crates/noxis-classfile/src/format/write/pool/mod.rs +++ b/crates/noxis-classfile/src/format/write/pool/mod.rs @@ -1,15 +1,15 @@ -//! Сборка constant pool при записи: строки нашего IR → индексы backend'а. +//! Building the constant pool on write: our IR strings → backend indices. //! -//! Пул строится с нуля детерминированным обходом (классы, поля, методы, -//! атрибуты, код), поэтому одинаковый IR даёт одинаковые байты. Индексы -//! `Raw`-атрибутов при этом не переносятся — см. `super::attrs`. +//! The pool is built from scratch by a deterministic walk (classes, fields, +//! methods, attributes, code), so identical IR yields identical bytes. `Raw` +//! attribute indices are not carried over - see `super::attrs`. //! -//! Backend не дедуплицирует: `add_*` всегда толкает новый элемент. Кэшируем -//! семантические ключи сами — иначе `LocalVariableTable` и -//! `LocalVariableTypeTable` получат разные `name_index` для одного имени, и -//! HotSpot отвергнет класс (`LVTT entry ... does not match any LVT entry`). -//! Порядок обхода детерминирован, поэтому кэш меняет только компактность пула. -//! Референсы (поле/метод/хендл/динамик) — в [`refs`]. +//! The backend does not deduplicate: `add_*` always pushes a new entry. We cache +//! semantic keys ourselves - otherwise `LocalVariableTable` and +//! `LocalVariableTypeTable` would get different `name_index` values for the same +//! name, and HotSpot would reject the class (`LVTT entry ... does not match any +//! LVT entry`). The walk order is deterministic, so the cache only changes pool +//! compactness. References (field/method/handle/dynamic) live in [`refs`]. use std::collections::HashMap; @@ -20,7 +20,7 @@ use crate::insn::Const; mod refs; -/// Строитель пула; живёт только внутри одного `write`. +/// The pool builder; lives only within a single `write`. pub(crate) struct Pool { pub(super) pool: ConstantPool<'static>, pub(super) utf8s: HashMap, @@ -68,8 +68,8 @@ impl Pool { if let Some(&index) = self.name_types.get(&key) { return Ok(index); } - // Собираем из примитивов, а не `add_name_and_type`: последний толкает - // собственные `Utf8`-строки мимо нашего кэша (дубли в пуле). + // Build from primitives, not `add_name_and_type`: the latter pushes its + // own `Utf8` strings past our cache (pool duplicates). let name_index = self.utf8(name)?; let descriptor_index = self.utf8(descriptor)?; let index = self @@ -96,7 +96,7 @@ impl Pool { Ok(index) } - /// Константа для `ldc`/`ldc2_w`; `dynamic` запрещён (только через bootstrap). + /// A constant for `ldc`/`ldc2_w`; `dynamic` is forbidden (bootstrap only). pub(super) fn constant(&mut self, value: &Const) -> Result { match value { Const::Int(v) => self.pool.add_integer(*v).map_err(write_err), diff --git a/crates/noxis-classfile/src/format/write/pool/refs.rs b/crates/noxis-classfile/src/format/write/pool/refs.rs index 67e6e02..2c93c55 100644 --- a/crates/noxis-classfile/src/format/write/pool/refs.rs +++ b/crates/noxis-classfile/src/format/write/pool/refs.rs @@ -1,15 +1,14 @@ -//! Референсы constant pool: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`. +//! Constant-pool references: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`. //! -//! Это `impl Pool` из [`super`]; вынесено отдельно, чтобы материнский файл -//! держался в лимите структуры. Каждый билдер мемоизирован по семантическому -//! ключу (owner/name/descriptor/…) — одинаковая ссылка всегда получает один -//! индекс, а пул не раздувается дублями (раздувание иначе расширяет `ldc` -//! в `ldc_w` и меняет длину кода при переносе). +//! This is an `impl Pool` from [`super`], split out so the parent file stays +//! within the structure limit. Each builder is memoized by a semantic key +//! (owner/name/descriptor/…) - an identical reference always gets the same index, +//! and the pool doesn't bloat with duplicates (bloat would otherwise widen `ldc` +//! into `ldc_w` and change code length on relocation). use ristretto_classfile::{Constant, ReferenceKind}; use crate::error::ClassfileError; -use crate::insn::InvokeKind; use super::{Pool, write_err}; @@ -42,9 +41,8 @@ impl Pool { owner: &str, name: &str, descriptor: &str, - kind: InvokeKind, + itf: bool, ) -> Result { - let itf = matches!(kind, InvokeKind::Interface); let key = ( owner.to_string(), name.to_string(), @@ -94,7 +92,7 @@ impl Pool { ClassfileError::Write(format!("некорректный reference_kind {kind}: {e}")) })?; let reference = if itf { - self.method_ref(owner, name, descriptor, InvokeKind::Interface)? + self.method_ref(owner, name, descriptor, true)? } else if matches!( reference_kind, ReferenceKind::GetField @@ -104,7 +102,7 @@ impl Pool { ) { self.field_ref(owner, name, descriptor)? } else { - self.method_ref(owner, name, descriptor, InvokeKind::Static)? + self.method_ref(owner, name, descriptor, false)? }; let index = self .pool diff --git a/crates/noxis-classfile/src/insn/kinds.rs b/crates/noxis-classfile/src/insn/kinds.rs index dc340b5..6c1a742 100644 --- a/crates/noxis-classfile/src/insn/kinds.rs +++ b/crates/noxis-classfile/src/insn/kinds.rs @@ -1,9 +1,9 @@ -//! Типы операндов инструкций: константы, примитивы, условия, вызовы. +//! Instruction operand types: constants, primitives, conditions, calls. -/// Идентификатор метки внутри одного метода. +/// A label identifier within a single method. pub type Label = u32; -/// Константа для `ldc`/`ldc_w`/`ldc2_w`. +/// A constant for `ldc`/`ldc_w`/`ldc2_w`. #[derive(Debug, Clone, PartialEq)] pub enum Const { Int(i32), @@ -11,7 +11,7 @@ pub enum Const { Float(f32), Double(f64), String(String), - /// Внутреннее имя класса (`java/lang/String`). + /// The class's internal name (`java/lang/String`). Class(String), MethodType(String), MethodHandle { @@ -21,7 +21,7 @@ pub enum Const { descriptor: String, itf: bool, }, - /// `CONSTANT_Dynamic`: имя, дескриптор, индекс bootstrap-метода. + /// `CONSTANT_Dynamic`: name, descriptor, bootstrap-method index. Dynamic { name: String, descriptor: String, @@ -29,7 +29,7 @@ pub enum Const { }, } -/// Размер операнда/результата арифметики. +/// Operand/result size of an arithmetic operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Prim { Int, @@ -38,7 +38,7 @@ pub enum Prim { Double, } -/// Арифметическая/битовая операция; тип берётся из [`Prim`]. +/// An arithmetic/bitwise operation; the type comes from [`Prim`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Arith { Add, @@ -55,7 +55,7 @@ pub enum Arith { Ushr, } -/// Условие перехода. +/// A branch condition. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Cond { Eq, @@ -66,10 +66,10 @@ pub enum Cond { Ge, } -/// Вид условного перехода (соответствует семействам `if*`). +/// Kind of conditional branch (matches the `if*` families). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BranchCond { - /// `if` относительно нуля. + /// `if` against zero. Zero(Cond), /// `if_icmp`. Int(Cond), @@ -79,7 +79,7 @@ pub enum BranchCond { Null { is_null: bool }, } -/// Вид вызова. +/// Kind of call. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum InvokeKind { Virtual, @@ -88,7 +88,7 @@ pub enum InvokeKind { Interface, } -/// Конверсия типов (`i2l`, `f2b`, ... — JVMS §6.5.i2). +/// Type conversion (`i2l`, `f2b`, ... - JVMS §6.5.i2). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Convert { I2L, @@ -108,7 +108,7 @@ pub enum Convert { D2F, } -/// Тип элемента массива для `newarray`/`*aload`/`*astore`. +/// Array element type for `newarray`/`*aload`/`*astore`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ArrayKind { Boolean, @@ -122,10 +122,10 @@ pub enum ArrayKind { Reference, } -/// Тип слота локальной переменной для `*load*`/`*store*`. +/// Local-variable slot type for `*load*`/`*store*`. /// -/// Хранится явно: выбор опкода (`iload` vs `aload`) — подсказка верификатору, -/// потерять её при round-trip нельзя. +/// Stored explicitly: the opcode choice (`iload` vs `aload`) is a hint to the +/// verifier, and losing it on a round-trip is not acceptable. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SlotKind { Int, diff --git a/crates/noxis-classfile/src/insn/mod.rs b/crates/noxis-classfile/src/insn/mod.rs index 0a4facc..8f77d97 100644 --- a/crates/noxis-classfile/src/insn/mod.rs +++ b/crates/noxis-classfile/src/insn/mod.rs @@ -1,7 +1,7 @@ -//! Инструкции IR: смещения отсутствуют, ветвления адресуют [`Label`]. +//! IR instructions: no offsets, branches address a [`Label`]. //! -//! Это принципиально: любой пасс, меняющий порядок/длину инструкций, не обязан -//! пересчитывать jump-офсеты — это делает writer один раз в конце пайплайна. +//! This is fundamental: any pass that changes instruction order/length need not +//! recompute jump offsets - the writer does that once at the end of the pipeline. mod kinds; @@ -9,32 +9,32 @@ pub use kinds::{ Arith, ArrayKind, BranchCond, Cond, Const, Convert, InvokeKind, Label, Prim, SlotKind, }; -/// Мнемоника одной инструкции. +/// Mnemonic of a single instruction. #[derive(Debug, Clone, PartialEq)] pub enum Insn { - /// Маркер метки. Ветвления указывают на [`Label`], writer вычисляет смещения. + /// Label marker. Branches point at a [`Label`]; the writer computes offsets. Mark(Label), Nop, AconstNull, Const(Const), - /// Загрузка локальной переменной (`iload`, `aload`, ...). + /// Load a local variable (`iload`, `aload`, ...). Load { slot: u16, kind: SlotKind, }, - /// Сохранение локальной переменной. + /// Store a local variable. Store { slot: u16, kind: SlotKind, }, - /// `iinc` — увеличение локальной переменной на константу. + /// `iinc` - increase a local variable by a constant. Iinc { index: u16, delta: i32, }, - /// Загрузка элемента массива. + /// Load an array element. ArrayLoad(ArrayKind), - /// Сохранение элемента массива. + /// Store an array element. ArrayStore(ArrayKind), Pop, Pop2, @@ -45,23 +45,23 @@ pub enum Insn { Dup2X1, Dup2X2, Swap, - /// `iadd`, `lmul`, `lneg`, ... — тип + операция. + /// `iadd`, `lmul`, `lneg`, ... - type + operation. Binary { prim: Prim, op: Arith, }, - /// Сравнение длин (`lcmp`) и плавающих (`fcmpl`/`fcmpg`). + /// Comparison of longs (`lcmp`) and floats (`fcmpl`/`fcmpg`). Cmp { prim: Prim, nan_great: bool, }, - /// Конверсия типов (`i2l`, `d2f`, ...). + /// Type conversion (`i2l`, `d2f`, ...). Convert(Convert), Branch(BranchCond, Label), Goto(Label), - /// `jsr` — вызов подпрограммы (только классы версии ≤ 50). + /// `jsr` - subroutine call (only version ≤ 50 classes). Jsr(Label), - /// `ret` — возврат из подпрограммы (`jsr`/`ret` парны). + /// `ret` - return from a subroutine (`jsr`/`ret` come in pairs). Ret(u16), TableSwitch { default: Label, @@ -73,9 +73,9 @@ pub enum Insn { default: Label, pairs: Vec<(i32, Label)>, }, - /// `return`/`ireturn`/...; `None` — пустой возврат. + /// `return`/`ireturn`/...; `None` - void return. Return(Option), - /// `areturn` — возврат ссылки (у [`Prim`] нет ссылочного типа). + /// `areturn` - return a reference ([`Prim`] has no reference type). AReturn, GetStatic { owner: String, @@ -112,7 +112,7 @@ pub enum Insn { New(String), NewArray(ArrayKind), ANewArray(String), - /// `multianewarray` — массив любого измерения; `dims` — сколько измерений со стека. + /// `multianewarray` - array of any dimension; `dims` - how many dimensions from the stack. MultiANewArray { descriptor: String, dims: u8, @@ -126,7 +126,7 @@ pub enum Insn { } impl Insn { - /// Метки, на которые ссылается инструкция (для построения CFG). + /// Labels the instruction references (for building the CFG). pub fn targets(&self) -> Vec