diff --git a/Cargo.lock b/Cargo.lock index a1ac432..364e024 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,7 +310,6 @@ dependencies = [ "noxis-core", "noxis-structure-check", "regex", - "serde_json", "thiserror", "tracing", ] @@ -356,7 +355,6 @@ dependencies = [ "noxis-core", "noxis-runtime", "noxis-structure-check", - "serde_json", "thiserror", "tracing", ] diff --git a/NOTICE.md b/NOTICE.md index 7451839..b059baf 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 72b20a2..4d592b6 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 (кадры готовы, 4 схемы: state-spread, computed-switch, butterfly, exception-goto) | ✅ | +| пасс flow (кадры готовы, схем флаттенинга пока нет) | 🚧 | Подробности в [`docs/architecture.md`](docs/architecture.md), план в [`todo.md`](todo.md). @@ -50,8 +50,12 @@ cargo run -p noxis -- patterns --input output.jar ``` `obfuscate` по умолчанию включает все готовые пассы. Флаги `--no-rename`, -`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`, -`--no-flow` выключают их по отдельности. +`--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). ## Структура diff --git a/crates/noxis-analysis/Cargo.toml b/crates/noxis-analysis/Cargo.toml index 4a65dac..40224a6 100644 --- a/crates/noxis-analysis/Cargo.toml +++ b/crates/noxis-analysis/Cargo.toml @@ -8,7 +8,6 @@ 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 deleted file mode 100644 index 65f9707..0000000 --- a/crates/noxis-analysis/src/JdkHierarchy.java +++ /dev/null @@ -1,34 +0,0 @@ -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 93349c0..f559d1f 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 b982d8f..6a57ea1 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 deleted file mode 100644 index 1e10d95..0000000 --- a/crates/noxis-analysis/src/jdk.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! 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/mod.rs b/crates/noxis-analysis/src/keep.rs similarity index 51% rename from crates/noxis-analysis/src/keep/mod.rs rename to crates/noxis-analysis/src/keep.rs index 498b9b5..bdb9ad2 100644 --- a/crates/noxis-analysis/src/keep/mod.rs +++ b/crates/noxis-analysis/src/keep.rs @@ -1,19 +1,12 @@ -//! Keep rules: what must not be renamed (glob patterns + entrypoints). +//! Keep-правила: что нельзя переименовывать (glob-паттерны + entrypoint'ы). -use std::collections::BTreeSet; - -use noxis_classfile::Program; +use noxis_classfile::{Attribute, Const, Program}; use regex::Regex; use crate::entrypoints::Entrypoints; use noxis_core::Config; -mod dispatch; -mod scans; - -pub use dispatch::external_dispatch_families; - -/// Compiled glob: `*` - anything but `/`, `**` - anything, `?` - one char. +/// Скомпилированный glob: `*` — любые символы кроме `/`, `**` — всё, `?` — один. fn compile(pattern: &str) -> Result { let mut out = String::from("^"); let chars: Vec = pattern.chars().collect(); @@ -43,19 +36,19 @@ fn compile(pattern: &str) -> Result { Regex::new(&out) } -/// "Do not touch" rules: explicit config patterns + entrypoints. +/// Правила «не трогать»: явные паттерны конфига + entrypoint'ы. #[derive(Debug, Default, Clone)] pub struct KeepRules { class_patterns: Vec, resource_patterns: Vec, - /// Exact names to keep (entrypoints, reflection, ...). - fixed: BTreeSet, - /// Member names protected by reflection. - fixed_members: BTreeSet, + /// Точные имена, которые нельзя трогать (entrypoint'ы, рефлексия, ...). + fixed: std::collections::BTreeSet, + /// Имена членов, защищённые рефлексией. + fixed_members: std::collections::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 { @@ -74,22 +67,22 @@ impl KeepRules { Ok(Self { class_patterns, resource_patterns, - fixed: BTreeSet::new(), - fixed_members: BTreeSet::new(), + fixed: std::collections::BTreeSet::new(), + fixed_members: std::collections::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()); } - /// Absorb found entrypoints. + /// Объединить с найденными entrypoint'ами. pub fn absorb(&mut self, entrypoints: &Entrypoints) { for name in &entrypoints.main_classes { self.keep_exact(name.clone()); @@ -111,7 +104,30 @@ impl KeepRules { } } - /// Whether the class with this internal name stays. + /// Методы, на которые ссылаются `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()); + } + } + } + } + } + } + } + } + + /// Нужно ли оставить класс с данным внутренним именем. pub fn keeps_class(&self, internal_name: &str) -> bool { self.fixed.contains(internal_name) || self @@ -120,17 +136,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() @@ -138,37 +154,35 @@ 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("malformed pattern `{pattern}`: {msg}")] + #[error("некорректный паттерн `{pattern}`: {msg}")] Pattern { pattern: String, msg: String }, } -/// The full pre-obfuscation analysis. +/// Полный анализ перед обфускацией. #[derive(Debug, Clone)] pub struct Analysis { pub entrypoints: Entrypoints, pub keep: KeepRules, - /// Classes that are not renamed. - pub locked_classes: BTreeSet, + /// Классы, которые не переименовываются. + pub locked_classes: std::collections::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 @@ -184,8 +198,40 @@ 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/dispatch.rs b/crates/noxis-analysis/src/keep/dispatch.rs deleted file mode 100644 index 22e3c57..0000000 --- a/crates/noxis-analysis/src/keep/dispatch.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Внешний диспатч: семейства методов, которые программный код зовёт через -//! внешние интерфейсы/классы (не из артефакта). Их нельзя переименовывать - -//! внешний вызывающий код не переписать, и 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/scans.rs b/crates/noxis-analysis/src/keep/scans.rs deleted file mode 100644 index 0ce16a6..0000000 --- a/crates/noxis-analysis/src/keep/scans.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! 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 21d9318..fb6fac5 100644 --- a/crates/noxis-analysis/src/lib.rs +++ b/crates/noxis-analysis/src/lib.rs @@ -5,15 +5,13 @@ //! //! Из этих данных пасс переименования узнаёт, **что** трогать нельзя. //! Урок из `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 jdk::JdkHierarchy; -pub use keep::{Analysis, KeepRules, RuleError, external_dispatch_families}; +pub use keep::{Analysis, KeepRules, RuleError}; diff --git a/crates/noxis-analysis/tests/dto.rs b/crates/noxis-analysis/tests/dto.rs deleted file mode 100644 index ac399f4..0000000 --- a/crates/noxis-analysis/tests/dto.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! 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 deleted file mode 100644 index ecc8354..0000000 --- a/crates/noxis-analysis/tests/keep.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! 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 deleted file mode 100644 index 898786b..0000000 --- a/crates/noxis-analysis/tests/mixins.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! 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 9066044..28f9689 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 5a95bec..3715578 100644 --- a/crates/noxis-classfile/src/format/frames/emit.rs +++ b/crates/noxis-classfile/src/format/frames/emit.rs @@ -1,9 +1,8 @@ -//! Emitting compact frames at the points where the verifier expects them. +//! Эмиссия компактных кадров в точках, где их ждёт верификатор. //! -//! 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. +//! Вид кадра выбирается сравнением с предыдущим кадром (`Same`/`Append`/ +//! `Chop`/`SameLocals`, иначе `Full`) — как у `javac`. Хвостовые `Top` +//! при сравнении и записи отрезаются: пустой слот — не тип. use std::collections::BTreeSet; @@ -12,10 +11,10 @@ use super::xfer::State; use super::{StackMapFrame, VerificationType}; use crate::error::ClassfileError; -/// Frames at every point in `targets` (sorted - deltas in order). +/// Кадры во всех точках `targets` (отсортированы — дельты по порядку). /// -/// Deltas are in instruction numbers (like the backend after reading); the writer -/// recomputes them into bytes itself. +/// Дельты — в номерах инструкций (как backend после чтения); writer сам +/// пересчитает их в байты. pub(super) fn emit_frames( states: &[Option], targets: &BTreeSet, @@ -35,7 +34,7 @@ pub(super) fn emit_frames( Some(previous) => target .checked_sub(previous) .and_then(|delta| delta.checked_sub(1)) - .ok_or_else(|| merger.invalid("frames out of order"))?, + .ok_or_else(|| merger.invalid("кадры не по порядку"))?, }; out.push(select(delta, &state.locals, &previous_locals, &state.stack)); previous_locals = state.locals.clone(); @@ -50,21 +49,17 @@ fn select( previous: &[VerificationType], stack: &[VerificationType], ) -> StackMapFrame { - // Comparison is at variable granularity (`long` - one entry, like `javac`); - // otherwise halves would produce `Append{[Top, Long]}`. + // Сравнение — на гранулярности переменных (`long` — одна запись, + // как у `javac`): иначе половины пар дают `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.as_slice() { + if let [local] = stack { return StackMapFrame::SameLocals { offset_delta: delta, local: local.clone(), @@ -98,34 +93,10 @@ fn select( } } -/// Stack entries → values: `[Double, Top]` - one entry (like `javac`). +/// Слоты → переменные: `[Long, Top]` — одна запись; хвостовые `Top` — прочь. /// -/// 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`). +/// Одиночные `Top` внутри (дыры) сохраняются: в `Full` это легальный тип, +/// а в `Append` мы их не пускаем (см. `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 2c98496..7a10222 100644 --- a/crates/noxis-classfile/src/format/frames/flow.rs +++ b/crates/noxis-classfile/src/format/frames/flow.rs @@ -1,4 +1,4 @@ -//! A method body's CFG: labels, edges, frame points, handler ranges. +//! CFG тела метода: метки, рёбра, точки кадров, диапазоны handler'ов. 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 edges without exceptions: fallthrough + branch targets. +/// Рёбра CFG без исключений: продолжение + цели переходов. 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(); - // No fallthrough: jumps that don't return and method exits. - // `Jsr`/`Ret` never reach here (rejected by `transfer`), but the edges exist. + // Без продолжения: переходы без возврата и выходы из метода. + // `Jsr`/`Ret` сюда не доходят (их отвергает `transfer`), но рёбра есть. let terminal = matches!( insn, Insn::Goto(..) @@ -67,7 +67,7 @@ pub(super) fn successors( Ok(out) } -/// Points where the verifier requires frames: branch targets + handler entries. +/// Точки, где верификатор требует кадры: цели переходов + входы handler'ов. pub(super) fn frame_targets( bare: &[&Insn], labels: &BTreeMap, @@ -91,12 +91,12 @@ pub(super) fn frame_targets( Ok(targets) } -/// A handler point in instruction numbers: `(start, end, handler, catch type)`. +/// Точка handler'а в номерах инструкций: `(start, end, handler, тип перехвата)`. /// -/// Ranges are half-open `[start, end)`, as in the JVMS. +/// Диапазоны полуоткрытые `[start, end)`, как в JVMS. pub(super) type HandlerRange = (u32, u32, u32, Option); -/// Handlers in instruction numbers, for exception edges. +/// Handler'ы в номерах инструкций для рёбер исключений. 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 e978c7b..dd9c243 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 @@ -//! Descriptor parsing (`(...)V`, `[L...;`). +//! Разбор дескрипторов типов (`(...)V`, `[L...;`). use super::super::VerificationType; -/// Descriptor parse error (context is added by the caller). +/// Ошибка разбора дескриптора (контекст добавляет вызывающий код). #[derive(Debug)] pub(crate) struct DescError(pub String); -/// Write value slots into `locals` at position; return next position. +/// Уложить слоты значения в locals с позиции; вернуть следующую позицию. 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(';'))) } -/// Slots for a single field descriptor (`long`/`double` - pair with `Top`). +/// Слоты одного полевого дескриптора (`long`/`double` — парой с `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 } } -/// Parameter and return slots (`None` - `void`). +/// Слоты параметров и возврата (`None` — `void`). type MethodSlots = (Vec>, Option>); -/// Method descriptor: parameter slots and return slots (`None` - `void`). +/// Дескриптор метода: слоты параметров и слоты возврата (`None` — `void`). pub(crate) fn method_slots(descriptor: &str) -> Result { let (params, ret) = descriptor .split_once('(') @@ -128,43 +128,24 @@ 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( - elem.strip_prefix('L') - .unwrap_or("java/lang/Object") - .to_string(), - ), + _ => VerificationType::Object(format!("[{elem};")), }; } 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 fc82fc4..28c3c20 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 @@ -//! Type merging (LUB) and descriptor parsing. +//! Слияние типов (LUB) и разбор дескрипторов. //! -//! 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`. +//! Решётка: `Top` — «пусто» (берётся сосед), `Null` впитывается в ссылку, +//! одинаковые — сами в себя, ссылки — наименьший общий предок по иерархии. +//! Несочетаемые инициализированные типы (`int` vs ссылка после `astore` +//! в handler'е) дают `Top`, как обрезанные кадры `javac`: `Top` в кадре +//! принимает любое фактическое значение, поэтому это всегда sound. +//! Исключение — неинициализированные типы: их слияние означает сломанный +//! поток конструирования, здесь честная ошибка, а не молчаливый `Top`. pub(super) mod descs; @@ -17,13 +17,13 @@ use crate::model::Method; use descs::write_local; -/// The class hierarchy for LUB: the superclass chain is enough. +/// Иерархия классов для LUB: достаточно цепочки суперклассов. pub trait Hierarchy { - /// The direct superclass (`None` - `java/lang/Object` or unknown). + /// Прямой суперкласс (`None` — `java/lang/Object` или неизвестный). fn superclass(&self, class: &str) -> Option; } -/// Merge context: names for errors + hierarchy for LCA. +/// Контекст слияния: имена для ошибок + иерархия для LCA. pub(super) struct Merger<'h> { pub class: String, pub method: String, @@ -38,7 +38,7 @@ impl Merger<'_> { } } - /// Merge an incoming state; `true` - the slot changed. + /// Влить входящее состояние; `true` — слот изменился. pub fn merge_into( &self, slot: &mut Option, @@ -61,7 +61,7 @@ impl Merger<'_> { } } - /// The initial state: parameters (+ `this`) over `Top`. + /// Начальное состояние: параметры (+ `this`) поверх `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("parameters do not fit into locals"))?; + .map_err(|_| self.invalid("параметры не влезают в locals"))?; } for param in params { slot = write_local(&mut locals, slot, param) - .map_err(|_| self.invalid("parameters do not fit into locals"))?; + .map_err(|_| self.invalid("параметры не влезают в 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 length differs across the merge")); + return Err(self.invalid("разная длина locals при слиянии")); } if first.stack.len() != second.stack.len() { - return Err(self.invalid("stack depth differs across the merge")); + return Err(self.invalid("разная глубина стека при слиянии")); } Ok(State { locals: first @@ -120,31 +120,26 @@ impl Merger<'_> { return Ok(first.clone()); } match (first, second) { - // 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), + (Top, other) | (other, Top) => Ok(other.clone()), (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(&format!( - "merging uninitialized types ({first:?} with {second:?})" - ))) + Err(self.invalid("слияние неинициализированных типов")) } - // Incompatible initialized (e.g. `int` from the `try` body and - // `Throwable` from a handler in one slot): `Top`, like `javac`. + // Несочетаемые инициализированные (например, `int` из тела `try` + // и `Throwable` из handler'а в одном слоте): `Top`, как у `javac`. _ => Ok(Top), } } - /// Least common ancestor: climb the chains, fallback - `Object`. + /// Наименьший общий предок: подъём по цепочкам, запасной — `Object`. fn common_superclass(&self, first: &str, second: &str) -> String { if first == second { return first.to_string(); @@ -181,7 +176,7 @@ impl Merger<'_> { "java/lang/Object".to_string() } - /// Arrays' LCA: same dimensionality + element LCA, otherwise `Object`. + /// LCA массивов: та же размерность + LCA элементов, иначе `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 5953722..07eec95 100644 --- a/crates/noxis-classfile/src/format/frames/mod.rs +++ b/crates/noxis-classfile/src/format/frames/mod.rs @@ -1,12 +1,12 @@ -//! `StackMapTable`: frame representation and computation after transformations. +//! `StackMapTable`: представление фреймов и вычисление после трансформаций. //! -//! 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`. +//! Фреймы — самая дорогая часть любого обфускатора на Rust: JVM-верификатор +//! (class version ≥ 50) требует точного `StackMapTable`, иначе класс не грузится. +//! Варианты реализации и их цены — `docs/stack.md`. //! -//! 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. +//! Метод: CFG по меткам → worklist с типами (`xfer`) → слияние LUB (`merge`) +//! → эмиссия компактных кадров (`emit`). Байтовые смещения берутся тем же +//! преобразованием, что использует writer, — иначе кадры разъедутся с байтами. mod emit; mod flow; @@ -27,7 +27,7 @@ pub use merge::Hierarchy; use merge::Merger; use xfer::{State, transfer}; -/// A verification type from JVMS §4.10.1. +/// Тип верификации из JVMS §4.10.1. #[derive(Debug, Clone, PartialEq)] pub enum VerificationType { Top, @@ -37,14 +37,14 @@ pub enum VerificationType { Long, Null, UninitializedThis, - /// The class's internal name (`java/lang/Object`) or an array descriptor. + /// Внутреннее имя класса (`java/lang/Object`) или дескриптор массива. Object(String), - /// The byte offset of the `new` instruction. + /// Байтовое смещение инструкции `new`. 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 { } } -/// A `StackMapTable` entry (JVMS §4.7.4). +/// Запись `StackMapTable` (JVMS §4.7.4). #[derive(Debug, Clone, PartialEq)] pub enum StackMapFrame { Same { @@ -80,11 +80,10 @@ pub enum StackMapFrame { }, } -/// Compute the frames for a method body after all transformations. +/// Вычислить фреймы для тела метода после всех трансформаций. /// -/// 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. +/// Кадры нужны только классам версии ≥ 50; `jsr`/`ret` отвергаются (такие +/// классы старше и кадры им не нужны). Иерархия — для LUB ссылочных типов. pub fn compute_frames( class: &str, method: &Method, @@ -113,7 +112,7 @@ pub fn compute_frames( emit::emit_frames(&states, &targets, &initial.locals, &merger) } -/// The byte offset of each instruction - using the same encoding as the writer. +/// Байтовое смещение каждой инструкции — тем же кодированием, что в writer'е. fn layout( bare: &[&Insn], labels: &BTreeMap, @@ -145,7 +144,7 @@ fn layout( .collect() } -/// Main loop: states flow along CFG edges to a fixed point. +/// Основной цикл: состояния текут по рёбрам CFG до неподвижной точки. fn run_worklist( merger: &Merger<'_>, bare: &[&Insn], @@ -188,7 +187,7 @@ fn run_worklist( Ok(()) } -/// Merge a state into an instruction; `true` - changed, keep walking. +/// Влить состояние в инструкцию; `true` — изменилось, продолжить обход. fn flow_into( merger: &Merger<'_>, states: &mut [Option], @@ -219,8 +218,8 @@ fn flow_into( Ok(()) } -/// CFG edges without exceptions: fallthrough + branch targets. -/// The exception type at a handler's entry (`catch-all` - any throwable). +/// Рёбра CFG без исключений: продолжение + цели переходов. +/// Тип исключения на входе в handler (`catch-all` — любое 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/mod.rs b/crates/noxis-classfile/src/format/frames/tests.rs similarity index 79% rename from crates/noxis-classfile/src/format/frames/tests/mod.rs rename to crates/noxis-classfile/src/format/frames/tests.rs index 41d623d..7e3bcad 100644 --- a/crates/noxis-classfile/src/format/frames/tests/mod.rs +++ b/crates/noxis-classfile/src/format/frames/tests.rs @@ -1,4 +1,4 @@ -//! Unit tests for `compute_frames` on synthesized IR. +//! Unit-тесты `compute_frames` на синтезированном 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}; -/// Empty hierarchy: everything unknown descends from `Object` (enough for LUB). -pub(super) struct NoHierarchy; +/// Пустая иерархия: всё неизвестное — наследники `Object` (для LUB хватает). +struct NoHierarchy; impl Hierarchy for NoHierarchy { fn superclass(&self, _class: &str) -> Option { @@ -16,7 +16,7 @@ impl Hierarchy for NoHierarchy { } } -pub(super) fn code_method( +fn code_method( name: &str, descriptor: &str, max_stack: u16, @@ -40,7 +40,7 @@ pub(super) fn code_method( } } -/// A branch emits two frames (`Same`, `SameLocals`). +/// Ветвь → два кадра (`Same`, `SameLocals`). #[test] fn branch_emits_same_frames() { let mut method = code_method( @@ -76,11 +76,7 @@ fn branch_emits_same_frames() { ); } -/// `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`). +/// `try/catch`: handler получает `Full`, продолжение — `Append`. #[test] fn handler_emits_full_frame() { let method = code_method( @@ -119,12 +115,15 @@ fn handler_emits_full_frame() { locals: vec![VerificationType::Integer], stack: vec![VerificationType::Object("java/lang/Exception".to_string())], }, - StackMapFrame::Same { offset_delta: 2 }, + StackMapFrame::Append { + offset_delta: 2, + locals: vec![VerificationType::Object("java/lang/Exception".to_string())], + }, ] ); } -/// Two `new` on different branches cannot merge - an honest error, not `Top`. +/// Два `new` на разных ветвях нельзя слить — честная ошибка, не `Top`. #[test] fn uninitialized_merge_is_rejected() { let method = code_method( @@ -151,37 +150,28 @@ fn uninitialized_merge_is_rejected() { ], vec![], ); - let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("merge"); + let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("слияние"); assert!( - err.to_string().contains("uninitialized"), - "wrong message: {err}" + err.to_string().contains("неинициализированных"), + "не тот текст: {err}" ); } -mod joins; - -pub(super) fn load(slot: u16) -> Insn { +fn load(slot: u16) -> Insn { Insn::Load { slot, kind: SlotKind::Int, } } -pub(super) fn load_ref(slot: u16) -> Insn { - Insn::Load { - slot, - kind: SlotKind::Ref, - } -} - -pub(super) fn store(slot: u16) -> Insn { +fn store(slot: u16) -> Insn { Insn::Store { slot, kind: SlotKind::Int, } } -pub(super) fn store_ref(slot: u16) -> Insn { +fn store_ref(slot: u16) -> Insn { Insn::Store { slot, kind: SlotKind::Ref, diff --git a/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs b/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs deleted file mode 100644 index 773ea67..0000000 --- a/crates/noxis-classfile/src/format/frames/tests/joins/arrays.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! 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 deleted file mode 100644 index ea82b9f..0000000 --- a/crates/noxis-classfile/src/format/frames/tests/joins/mod.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! 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/xfer/calls.rs b/crates/noxis-classfile/src/format/frames/xfer/calls.rs index d25de8c..98f4950 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,12 +34,18 @@ 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, "call arguments")?; + super::stack::pop_slots( + state, + count_slots(¶ms), + class, + method, + "аргументы вызова", + )?; 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) => { @@ -49,11 +55,9 @@ pub(super) fn invoke( &initialized(class), ); } - // Only the receiver's own allocation site: an enclosing `new` - // whose `` has not run yet must stay uninitialized. - Some(VerificationType::Uninitialized(offset)) => { + Some(VerificationType::Uninitialized(_)) => { let fresh = VerificationType::Object(owner.to_string()); - replace(state, &VerificationType::Uninitialized(offset), &fresh); + replace_uninit(state, &fresh); } _ => {} } @@ -64,12 +68,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 { @@ -78,6 +82,15 @@ 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()) } @@ -102,7 +115,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 44279c8..1814794 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 @@ -//! Type states and per-instruction transfer functions. +//! Состояние типов и transfer-функции инструкций. //! -//! 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. +//! Стек растёт вправо (`push` — в конец). `long`/`double` занимают два слота: +//! значение + `Top`. Проверяется только ФОРМА (глубина, категории), не +//! соответствие типов — неверные типы честно упадут на верификаторе JVM. 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}; -/// Local types plus the operand stack at one program point. +/// Типы locals + operand stack в одной точке программы. #[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,11 +31,7 @@ pub(super) fn transfer( state: &mut State, ) -> Result<(), ClassfileError> { match insn { - Insn::Mark(label) => Err(invalid( - class, - method, - &format!("marker {label} was not stripped"), - )), + Insn::Mark(label) => Err(invalid(class, method, &format!("маркер {label} не снят"))), Insn::Nop => Ok(()), Insn::AconstNull => push(state, vec![VerificationType::Null]), Insn::Const(value) => { @@ -55,29 +51,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 over a non-int")); + return Err(invalid(class, method, "iinc не по int")); } Ok(()) } Insn::ArrayLoad(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))) + pop_slots(state, 1, class, method, "индекс массива")?; + let array = pop_slots(state, 1, class, method, "массив")?.remove(0); + push(state, vec![array_element(&array, *kind)]) } Insn::ArrayStore(kind) => { let count = match kind { ArrayKind::Long | ArrayKind::Double => 2, _ => 1, }; - pop_slots(state, count, class, method, "value")?; - pop_slots(state, 1, class, method, "array index")?; - pop_slots(state, 1, class, method, "array")?; + pop_slots(state, count, class, method, "значение")?; + pop_slots(state, 1, class, method, "индекс массива")?; + pop_slots(state, 1, class, method, "массив")?; Ok(()) } Insn::Pop => { let top = pop_slots(state, 1, class, method, "pop")?.remove(0); if top == VerificationType::Top { - return Err(invalid(class, method, "pop of a long/double half")); + return Err(invalid(class, method, "pop половины long/double")); } Ok(()) } @@ -94,7 +90,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 with a half")); + return Err(invalid(class, method, "swap с половиной")); } taken.reverse(); push(state, taken) @@ -104,7 +100,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) { - // A shift takes (value, int), not two values. + // Сдвиг берёт (значение, int), а не два значения. pop_slots(state, slots as usize + 1, class, method, "shift")?; } else { pop_slots(state, 2 * slots as usize, class, method, "arith")?; @@ -132,7 +128,7 @@ pub(super) fn transfer( Insn::Jsr(_) | Insn::Ret(_) => Err(invalid( class, method, - "jsr/ret subroutines are not supported", + "подпрограммы jsr/ret не поддерживаются", )), Insn::TableSwitch { .. } | Insn::LookupSwitch { .. } => { pop_slots(state, 1, class, method, "switch")?; @@ -196,7 +192,7 @@ pub(super) fn transfer( ArrayKind::Int => "[I", ArrayKind::Long => "[J", ArrayKind::Reference => { - return Err(invalid(class, method, "newarray of a reference type")); + return Err(invalid(class, method, "newarray ссылочного типа")); } }; push( @@ -206,16 +202,7 @@ pub(super) fn transfer( } Insn::ANewArray(name) => { pop_slots(state, 1, class, method, "anewarray")?; - // `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)]) + push(state, vec![VerificationType::Object(format!("[L{name};"))]) } 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 f9c6744..0481536 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 7b692e9..36826d1 100644 --- a/crates/noxis-classfile/src/format/mod.rs +++ b/crates/noxis-classfile/src/format/mod.rs @@ -1,6 +1,5 @@ -//! Reading/writing the binary `.class` format (JVMS §4) through the -//! `ristretto_classfile` backend: candidate review and decision in -//! `docs/stack.md`. +//! Чтение/запись бинарного формата `.class` (JVMS §4) через backend +//! `ristretto_classfile`: обзор кандидатов и решение — `docs/stack.md`. mod frames; mod parse; @@ -11,21 +10,20 @@ pub use frames::{Hierarchy, StackMapFrame, VerificationType, compute_frames}; use crate::error::ClassfileError; use crate::model::ClassFile; -/// Parse one `.class` into a [`ClassFile`]. +/// Разобрать один `.class` в [`ClassFile`]. pub fn parse(bytes: &[u8]) -> Result { parse::class::parse_class(bytes) } -/// Write a [`ClassFile`] to bytes, including `Code`/`StackMapTable` recompute. +/// Записать [`ClassFile`] в байты, включая пересчёт `Code`/`StackMapTable`. pub fn write(class: &ClassFile) -> Result, ClassfileError> { write::write_class(class) } -/// Classes that were not modified must go to the output archive "as-is". +/// Классы, которые не изменялись, должны уезжать в выходной архив «как есть». /// -/// 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). +/// Это дешевле и безопаснее, чем round-trip через наш IR: нет риска потерять +/// неизвестный атрибут. Реализация зависит от решения по backend (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 deleted file mode 100644 index a365c07..0000000 --- a/crates/noxis-classfile/src/format/parse/annos/mod.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! 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 c3eb382..8dc3c94 100644 --- a/crates/noxis-classfile/src/format/parse/attrs.rs +++ b/crates/noxis-classfile/src/format/parse/attrs.rs @@ -1,22 +1,21 @@ -//! Backend attributes → our IR attributes. +//! Атрибуты backend'а → атрибуты нашего IR. //! -//! `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`). +//! `BootstrapMethods`, `EnclosingMethod`, `MethodParameters` и `ConstantValue` +//! моделируются явно (в них лежат ссылки пула, переживающие пересборку); +//! остальное структурированное, но нам ненужное, уезжает в `Raw` как есть. +//! `Code` и `StackMapTable` здесь не обрабатываются — их разбирает вызывающий +//! код метода (см. `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}; -/// One backend attribute → our attribute (except `Code`/`StackMapTable`). +/// Один атрибут backend'а → наш атрибут (кроме `Code`/`StackMapTable`). pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result { Ok(match attr { RtAttr::SourceFile { @@ -48,12 +47,6 @@ 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, @@ -108,34 +101,11 @@ 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)?, }) } -/// An unmodeled attribute → `Raw`: name + `info` bytes (without the header). +/// Несмоделированный атрибут → `Raw`: имя + байты `info` (без заголовка). pub(super) fn raw(attr: &RtAttr) -> Result { let mut bytes = Vec::new(); attr.to_bytes(&mut bytes) @@ -161,7 +131,7 @@ fn inner( }) } -/// The enclosing class's method (`0` - class only, no method). +/// Метод объемлющего класса (`0` — только класс, без метода). fn enclosing_method( pool: &ConstantPool<'_>, index: u16, @@ -224,7 +194,7 @@ fn bootstrap( }) } -/// A pool index where `0` means the value is absent. +/// Индекс пула, где `0` означает отсутствие значения. fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result, ClassfileError> { if index == 0 { Ok(None) @@ -233,7 +203,7 @@ fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result, } } -/// A `CONSTANT_Utf8` index where `0` means the value is absent. +/// Индекс `CONSTANT_Utf8`, где `0` означает отсутствие значения. 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 2e6ee58..8a629e7 100644 --- a/crates/noxis-classfile/src/format/parse/class.rs +++ b/crates/noxis-classfile/src/format/parse/class.rs @@ -1,4 +1,4 @@ -//! The whole class: backend `ClassFile` → our [`ClassFile`](crate::model::ClassFile). +//! Класс целиком: backend `ClassFile` → наш [`ClassFile`](crate::model::ClassFile). use ristretto_classfile::attributes::Attribute as RtAttr; use ristretto_classfile::{ @@ -11,22 +11,7 @@ use super::pool::{class_name, utf8}; use crate::error::ClassfileError; use crate::model::{Attribute, ClassFile, Code, Field, Method, Version}; -/// 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. +/// Разобрать байты `.class` в наш 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; @@ -40,7 +25,7 @@ pub(crate) fn parse_class(bytes: &[u8]) -> Result { minor: rt.version.minor(), major: rt.version.major(), }, - access_flags: normalize_class_flags(rt.access_flags.bits()), + access_flags: rt.access_flags.bits(), this_class: class_name(pool, rt.this_class)?, super_class: optional_class(pool, rt.super_class)?, interfaces, @@ -114,7 +99,7 @@ fn convert_attrs( .collect() } -/// The superclass index, where `0` means absent (`java/lang/Object`). +/// Индекс суперкласса, где `0` — его отсутствие (`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 422e8fe..09a6ab3 100644 --- a/crates/noxis-classfile/src/format/parse/code/frames.rs +++ b/crates/noxis-classfile/src/format/parse/code/frames.rs @@ -1,8 +1,7 @@ -//! `StackMapTable` frames on read: variant to variant, deltas as-is. +//! Кадры `StackMapTable` при чтении: вариант в вариант, дельты как есть. //! -//! 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`. +//! Backend хранит кадры в номерах инструкций (см. `from_bytes_code_attributes`), +//! наш IR — тоже: writer сам пересчитает их в байты при `to_bytes`. use ristretto_classfile::ConstantPool; use ristretto_classfile::attributes::{StackFrame, VerificationType as RtType}; @@ -11,7 +10,7 @@ use super::super::pool::class_name; use crate::error::ClassfileError; use crate::format::{StackMapFrame, VerificationType}; -/// Backend frames → ours (index deltas - as-is). +/// Кадры backend'а → наши (индексные дельты — как есть). pub(super) fn to_frames( frames: &[StackFrame], pool: &ConstantPool<'_>, @@ -67,7 +66,7 @@ fn to_frame(frame: &StackFrame, pool: &ConstantPool<'_>) -> Result) -> Result { let mut types = types(stack, pool)?.into_iter(); match (types.next(), types.next()) { @@ -85,7 +84,7 @@ fn types( values.iter().map(|value| vtype(value, pool)).collect() } -/// Backend verification type → our type (the class name comes from the constant pool). +/// Тип верификации backend'а → наш тип (имя класса берётся из constant pool). fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result { Ok(match value { RtType::Top => VerificationType::Top, @@ -100,7 +99,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 f877044..0352a8b 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. +//! Метки тела метода: где обязаны стоять и как резолвятся. //! -//! The backend numbers instructions in order - labels are placed directly on the -//! numbers, without byte offsets. +//! Backend нумерует инструкции по порядку — метки ставятся прямо на номера, +//! без байтовых смещений. 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` - debug-table positions (already as numbers): pass insertions must -/// not leave them without a label. +/// `extra` — позиции отладочных таблиц (уже номерами): вставки пассов +/// не должны оставлять их без меток. pub(super) fn label_indexes( code: &[Instruction], exception_table: &[ExceptionTableEntry], @@ -36,7 +36,7 @@ pub(super) fn label_indexes( Ok(indexes) } -/// Backend branch targets: for `if*`/`goto` an absolute number, for `switch` a delta. +/// Цели ветвлений backend'а: для `if*`/`goto` — абсолютный номер, для `switch` — дельта. 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 f0e472f..c6c4ebd 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 @@ -//! Backend `Code` → our IR method body: labels, exceptions, frames. +//! `Code` backend'а → тело метода нашего IR: метки, исключения, кадры. //! -//! 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). +//! Backend уже перевёл байтовые смещения в номера инструкций — конвертеры +//! работают прямо с ними: метки ставятся на целях переходов, границах +//! try-блоков и позициях отладочных таблиц; кадры переносятся как есть +//! (индексные дельты). Позиции `LineNumberTable`/`LocalVariableTable` — +//! тоже метки, поэтому вставки пассов их не ломают (байты досчитает writer). 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}; -/// The whole method body: backend `Code` → our [`Code`]. +/// Тело метода целиком: backend `Code` → наш [`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 eb1d91a..f1f7025 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 @@ -//! Simple instructions with no pool references (except `ldc`) and no branches. +//! Простые инструкции без ссылок на пул (кроме `ldc`) и без ветвлений. 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` - the instruction is covered; `None` - hand it to the next converters. +/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. 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 7d3b65b..cfb3249 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 @@ -//! Branches, `switch` and returns: absolute/relative targets → labels. +//! Ветвления, `switch` и возвраты: абсолютные/относительные цели → метки. 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` - the instruction is covered; `None` - hand it to the next converters. +/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. 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 c5291f6..93e9efc 100644 --- a/crates/noxis-classfile/src/format/parse/insns/mod.rs +++ b/crates/noxis-classfile/src/format/parse/insns/mod.rs @@ -1,8 +1,9 @@ -//! Backend `Instruction` → [`Insn`](crate::insn::Insn) of our IR. +//! `Instruction` backend'а → [`Insn`](crate::insn::Insn) нашего IR. //! -//! 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. +//! Смещения ветвлений приходят из backend'а (абсолютные для `if*`/`goto`, +//! относительные от начала инструкции для `switch`), поэтому конвертация +//! принимает резолвер смещения в [`Label`](crate::insn::Label) — метки +//! назначает вызывающий код. mod basic; mod flow; @@ -14,10 +15,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; -/// Convert one instruction. `index` - its number in the method body (`switch` needs it). +/// Конвертировать одну инструкцию. `index` — её номер в теле метода (нужно `switch`). 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 f5623fe..de2dc67 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 @@ -//! Fields, calls and object creation: pool indices → IR strings. +//! Поля, вызовы и создание объектов: индексы пула → строки IR. 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` - the instruction is covered; `None` - hand it to the next converters. +/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам. 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 38927ad..d103e9b 100644 --- a/crates/noxis-classfile/src/format/parse/mod.rs +++ b/crates/noxis-classfile/src/format/parse/mod.rs @@ -1,11 +1,10 @@ -//! Backend `ristretto_classfile` → our IR: pool, instructions, method bodies. +//! Backend `ristretto_classfile` → наш IR: пул, инструкции, тела методов. //! -//! 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. +//! Пока ниоткуда не подключён (P1): `format` вернёт `Unimplemented`, пока не +//! будут готовы `parse`/`write` классового уровня поверх этих конвертеров. +//! Дерево уже разбито по ответственностям, чтобы подключение было одним +//! `mod parse` без рефакторинга. -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 8908611..dd8c538 100644 --- a/crates/noxis-classfile/src/format/parse/pool.rs +++ b/crates/noxis-classfile/src/format/parse/pool.rs @@ -1,11 +1,11 @@ -//! Resolving constant-pool indices into strings of our IR. +//! Разрешение индексов constant pool в строки нашего IR. use ristretto_classfile::{Constant, ConstantPool, ReferenceKind}; use crate::error::ClassfileError; use crate::insn::{Const, InvokeKind}; -/// The class name from a `CONSTANT_Class`. +/// Имя класса по `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)` for a `CONSTANT_NameAndType`. +/// `(name, descriptor)` для `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)) } -/// The string from a `CONSTANT_Utf8`. +/// Строка из `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: the `reference_kind` number for a `CONSTANT_MethodHandle`. +/// JVMS §5.4.3.5: номер `reference_kind` для `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 { } } -/// Checks that an `Invoke` really refers to the expected kind. +/// Проверка, что `Invoke` действительно ссылается на ожидаемый вид. /// -/// 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). +/// JVM принимает `Methodref` и `InterfaceMethodref` для всех видов вызова, +/// кроме `invokeinterface` (там только интерфейсная); строгость сверх JVM +/// ломает чтение реальных классов (статические методы интерфейсов). 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 deleted file mode 100644 index e62fc39..0000000 --- a/crates/noxis-classfile/src/format/write/annotations.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! 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 8418b47..aa45119 100644 --- a/crates/noxis-classfile/src/format/write/attrs.rs +++ b/crates/noxis-classfile/src/format/write/attrs.rs @@ -1,27 +1,26 @@ -//! Our IR attributes → backend attributes. +//! Атрибуты нашего IR → атрибуты backend'а. //! -//! Attribute names (`SourceFile`, …) are interned into the pool right here - the -//! backend stores only `name_index`, and the string is recovered on read. +//! Имена атрибутов (`SourceFile`, …) интернируются в пул здесь же — backend +//! хранит только `name_index`, строка восстанавливается при чтении. 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}; -/// Code-table positions: labels → bytes of the current layout. +/// Позиции таблиц кода: метки → байты текущего layout. pub(super) struct Positions<'a> { pub resolve: &'a dyn Fn(Label) -> Result, pub byte_of: &'a dyn Fn(u32) -> Result, } -/// `LineNumberTable`: the backend stores instruction numbers and maps them itself. +/// `LineNumberTable`: backend хранит номера инструкций и маппит сам. pub(super) fn line_number_table( lines: &[LineNumber], pool: &mut Pool, @@ -44,7 +43,7 @@ pub(super) fn line_number_table( }) } -/// `LocalVariableTable`/`TypeTable` with the range recomputed. +/// `LocalVariableTable`/`TypeTable` с пересчётом диапазона. pub(super) fn local_table( vars: &[LocalVariable], pool: &mut Pool, @@ -67,7 +66,7 @@ pub(super) fn local_table( .collect::>()?, }) } -/// The same table for types (`signature` instead of a descriptor). +/// Та же таблица для типов (`signature` вместо дескриптора). pub(super) fn local_type_table( vars: &[LocalVariableType], pool: &mut Pool, @@ -104,7 +103,7 @@ fn range( Ok((first, length)) } -/// One of our attributes → a backend attribute. +/// Один наш атрибут → атрибут backend'а. pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result { Ok(match attr { Attribute::SourceFile(name) => RtAttr::SourceFile { @@ -146,13 +145,6 @@ 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)?, @@ -179,40 +171,6 @@ 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 7cd6abe..20f5c7a 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` frames on write: variant to variant, deltas per instruction. +//! Кадры `StackMapTable` при записи: вариант в вариант, дельты по инструкциям. //! -//! 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. +//! Наш IR хранит `offset_delta` в номерах инструкций; backend при `to_bytes` +//! сам пересчитает их в байты. Компактный формат (`Same`/`SameLocals`) годен +//! только когда **байтовая** дельта ≤ 63 — иначе нужен расширенный вариант. +//! Выбор делаем по байтовой дельте: байты считаются от 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 frames → backend frames (index deltas - as-is). +/// Кадры IR → кадры backend'а (индексные дельты — как есть). 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` is the true byte delta; the compact form is valid only when ≤ 63. +/// `byte_delta` — истинная байтовая дельта; компактный вид годен лишь при ≤ 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 { - // The backend, in verify()/to_bytes, reads frame_type as a delta by - // INSTRUCTION and recomputes it into bytes itself (≤ 63 fits). + // Backend при verify()/to_bytes читает frame_type как дельту по + // ИНСТРУКЦИЯМ и сам пересчитает её в байты (≤ 63 — влезает). 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 e7781b1..031682a 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 @@ -//! Our [`Insn`](crate::insn::Insn) → the backend's `Instruction`. +//! Наш [`Insn`](crate::insn::Insn) → `Instruction` backend'а. //! -//! 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). +//! Обратная сторона `super::super::parse::insns`: метки резолвятся в +//! абсолютные номера инструкций (`switch` — в дельты от себя), константы +//! и ссылки уходят в пул через [`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}; -/// One IR instruction → a backend instruction (`None` - a label marker). +/// Одна инструкция IR → инструкция backend'а (`None` — маркер метки). /// -/// `index` - the instruction's number in the method (needed for `switch` deltas). +/// `index` — номер инструкции в методе (нужен `switch`-дельтам). pub(crate) fn convert( insn: &Insn, index: u32, @@ -96,9 +96,8 @@ pub(crate) fn convert( owner, name, descriptor, - itf, .. - } => invoke(*kind, owner, name, descriptor, *itf, pool)?, + } => invoke(*kind, owner, name, descriptor, pool)?, Insn::InvokeDynamic { name, descriptor, @@ -179,7 +178,7 @@ fn store(slot: u16, kind: SlotKind) -> RtInsn { } } -/// The short form when the slot is ≤255, otherwise the `wide` form. +/// Короткая форма при слоте ≤255, иначе `wide`-форма. 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 fa9b671..d621396 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 @@ -//! Our IR method body → the backend `Code` attribute. +//! Тело метода нашего IR → атрибут `Code` backend'а. //! -//! Labels resolve into instruction numbers once, here; then the backend -//! recomputes numbers into byte offsets on `to_bytes`. +//! Метки резолвятся в номера инструкций один раз здесь; дальше backend сам +//! пересчитывает номера в байтовые смещения при `to_bytes`. mod frames; pub(crate) mod insns; @@ -22,15 +22,8 @@ use crate::model::{Attribute, Code, ExceptionHandler}; use frames::convert_frames; -/// 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 { +/// Тело метода → готовый атрибут `Code` (с логическими номерами инструкций). +pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result { let (labels, bare) = split_marks(&code.insns)?; let resolve = |label: Label| -> Result { labels @@ -62,15 +55,11 @@ pub(super) fn convert_code( resolve: &resolve, byte_of: &byte_of, }; - let frames = if emit_frames { - convert_frames(&code.frames, pool, &byte_of)? - } else { - Vec::new() - }; + let frames = convert_frames(&code.frames, pool, &byte_of)?; let mut attributes = Vec::with_capacity(code.attributes.len() + 1); for attr in &code.attributes { attributes.push(match attr { - // The backend stores line numbers as indices and maps them itself. + // Backend хранит номера строк в индексах и маппит сам. Attribute::LineNumberTable(lines) => attrs::line_number_table(lines, pool, &positions)?, Attribute::LocalVariableTable(vars) => attrs::local_table(vars, pool, &positions)?, Attribute::LocalVariableTypeTable(vars) => { @@ -79,7 +68,7 @@ pub(super) fn convert_code( other => attrs::convert(other, pool)?, }); } - if emit_frames && !frames.is_empty() { + if !frames.is_empty() { attributes.push(RtAttr::StackMapTable { name_index: pool.utf8("StackMapTable")?, frames, @@ -95,7 +84,7 @@ pub(super) fn convert_code( }) } -/// Labels → instruction numbers; the markers themselves are removed from the stream. +/// Метки → номера инструкций; сами маркеры из потока убираются. fn split_marks(insns: &[Insn]) -> Result<(BTreeMap, Vec<&Insn>), ClassfileError> { let mut labels = BTreeMap::new(); let mut bare = Vec::with_capacity(insns.len()); @@ -119,10 +108,10 @@ fn split_marks(insns: &[Insn]) -> Result<(BTreeMap, Vec<&Insn>), Cla Ok((labels, bare)) } -/// Instruction number → byte offset (measured with placeholder targets). +/// Номер инструкции → байтовое смещение (замер с заглушками целей). /// -/// The map also includes the code end (`len` → length): range ends point past -/// the last instruction. +/// В карту входит и конец кода (`len` → длина): концы диапазонов указывают +/// за последнюю инструкцию. pub(crate) fn measure(insns: &[RtInsn]) -> Result, ClassfileError> { let mut map = BTreeMap::new(); let mut cursor = Cursor::new(Vec::new()); @@ -143,7 +132,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) @@ -189,7 +178,7 @@ fn entry( }) } -/// An IR conditional branch → the backend's `if*`. +/// Условный переход IR → `if*` backend'а. fn branch(cond: BranchCond, target: u32) -> Result { let target = fit_index(target)?; Ok(match cond { @@ -222,13 +211,13 @@ fn ret_op(prim: Option) -> RtInsn { } } -/// The instruction number must fit in `u16` (method < 64 KB of code). +/// Номер инструкции обязан влезать в `u16` (метод < 64 КБ кода). fn fit_index(index: u32) -> Result { u16::try_from(index) .map_err(|_| ClassfileError::Write(format!("номер инструкции {index} вне u16"))) } -/// A `switch` delta: the target minus the `switch` instruction's own position. +/// Дельта `switch`: цель минус позиция самого `switch`. 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 f8566c6..ef57be7 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}; -/// A constant: short forms (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` through the pool. +/// Константа: короткие формы (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` через пул. pub(super) fn int_const(value: &Const, pool: &mut Pool) -> Result { Ok(match value { Const::Int(v) => match *v { @@ -166,34 +166,29 @@ 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, itf)?) + RtInsn::Invokevirtual(pool.method_ref(owner, name, descriptor, kind)?) } InvokeKind::Special => { - RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, itf)?) + RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, kind)?) } - InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, itf)?), + InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, kind)?), InvokeKind::Interface => { - let index = pool.method_ref(owner, name, descriptor, itf)?; + let index = pool.method_ref(owner, name, descriptor, kind)?; RtInsn::Invokeinterface(index, arg_count(descriptor)?) } }) } -/// The `count` byte for `invokeinterface`: argument slots + `objectref`. +/// Байт `count` для `invokeinterface`: слоты аргументов + `objectref`. fn arg_count(descriptor: &str) -> Result { let params = descriptor .split_once('(') @@ -234,7 +229,7 @@ fn arg_count(descriptor: &str) -> Result { .map_err(|_| ClassfileError::Write(format!("слишком много аргументов в {descriptor}"))) } -/// Skip characters up to the separator (inclusive); `false` - the string ended. +/// Пропустить символы до разделителя (включительно); `false` — строка кончилась. 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 5768a7e..f314cf1 100644 --- a/crates/noxis-classfile/src/format/write/helpers.rs +++ b/crates/noxis-classfile/src/format/write/helpers.rs @@ -1,9 +1,8 @@ -//! Helpers building `InnerClasses`/`BootstrapMethods`/`MethodParameters`. +//! Хелперы сборки `InnerClasses`/`BootstrapMethods`/`MethodParameters`. //! -//! 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. +//! Вынесены из `attrs`, чтобы тот держался в лимите 250 строк; логика не +//! изменилась — только место. Каждый строит запись backend'а из элемента IR, +//! интернируя имена/дескрипторы и резолвя индексы `CONSTANT_Class` через пул. use ristretto_classfile::MethodAccessFlags; use ristretto_classfile::attributes::{ @@ -51,7 +50,7 @@ pub(super) fn bootstrap( }) } -/// A bootstrap-method argument: the same constants as in `ldc`, plus `Dynamic`. +/// Аргумент bootstrap-метода: те же константы, что в `ldc`, плюс `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 8419aec..3561059 100644 --- a/crates/noxis-classfile/src/format/write/mod.rs +++ b/crates/noxis-classfile/src/format/write/mod.rs @@ -1,9 +1,8 @@ -//! Our IR → `.class` bytes through the `ristretto_classfile` backend. +//! Наш IR → байты `.class` через backend `ristretto_classfile`. //! -//! The pool is built from scratch by a deterministic walk; the backend recomputes -//! instruction numbers into byte offsets and verifies the result (`verify`). +//! Пул собирается с нуля детерминированным обходом; backend сам пересчитывает +//! номера инструкций в байтовые смещения и проверяет результат (`verify`). -mod annotations; mod attrs; pub(crate) mod code; mod helpers; @@ -17,16 +16,11 @@ use ristretto_classfile::{ use crate::error::ClassfileError; use crate::model::{ClassFile, Field, Method}; -/// Our IR class → `.class` bytes. +/// Класс нашего IR → байты `.class`. 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, @@ -42,7 +36,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, emit_frames)?); + methods.push(convert_method(method, &mut pool)?); } let mut attributes = Vec::with_capacity(class.attributes.len()); for attr in &class.attributes { @@ -83,17 +77,13 @@ fn convert_field(field: &Field, pool: &mut pool::Pool) -> Result Result { +fn convert_method(method: &Method, pool: &mut pool::Pool) -> 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, emit_frames)?); + attributes.push(code::convert_code(code, pool)?); } 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 2900d0e..27cccc1 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 @@ -//! Building the constant pool on write: our IR strings → backend indices. +//! Сборка constant pool при записи: строки нашего IR → индексы backend'а. //! -//! 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`. +//! Пул строится с нуля детерминированным обходом (классы, поля, методы, +//! атрибуты, код), поэтому одинаковый IR даёт одинаковые байты. Индексы +//! `Raw`-атрибутов при этом не переносятся — см. `super::attrs`. //! -//! 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`]. +//! Backend не дедуплицирует: `add_*` всегда толкает новый элемент. Кэшируем +//! семантические ключи сами — иначе `LocalVariableTable` и +//! `LocalVariableTypeTable` получат разные `name_index` для одного имени, и +//! HotSpot отвергнет класс (`LVTT entry ... does not match any LVT entry`). +//! Порядок обхода детерминирован, поэтому кэш меняет только компактность пула. +//! Референсы (поле/метод/хендл/динамик) — в [`refs`]. use std::collections::HashMap; @@ -20,7 +20,7 @@ use crate::insn::Const; mod refs; -/// The pool builder; lives only within a single `write`. +/// Строитель пула; живёт только внутри одного `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); } - // Build from primitives, not `add_name_and_type`: the latter pushes its - // own `Utf8` strings past our cache (pool duplicates). + // Собираем из примитивов, а не `add_name_and_type`: последний толкает + // собственные `Utf8`-строки мимо нашего кэша (дубли в пуле). let name_index = self.utf8(name)?; let descriptor_index = self.utf8(descriptor)?; let index = self @@ -96,7 +96,7 @@ impl Pool { Ok(index) } - /// A constant for `ldc`/`ldc2_w`; `dynamic` is forbidden (bootstrap only). + /// Константа для `ldc`/`ldc2_w`; `dynamic` запрещён (только через bootstrap). 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 2c93c55..67e6e02 100644 --- a/crates/noxis-classfile/src/format/write/pool/refs.rs +++ b/crates/noxis-classfile/src/format/write/pool/refs.rs @@ -1,14 +1,15 @@ -//! Constant-pool references: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`. +//! Референсы constant pool: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`. //! -//! 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). +//! Это `impl Pool` из [`super`]; вынесено отдельно, чтобы материнский файл +//! держался в лимите структуры. Каждый билдер мемоизирован по семантическому +//! ключу (owner/name/descriptor/…) — одинаковая ссылка всегда получает один +//! индекс, а пул не раздувается дублями (раздувание иначе расширяет `ldc` +//! в `ldc_w` и меняет длину кода при переносе). use ristretto_classfile::{Constant, ReferenceKind}; use crate::error::ClassfileError; +use crate::insn::InvokeKind; use super::{Pool, write_err}; @@ -41,8 +42,9 @@ impl Pool { owner: &str, name: &str, descriptor: &str, - itf: bool, + kind: InvokeKind, ) -> Result { + let itf = matches!(kind, InvokeKind::Interface); let key = ( owner.to_string(), name.to_string(), @@ -92,7 +94,7 @@ impl Pool { ClassfileError::Write(format!("некорректный reference_kind {kind}: {e}")) })?; let reference = if itf { - self.method_ref(owner, name, descriptor, true)? + self.method_ref(owner, name, descriptor, InvokeKind::Interface)? } else if matches!( reference_kind, ReferenceKind::GetField @@ -102,7 +104,7 @@ impl Pool { ) { self.field_ref(owner, name, descriptor)? } else { - self.method_ref(owner, name, descriptor, false)? + self.method_ref(owner, name, descriptor, InvokeKind::Static)? }; let index = self .pool diff --git a/crates/noxis-classfile/src/insn/kinds.rs b/crates/noxis-classfile/src/insn/kinds.rs index 6c1a742..dc340b5 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; -/// A constant for `ldc`/`ldc_w`/`ldc2_w`. +/// Константа для `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), - /// The class's internal name (`java/lang/String`). + /// Внутреннее имя класса (`java/lang/String`). Class(String), MethodType(String), MethodHandle { @@ -21,7 +21,7 @@ pub enum Const { descriptor: String, itf: bool, }, - /// `CONSTANT_Dynamic`: name, descriptor, bootstrap-method index. + /// `CONSTANT_Dynamic`: имя, дескриптор, индекс bootstrap-метода. 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, } -/// An arithmetic/bitwise operation; the type comes from [`Prim`]. +/// Арифметическая/битовая операция; тип берётся из [`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, } -/// Kind of conditional branch (matches the `if*` families). +/// Вид условного перехода (соответствует семействам `if*`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BranchCond { - /// `if` against zero. + /// `if` относительно нуля. 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, } -/// Type conversion (`i2l`, `f2b`, ... - JVMS §6.5.i2). +/// Конверсия типов (`i2l`, `f2b`, ... — JVMS §6.5.i2). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Convert { I2L, @@ -108,7 +108,7 @@ pub enum Convert { D2F, } -/// Array element type for `newarray`/`*aload`/`*astore`. +/// Тип элемента массива для `newarray`/`*aload`/`*astore`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ArrayKind { Boolean, @@ -122,10 +122,10 @@ pub enum ArrayKind { Reference, } -/// Local-variable slot type for `*load*`/`*store*`. +/// Тип слота локальной переменной для `*load*`/`*store*`. /// -/// Stored explicitly: the opcode choice (`iload` vs `aload`) is a hint to the -/// verifier, and losing it on a round-trip is not acceptable. +/// Хранится явно: выбор опкода (`iload` vs `aload`) — подсказка верификатору, +/// потерять её при round-trip нельзя. #[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 8f77d97..0a4facc 100644 --- a/crates/noxis-classfile/src/insn/mod.rs +++ b/crates/noxis-classfile/src/insn/mod.rs @@ -1,7 +1,7 @@ -//! IR instructions: no offsets, branches address a [`Label`]. +//! Инструкции IR: смещения отсутствуют, ветвления адресуют [`Label`]. //! -//! 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. +//! Это принципиально: любой пасс, меняющий порядок/длину инструкций, не обязан +//! пересчитывать jump-офсеты — это делает writer один раз в конце пайплайна. 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 marker. Branches point at a [`Label`]; the writer computes offsets. + /// Маркер метки. Ветвления указывают на [`Label`], writer вычисляет смещения. Mark(Label), Nop, AconstNull, Const(Const), - /// Load a local variable (`iload`, `aload`, ...). + /// Загрузка локальной переменной (`iload`, `aload`, ...). Load { slot: u16, kind: SlotKind, }, - /// Store a local variable. + /// Сохранение локальной переменной. Store { slot: u16, kind: SlotKind, }, - /// `iinc` - increase a local variable by a constant. + /// `iinc` — увеличение локальной переменной на константу. 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`, ... - type + operation. + /// `iadd`, `lmul`, `lneg`, ... — тип + операция. Binary { prim: Prim, op: Arith, }, - /// Comparison of longs (`lcmp`) and floats (`fcmpl`/`fcmpg`). + /// Сравнение длин (`lcmp`) и плавающих (`fcmpl`/`fcmpg`). Cmp { prim: Prim, nan_great: bool, }, - /// Type conversion (`i2l`, `d2f`, ...). + /// Конверсия типов (`i2l`, `d2f`, ...). Convert(Convert), Branch(BranchCond, Label), Goto(Label), - /// `jsr` - subroutine call (only version ≤ 50 classes). + /// `jsr` — вызов подпрограммы (только классы версии ≤ 50). Jsr(Label), - /// `ret` - return from a subroutine (`jsr`/`ret` come in pairs). + /// `ret` — возврат из подпрограммы (`jsr`/`ret` парны). Ret(u16), TableSwitch { default: Label, @@ -73,9 +73,9 @@ pub enum Insn { default: Label, pairs: Vec<(i32, Label)>, }, - /// `return`/`ireturn`/...; `None` - void return. + /// `return`/`ireturn`/...; `None` — пустой возврат. Return(Option), - /// `areturn` - return a reference ([`Prim`] has no reference type). + /// `areturn` — возврат ссылки (у [`Prim`] нет ссылочного типа). AReturn, GetStatic { owner: String, @@ -112,7 +112,7 @@ pub enum Insn { New(String), NewArray(ArrayKind), ANewArray(String), - /// `multianewarray` - array of any dimension; `dims` - how many dimensions from the stack. + /// `multianewarray` — массив любого измерения; `dims` — сколько измерений со стека. MultiANewArray { descriptor: String, dims: u8, @@ -126,7 +126,7 @@ pub enum Insn { } impl Insn { - /// Labels the instruction references (for building the CFG). + /// Метки, на которые ссылается инструкция (для построения CFG). pub fn targets(&self) -> Vec