Compare commits

..

No commits in common. "1ebbca10fa49f3b7d31173cb6a12de36c5f9f6f4" and "ec28ec82e3aec36f28d48c7bb96485944996002a" have entirely different histories.

147 changed files with 1798 additions and 7758 deletions

2
Cargo.lock generated
View file

@ -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",
]

View file

@ -1,8 +1,8 @@
# NOTICE - сторонние компоненты
# NOTICE — сторонние компоненты
Проект `noxis` распространяется по лицензии AGPL-3.0-only
(см. [`LICENSE`](LICENSE)).
Ниже - компоненты third-party, которые используются напрямую и чьи
Ниже — компоненты third-party, которые используются напрямую и чьи
лицензионные условия обязательны к сохранению.
## ristretto_classfile

View file

@ -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).
## Структура

View file

@ -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 }

View file

@ -1,34 +0,0 @@
import java.util.Scanner;
/**
* Answers superclass queries from the obfuscator's frame analysis.
*
* <p>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);
}
}
}

View file

@ -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<String> {
/// Линейный эвристический поиск имён в рефлексивных 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"),

View file

@ -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`):
/// - `<init>`/`<clinit>` - никогда;
/// - `private`/`static`/`final`/`<package-private>` внутри финального класса - можно;
/// - `<init>`/`<clinit>` — никогда;
/// - `private`/`static`/`final`/`<package-private>` внутри финального класса — можно;
/// - `public`/`protected`/`package-private`, если класс не `final` и есть
/// наследники (внутри артефакта или нет) - нельзя, пока нет доказательства.
/// наследники (внутри артефакта или нет) — нельзя, пока нет доказательства.
pub fn method_rename_safety(
program: &Program,
hierarchy: &ClassHierarchy,

View file

@ -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<Shared>,
}
#[derive(Default)]
struct Shared {
cache: HashMap<String, Option<String>>,
child: Option<Pipes>,
dead: bool,
}
struct Pipes {
rx: BufReader<ChildStdout>,
tx: BufWriter<ChildStdin>,
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<String> {
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<String> {
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<Pipes> {
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<Option<String>> {
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);
}
}

View file

@ -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<Regex, regex::Error> {
let mut out = String::from("^");
let chars: Vec<char> = pattern.chars().collect();
@ -43,19 +36,19 @@ fn compile(pattern: &str) -> Result<Regex, regex::Error> {
Regex::new(&out)
}
/// "Do not touch" rules: explicit config patterns + entrypoints.
/// Правила «не трогать»: явные паттерны конфига + entrypoint'ы.
#[derive(Debug, Default, Clone)]
pub struct KeepRules {
class_patterns: Vec<Regex>,
resource_patterns: Vec<Regex>,
/// Exact names to keep (entrypoints, reflection, ...).
fixed: BTreeSet<String>,
/// Member names protected by reflection.
fixed_members: BTreeSet<String>,
/// Точные имена, которые нельзя трогать (entrypoint'ы, рефлексия, ...).
fixed: std::collections::BTreeSet<String>,
/// Имена членов, защищённые рефлексией.
fixed_members: std::collections::BTreeSet<String>,
}
impl KeepRules {
/// Build the rules from the config.
/// Собрать правила из конфига.
pub fn from_config(config: &Config) -> Result<Self, RuleError> {
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<String>) {
self.fixed_members.insert(name.into());
}
/// Add an exact class name (from program analysis).
/// Добавить точное имя класса (из анализа программы).
pub fn keep_exact(&mut self, internal_name: impl Into<String>) {
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<String>,
/// Классы, которые не переименовываются.
pub locked_classes: std::collections::BTreeSet<String>,
}
impl Analysis {
/// Run the whole analysis over the program.
/// Прогнать весь анализ по программе.
pub fn run(program: &Program, config: &Config) -> Result<Self, RuleError> {
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"));
}
}

View file

@ -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<String> = HashSet::new();
let mut seen: HashSet<String> = 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
}
/// `(<params>)<ret>` → `(<params>)`, или `None` при кривом дескрипторе.
fn params_part(descriptor: &str) -> Option<&str> {
let close = descriptor.find(')')?;
if !descriptor.starts_with('(') {
return None;
}
Some(&descriptor[..=close])
}

View file

@ -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<String> = 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<String> {
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<String> {
let Ok(json) = serde_json::from_str::<serde_json::Value>(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<String> {
let Ok(json) = serde_json::from_str::<serde_json::Value>(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<String>| {
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
}

View file

@ -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};

View file

@ -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"
);
}

View file

@ -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"));
}

View file

@ -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"));
}

View file

@ -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}")]

View file

@ -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<State>],
targets: &BTreeSet<u32>,
@ -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<VerificationType> {
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<VerificationType> {
let mut out = Vec::with_capacity(locals.len());
let mut index = 0;

View file

@ -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<Vec<u32>, 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<Label, u32>,
@ -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<String>);
/// Handlers in instruction numbers, for exception edges.
/// Handler'ы в номерах инструкций для рёбер исключений.
pub(super) fn handler_ranges(
table: &[ExceptionHandler],
labels: &BTreeMap<Label, u32>,

View file

@ -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<Vec<VerificationType>, DescError> {
let mut chars = descriptor.chars();
match chars.next() {
@ -57,10 +57,10 @@ pub(crate) fn field_slots(descriptor: &str) -> Result<Vec<VerificationType>, Des
}
}
/// Parameter and return slots (`None` - `void`).
/// Слоты параметров и возврата (`None` — `void`).
type MethodSlots = (Vec<Vec<VerificationType>>, Option<Vec<VerificationType>>);
/// Method descriptor: parameter slots and return slots (`None` - `void`).
/// Дескриптор метода: слоты параметров и слоты возврата (`None` — `void`).
pub(crate) fn method_slots(descriptor: &str) -> Result<MethodSlots, DescError> {
let (params, ret) = descriptor
.split_once('(')
@ -128,43 +128,24 @@ pub(crate) fn method_slots(descriptor: &str) -> Result<MethodSlots, DescError> {
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 [<elem>;` 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 {

View file

@ -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<String>;
}
/// 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<State>,
@ -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<State, ClassfileError> {
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<State, ClassfileError> {
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));

View file

@ -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<Label, u32>,
@ -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<State>],
@ -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<String>) -> VerificationType {
match catch {
Some(name) => VerificationType::Object(name.clone()),

View file

@ -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<String> {
@ -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,

View file

@ -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<VerificationType> = 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<VerificationType> = 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:?}");
}

View file

@ -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: "<init>".to_string(),
descriptor: "()V".to_string(),
itf: false,
},
Insn::Invoke {
kind: crate::insn::InvokeKind::Special,
owner: "demo/Outer".to_string(),
name: "<init>".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,
},
]
);
}

View file

@ -1,4 +1,4 @@
//! Calls and constants: descriptors, `<init>`, value slots.
//! Вызовы и константы: дескрипторы, `<init>`, слоты значений.
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(&params), class, method, "call arguments")?;
super::stack::pop_slots(
state,
count_slots(&params),
class,
method,
"аргументы вызова",
)?;
let mut receiver = None;
if kind != InvokeKind::Static {
receiver = super::stack::pop_slots(state, 1, class, method, "objectref")?.pop();
}
// `<init>` initializes the receiver in ALL its copies.
// `<init>` инициализирует получателя во ВСЕХ его копиях.
if name == "<init>" {
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 `<init>` 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<VerificationType>]) -> usize {
params.iter().map(Vec::len).sum()
}
/// Replace every occurrence of a type with a new one (init via `<init>`).
/// Заменить все вхождения типа новым (инициализация через `<init>`).
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<VerificationType> {
}
}
/// `(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};

View file

@ -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<VerificationType>,
pub stack: Vec<VerificationType>,
}
/// 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")?;

View file

@ -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<VerificationType>) -> 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<VerificationType> {
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,

View file

@ -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<ClassFile, ClassfileError> {
parse::class::parse_class(bytes)
}
/// Write a [`ClassFile`] to bytes, including `Code`/`StackMapTable` recompute.
/// Записать [`ClassFile`] в байты, включая пересчёт `Code`/`StackMapTable`.
pub fn write(class: &ClassFile) -> Result<Vec<u8>, 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()
}

View file

@ -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<Vec<Annotation>, 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<Vec<Vec<Annotation>>, 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<Vec<TypeAnnotation>, 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<AnnotationValue, ClassfileError> {
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::<Result<_, _>>()?,
),
})
}
/// One `annotation` structure → IR (names, not pool indices).
fn annotation(
pool: &ConstantPool<'_>,
anno: &ristretto_classfile::attributes::Annotation,
) -> Result<Annotation, ClassfileError> {
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::<Result<_, ClassfileError>>()?,
})
}
/// 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<TypeAnnotation, ClassfileError> {
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::<Result<_, ClassfileError>>()?,
})
}
/// The `CONSTANT_Integer` behind a `B`/`C`/`S`/`Z`/`I` element.
fn const_int(pool: &ConstantPool<'_>, index: u16) -> Result<i32, ClassfileError> {
match const_from(pool, index)? {
Const::Int(v) => Ok(v),
_ => Err(ClassfileError::Parse("не Integer".into())),
}
}
fn const_long(pool: &ConstantPool<'_>, index: u16) -> Result<i64, ClassfileError> {
match const_from(pool, index)? {
Const::Long(v) => Ok(v),
_ => Err(ClassfileError::Parse("не Long".into())),
}
}
fn const_float(pool: &ConstantPool<'_>, index: u16) -> Result<f32, ClassfileError> {
match const_from(pool, index)? {
Const::Float(v) => Ok(v),
_ => Err(ClassfileError::Parse("не Float".into())),
}
}
fn const_double(pool: &ConstantPool<'_>, index: u16) -> Result<f64, ClassfileError> {
match const_from(pool, index)? {
Const::Double(v) => Ok(v),
_ => Err(ClassfileError::Parse("не Double".into())),
}
}

View file

@ -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<Attribute, ClassfileError> {
Ok(match attr {
RtAttr::SourceFile {
@ -48,12 +47,6 @@ pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result<Attribut
.map(|index| class_name(pool, *index))
.collect::<Result<_, _>>()?,
),
RtAttr::PermittedSubclasses { class_indexes, .. } => Attribute::PermittedSubclasses(
class_indexes
.iter()
.map(|index| class_name(pool, *index))
.collect::<Result<_, _>>()?,
),
RtAttr::EnclosingMethod {
class_index,
method_index,
@ -108,34 +101,11 @@ pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result<Attribut
"Code/StackMapTable разбирает вызывающий код метода".into(),
));
}
RtAttr::RuntimeVisibleAnnotations { annotations, .. } => {
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<Attribute, ClassfileError> {
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<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)
@ -233,7 +203,7 @@ fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>,
}
}
/// A `CONSTANT_Utf8` index where `0` means the value is absent.
/// Индекс `CONSTANT_Utf8`, где `0` означает отсутствие значения.
fn optional_utf8(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)

View file

@ -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<ClassFile, ClassfileError> {
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<ClassFile, ClassfileError> {
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<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)

View file

@ -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<StackMapFrame
})
}
/// The frame's single stack element (`same_locals_1_stack_item`).
/// Единственный элемент стека кадра (`same_locals_1_stack_item`).
fn single(stack: &[RtType], pool: &ConstantPool<'_>) -> Result<VerificationType, ClassfileError> {
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<VerificationType, ClassfileError> {
Ok(match value {
RtType::Top => VerificationType::Top,
@ -100,7 +99,7 @@ fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result<VerificationType, Cl
})
}
/// The catch type (`0` - catch-all for `finally`/`any`).
/// Тип перехвата (`0` — catch-all для `finally`/`any`).
pub(super) fn catch_type(
pool: &ConstantPool<'_>,
index: u16,

View file

@ -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<i32> {
let base = i32::from(index);
match instruction {
@ -73,7 +73,7 @@ fn once(value: i32) -> std::iter::Once<i32> {
std::iter::once(value)
}
/// Turn a sorted set of numbers into sequential labels.
/// Превратить отсортированный набор номеров в последовательные метки.
pub(super) fn assign(indexes: &BTreeSet<u32>) -> BTreeMap<u32, Label> {
indexes
.iter()
@ -82,7 +82,7 @@ pub(super) fn assign(indexes: &BTreeSet<u32>) -> BTreeMap<u32, Label> {
.collect()
}
/// The label for an instruction number.
/// Метка для номера инструкции.
pub(super) fn lookup(labels: &BTreeMap<u32, Label>, index: u16) -> Result<Label, ClassfileError> {
labels
.get(&u32::from(index))
@ -90,7 +90,7 @@ pub(super) fn lookup(labels: &BTreeMap<u32, Label>, index: u16) -> Result<Label,
.ok_or_else(|| ClassfileError::Parse(format!("нет метки для инструкции {index}")))
}
/// Debug-table positions that need labels.
/// Позиции отладочных таблиц, которым нужны метки.
pub(super) fn collect_debug_labels(
attributes: &[RtAttr],
starts: &[u16],
@ -122,7 +122,7 @@ pub(super) fn collect_debug_labels(
Ok(())
}
/// Byte → instruction number (instruction boundaries only).
/// Байт → номер инструкции (только границы инструкций).
pub(super) fn byte_to_index(starts: &[u16], byte: u16) -> Result<u32, ClassfileError> {
starts
.iter()
@ -131,7 +131,7 @@ pub(super) fn byte_to_index(starts: &[u16], byte: u16) -> Result<u32, ClassfileE
.ok_or_else(|| ClassfileError::Parse(format!("смещение {byte} мимо инструкции")))
}
/// End of the range `[start, start+length)`: the index past the end.
/// Конец диапазона `[start, start+length)`: индекс за концом.
fn end_index(
starts: &[u16],
start: u16,
@ -148,7 +148,7 @@ fn end_index(
byte_to_index(starts, end)
}
/// The label for a debug table's byte offset.
/// Метка для байтового смещения отладочной таблицы.
pub(super) fn resolve_byte(
labels: &BTreeMap<u32, Label>,
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<u32, Label>,
starts: &[u16],

View file

@ -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>, u16), ClassfileError> {
let mut cursor = Cursor::new(Vec::new());
let mut offsets = Vec::with_capacity(code.len());

View file

@ -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<'_>,

View file

@ -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<Insn,
Ok(Insn::Branch(cond, resolve(target)?))
}
/// A `switch` target - an instruction number: base plus the backend's relative delta.
/// Цель `switch` — номер инструкции: база плюс относительная дельта backend'а.
fn abs(index: u16, delta: i32, resolve: &Resolver<'_>) -> Result<Label, ClassfileError> {
let absolute = i32::from(index)
.checked_add(delta)

View file

@ -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<Label, ClassfileError> + 'a;
/// Convert one instruction. `index` - its number in the method body (`switch` needs it).
/// Конвертировать одну инструкцию. `index` — её номер в теле метода (нужно `switch`).
pub(super) fn convert(
instruction: &Instruction,
index: u16,

View file

@ -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<'_>,

View file

@ -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;

View file

@ -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<String, ClassfileError> {
let name = pool
.try_get_class(index)
@ -13,7 +13,7 @@ pub(super) fn class_name(pool: &ConstantPool<'_>, index: u16) -> Result<String,
Ok(name.to_string())
}
/// `(owner, name, descriptor)` for a `CONSTANT_Fieldref`/`_Methodref`.
/// `(owner, name, descriptor)` для `CONSTANT_Fieldref`/`_Methodref`.
pub(super) fn ref_parts(
pool: &ConstantPool<'_>,
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<String, ClassfileError> {
let value = pool
.try_get_utf8(index)
@ -66,7 +66,7 @@ pub(super) fn utf8(pool: &ConstantPool<'_>, index: u16) -> Result<String, Classf
Ok(value.to_string())
}
/// The constant for `ldc`/`ldc_w`/`ldc2_w`.
/// Константа для `ldc`/`ldc_w`/`ldc2_w`.
pub(super) fn const_from(pool: &ConstantPool<'_>, index: u16) -> Result<Const, ClassfileError> {
let constant = pool
.try_get(index)
@ -111,7 +111,7 @@ pub(super) fn const_from(pool: &ConstantPool<'_>, index: u16) -> Result<Const, C
})
}
/// `(name, descriptor, bootstrap)` for a `CONSTANT_InvokeDynamic`.
/// `(name, descriptor, bootstrap)` для `CONSTANT_InvokeDynamic`.
pub(super) fn dynamic_parts(
pool: &ConstantPool<'_>,
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,

View file

@ -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<Vec<RtAnno>, ClassfileError> {
annos.iter().map(|anno| annotation(anno, pool)).collect()
}
/// The per-parameter lists of a parameter-annotation attribute.
pub(super) fn parameters(
params: &[Vec<Annotation>],
pool: &mut Pool,
) -> Result<Vec<RtParamAnno>, 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<Vec<RtTypeAnno>, 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<RtAnno, ClassfileError> {
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::<Result<_, ClassfileError>>()?,
})
}
/// 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<RtTypeAnno, ClassfileError> {
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::<Result<_, ClassfileError>>()?,
})
}
/// One IR element value → backend structure, tag preserved.
pub(super) fn element(value: &AnnotationValue, pool: &mut Pool) -> Result<RtElem, ClassfileError> {
fn int(v: i32, pool: &mut Pool) -> Result<u16, ClassfileError> {
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::<Result<_, _>>()?,
},
})
}

View file

@ -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<u32, ClassfileError>,
pub byte_of: &'a dyn Fn(u32) -> Result<u16, ClassfileError>,
}
/// `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::<Result<_, ClassfileError>>()?,
})
}
/// 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<RtAttr, ClassfileError> {
Ok(match attr {
Attribute::SourceFile(name) => RtAttr::SourceFile {
@ -146,13 +145,6 @@ pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result<RtAttr, Class
.map(|name| pool.class(name))
.collect::<Result<_, _>>()?,
},
Attribute::PermittedSubclasses(classes) => RtAttr::PermittedSubclasses {
name_index: pool.utf8("PermittedSubclasses")?,
class_indexes: classes
.iter()
.map(|name| pool.class(name))
.collect::<Result<_, _>>()?,
},
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<RtAttr, Class
.map(|param| helpers::method_param(param, pool))
.collect::<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(),

View file

@ -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<u16, ClassfileError> + '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 {

View file

@ -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))
}

View file

@ -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<RtAttr, ClassfileError> {
/// Тело метода → готовый атрибут `Code` (с логическими номерами инструкций).
pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result<RtAttr, ClassfileError> {
let (labels, bare) = split_marks(&code.insns)?;
let resolve = |label: Label| -> Result<u32, ClassfileError> {
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<Label, u32>, 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<Label, u32>, 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<BTreeMap<u32, u16>, ClassfileError> {
let mut map = BTreeMap::new();
let mut cursor = Cursor::new(Vec::new());
@ -143,7 +132,7 @@ pub(crate) fn measure(insns: &[RtInsn]) -> Result<BTreeMap<u32, u16>, 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<RtInsn, ClassfileError> {
let target = fit_index(target)?;
Ok(match cond {
@ -222,13 +211,13 @@ fn ret_op(prim: Option<Prim>) -> RtInsn {
}
}
/// The instruction number must fit in `u16` (method < 64 KB of code).
/// Номер инструкции обязан влезать в `u16` (метод < 64 КБ кода).
fn fit_index(index: u32) -> Result<u16, ClassfileError> {
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<i32, ClassfileError> {
let (index, target) = (to_i32(index)?, to_i32(target)?);
target

View file

@ -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<RtInsn, ClassfileError> {
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<RtInsn, ClassfileError> {
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<u8, ClassfileError> {
let params = descriptor
.split_once('(')
@ -234,7 +229,7 @@ fn arg_count(descriptor: &str) -> Result<u8, ClassfileError> {
.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 {

View file

@ -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<u16, ClassfileError> {
match arg {
Const::Dynamic {

View file

@ -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<Vec<u8>, 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<Vec<u8>, 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<RtField, Classf
})
}
fn convert_method(
method: &Method,
pool: &mut pool::Pool,
emit_frames: bool,
) -> Result<RtMethod, ClassfileError> {
fn convert_method(method: &Method, pool: &mut pool::Pool) -> Result<RtMethod, ClassfileError> {
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),

View file

@ -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<String, u16>,
@ -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<u16, ClassfileError> {
match value {
Const::Int(v) => self.pool.add_integer(*v).map_err(write_err),

View file

@ -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<u16, ClassfileError> {
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

View file

@ -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<cond>` against zero.
/// `if<cond>` относительно нуля.
Zero(Cond),
/// `if_icmp<cond>`.
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<b|c|s|l|f|d>).
/// Конверсия типов (`i2l`, `f2b`, ... — JVMS §6.5.i2<b|c|s|l|f|d>).
#[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,

View file

@ -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<Prim>),
/// `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<Label> {
match self {
Insn::Branch(_, label) | Insn::Goto(label) | Insn::Jsr(label) => vec![*label],
@ -154,7 +154,7 @@ impl Insn {
}
}
/// An encoded jump target (for inserting opaque predicates and rebuilding the CFG).
/// Незакодированный переход (для вставки opaque-предикатов и перестройки CFG).
pub fn branch_target_mut(&mut self) -> Option<&mut Label> {
match self {
Insn::Branch(_, label) | Insn::Goto(label) => Some(label),

View file

@ -1,13 +1,13 @@
//! # noxis-classfile
//!
//! Own IR for JVM class files: parsing, representation, writing.
//! Собственный IR для классовых файлов JVM: разбор, представление, запись.
//!
//! Why a custom IR instead of working directly with a parser crate: passes
//! need a stable model (labels instead of offsets, a deliberate attribute
//! set), not a third-party API that changes between versions.
//! Почему свой IR, а не работа напрямую с крейтом-парсером: пассам нужна
//! стабильная модель (метки вместо смещений, осознанный набор атрибутов),
//! а не API третьей стороны, который меняется между версиями.
//!
//! Status: model and builder are ready; binary parse/write is stage P1
//! (see `docs/stack.md`).
//! Статус: модель и билдер готовы, бинарный parse/write — этап P1
//! (см. `docs/stack.md`).
pub mod error;
pub mod format;
@ -23,15 +23,7 @@ pub use insn::{
};
pub use model::builder::{ClassBuilder, empty_code};
pub use model::{
Annotation, AnnotationValue, Attribute, BootstrapMethod, ClassFile, Code, ExceptionHandler,
Field, InnerClass, LineNumber, LocalVariable, LocalVariableType, Method, MethodParameter,
Program, RecordComponent, Resource, TypeAnnotation, Version,
Attribute, BootstrapMethod, ClassFile, Code, ExceptionHandler, Field, InnerClass, LineNumber,
LocalVariable, LocalVariableType, Method, MethodParameter, Program, RecordComponent, Resource,
Version,
};
/// Safety budget: a method body that would grow past this many instructions
/// is left alone by the expanding passes (`strings`, `constants`).
///
/// The writer caps a method body at 64KB; at a pessimistic 8 bytes per
/// instruction this count can never overflow it, while real methods
/// (hundreds of instructions) never come close.
pub const MAX_METHOD_INSNS: usize = 8_000;

View file

@ -1,55 +0,0 @@
//! Runtime-visible/invisible annotations: names instead of pool indices.
//!
//! Raw `info` blobs go stale the moment the pool is rebuilt on write, and
//! the JVM's reflection parser then dies with `AnnotationFormatError` or
//! reads neighboring attribute bytes as signatures.
/// One `annotation` structure: the type descriptor + element-value pairs.
#[derive(Debug, Clone, PartialEq)]
pub struct Annotation {
/// The annotation type as a field descriptor (`Lpkg/Ann;`).
pub descriptor: String,
/// `(element name, value)` pairs in class-file order.
pub elements: Vec<(String, AnnotationValue)>,
}
/// One `type_annotation` (JVMS §4.7.20): a type-use annotation on a
/// method return type, a cast, a local variable, and so on.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeAnnotation {
/// `target_info` + `type_path` bytes (§4.7.20.1-2): no pool references
/// there at all, kept opaque so write copies them verbatim.
pub target: Vec<u8>,
/// The annotated type as a field descriptor (`type_index`).
pub descriptor: String,
/// `(element name, value)` pairs - same shape as [`Annotation`]'s.
pub elements: Vec<(String, AnnotationValue)>,
}
/// A single `element_value`: one variant per tag, so `B`/`C`/`S`/`Z`
/// keep their identity (the pool stores them all as `CONSTANT_Integer`,
/// but HotSpot checks the tag against the annotation member's type).
#[derive(Debug, Clone, PartialEq)]
pub enum AnnotationValue {
Byte(i32),
Char(i32),
Double(f64),
Float(f32),
Int(i32),
Long(i64),
Short(i32),
Boolean(i32),
/// The `s` tag: a `CONSTANT_Utf8`, not a `CONSTANT_String`.
String(String),
/// The `e` tag: enum type descriptor + constant name.
Enum {
descriptor: String,
name: String,
},
/// The `c` tag: a class-info descriptor (`Ljava/lang/String;` or `I`).
Class(String),
/// The `@` tag: a nested annotation.
Nested(Box<Annotation>),
/// The `[` tag: array of values.
Array(Vec<AnnotationValue>),
}

View file

@ -1,8 +1,8 @@
//! Building classes "from scratch": junk classes, runtime decoders, noise annotations.
//! Сборка классов «с нуля»: junk-классы, рантайм-декодеры, аннотации-шум.
use crate::model::{Attribute, ClassFile, Code, Field, Method, Version};
/// A class builder with no binary representation on input.
/// Строитель класса без бинарного представления на входе.
#[derive(Debug, Clone)]
pub struct ClassBuilder {
version: Version,
@ -16,8 +16,8 @@ pub struct ClassBuilder {
}
impl ClassBuilder {
/// A new `public` class with the given superclass (`None` = `java/lang/Object`,
/// except for `java/lang/Object` itself - it has no superclass).
/// Новый класс `public` с указанным суперклассом (`None` = `java/lang/Object`,
/// кроме самого `java/lang/Object` — у него суперкласса нет).
pub fn new(this_class: impl Into<String>, super_class: Option<&str>) -> Self {
let this_class = this_class.into();
let super_class = match super_class {
@ -37,25 +37,25 @@ impl ClassBuilder {
}
}
/// Set the class-file version.
/// Задать версию классового файла.
pub fn version(mut self, version: Version) -> Self {
self.version = version;
self
}
/// Set access flags (overwrites `ACC_PUBLIC|ACC_SUPER`).
/// Задать флаги доступа (перезаписывает `ACC_PUBLIC|ACC_SUPER`).
pub fn access_flags(mut self, flags: u16) -> Self {
self.access_flags = flags;
self
}
/// Add an interface.
/// Добавить интерфейс.
pub fn interface(mut self, name: impl Into<String>) -> Self {
self.interfaces.push(name.into());
self
}
/// Add a field.
/// Добавить поле.
pub fn field(mut self, name: impl Into<String>, descriptor: impl Into<String>) -> Self {
self.fields.push(Field {
access_flags: 0x0001, // ACC_PUBLIC
@ -66,7 +66,7 @@ impl ClassBuilder {
self
}
/// Add a method without a body (`abstract`/`native` must set their own flags).
/// Добавить метод без тела (`abstract`/`native` должны выставить флаги сами).
pub fn method(
mut self,
access_flags: u16,
@ -83,7 +83,7 @@ impl ClassBuilder {
self
}
/// Add a method with a body.
/// Добавить метод с телом.
pub fn method_with_code(
mut self,
access_flags: u16,
@ -101,13 +101,13 @@ impl ClassBuilder {
self
}
/// Add a class-level attribute.
/// Добавить атрибут уровня класса.
pub fn attribute(mut self, attribute: Attribute) -> Self {
self.attributes.push(attribute);
self
}
/// Build the class.
/// Собрать класс.
pub fn build(self) -> ClassFile {
ClassFile {
version: self.version,
@ -122,7 +122,7 @@ impl ClassBuilder {
}
}
/// An empty method body (`return`), for junk methods.
/// Пустое тело метода (`return`), для junk-методов.
pub fn empty_code(max_locals: u16) -> Code {
Code {
max_stack: 0,

View file

@ -1,16 +1,14 @@
//! The "program" structure - the unit of work for the pipeline.
//! Структура «программы» — единица работы пайплайна.
pub mod annotations;
pub mod builder;
pub mod version;
pub use annotations::{Annotation, AnnotationValue, TypeAnnotation};
pub use version::Version;
use crate::format::StackMapFrame;
use crate::insn::{Const, Insn, Label};
/// Unknown/specific attributes are stored as bytes - lossless round-trip.
/// Неизвестные/специфичные атрибуты хранятся байтами — round-trip без потерь.
#[derive(Debug, Clone, PartialEq)]
pub enum Attribute {
SourceFile(String),
@ -21,49 +19,26 @@ pub enum Attribute {
Deprecated,
Synthetic,
InnerClasses(Vec<InnerClass>),
/// `NestHost`: the class acting as nest host (JVMS §4.7.28).
/// `NestHost`: класс, служащий nest-хостом (JVMS §4.7.28).
NestHost(String),
/// `NestMembers`: the member classes of this nest host (JVMS §4.7.29).
/// `NestMembers`: классы-члены этого nest-хоста (JVMS §4.7.29).
NestMembers(Vec<String>),
/// `PermittedSubclasses`: who may extend a sealed class (JVMS §4.7.31).
/// Stored as names: pool indices go stale when the pool is rebuilt.
PermittedSubclasses(Vec<String>),
/// A field's `ConstantValue` (`static final`): a value from the pool.
/// `ConstantValue` поля (`static final`): значение из пула.
ConstantValue(Const),
/// `BootstrapMethods` for `invokedynamic` (lambdas): method + arguments.
/// `BootstrapMethods` для `invokedynamic` (лямбды): метод + аргументы.
BootstrapMethods(Vec<BootstrapMethod>),
/// `EnclosingMethod`: the class and optional method enclosing a local class.
/// `EnclosingMethod`: класс и опциональный метод, содержащие локальный класс.
EnclosingMethod {
class: String,
method: Option<(String, String)>,
},
/// `MethodParameters`: formal parameter names (`None` - unnamed).
/// `MethodParameters`: имена формальных параметров (`None` — безымянный).
MethodParameters(Vec<MethodParameter>),
/// `Record`: the record class's components.
/// `Record`: компоненты record-класса.
Record(Vec<RecordComponent>),
/// `LocalVariableTypeTable`: generic local signatures (like LVT).
/// `LocalVariableTypeTable`: сигнатуры generic-локальных (как LVT).
LocalVariableTypeTable(Vec<LocalVariableType>),
/// `RuntimeVisibleAnnotations` (JVMS §4.7.16): parsed, not raw bytes -
/// reflection reads them at runtime and raw indices go stale on write.
RuntimeVisibleAnnotations(Vec<Annotation>),
/// `RuntimeInvisibleAnnotations` (JVMS §4.7.17): CLASS-retention ones.
RuntimeInvisibleAnnotations(Vec<Annotation>),
/// `RuntimeVisibleParameterAnnotations` (JVMS §4.7.18): per-parameter
/// annotations. Parsed like the class-level ones - raw pool indices go
/// stale when the pool is rebuilt.
RuntimeVisibleParameterAnnotations(Vec<Vec<Annotation>>),
/// `RuntimeInvisibleParameterAnnotations` (JVMS §4.7.19).
RuntimeInvisibleParameterAnnotations(Vec<Vec<Annotation>>),
/// `RuntimeVisibleTypeAnnotations` (JVMS §4.7.20): type-use
/// annotations. Parsed - raw pool indices go stale on write and ASM
/// dies with `ArrayIndexOutOfBoundsException` reading them back.
RuntimeVisibleTypeAnnotations(Vec<TypeAnnotation>),
/// `RuntimeInvisibleTypeAnnotations` (JVMS §4.7.21).
RuntimeInvisibleTypeAnnotations(Vec<TypeAnnotation>),
/// `AnnotationDefault` (JVMS §4.7.22): the default value of one
/// annotation member - a single `element_value` with pool references.
AnnotationDefault(AnnotationValue),
/// Everything else: name + raw `info` bytes (careful with pool indices).
/// Всё остальное: имя + сырые байты `info` (осторожно с индексами пула).
Raw {
name: String,
data: Vec<u8>,
@ -72,14 +47,14 @@ pub enum Attribute {
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineNumber {
/// Start label (the writer computes bytes - survives pass insertions).
/// Метка начала (байты вычисляет writer — переживает вставки пассов).
pub start: Label,
pub line: u16,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LocalVariable {
/// Visibility-range labels (the writer recomputes them into bytes).
/// Метки диапазона видимости (writer пересчитает в байты).
pub start: Label,
pub end: Label,
pub name: String,
@ -95,10 +70,10 @@ pub struct InnerClass {
pub access_flags: u16,
}
/// One `bootstrap` method: a `MethodHandle`-style reference + const arguments.
/// Один `bootstrap`-метод: ссылка вида `MethodHandle` + аргументы-константы.
#[derive(Debug, Clone, PartialEq)]
pub struct BootstrapMethod {
/// The `reference_kind` number (JVMS §5.4.3.5).
/// Номер `reference_kind` (JVMS §5.4.3.5).
pub kind: u8,
pub owner: String,
pub name: String,
@ -107,14 +82,14 @@ pub struct BootstrapMethod {
pub args: Vec<Const>,
}
/// A method's formal parameter (`MethodParameters`).
/// Формальный параметр метода (`MethodParameters`).
#[derive(Debug, Clone, PartialEq)]
pub struct MethodParameter {
pub name: Option<String>,
pub access_flags: u16,
}
/// A `Record` component: a record class field with attributes.
/// Компонент `Record`: поле record-класса с атрибутами.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordComponent {
pub name: String,
@ -122,10 +97,10 @@ pub struct RecordComponent {
pub attributes: Vec<Attribute>,
}
/// A `LocalVariableTypeTable` entry (like `LocalVariable`, but with a signature).
/// Строка `LocalVariableTypeTable` (как `LocalVariable`, но с сигнатурой).
#[derive(Debug, Clone, PartialEq)]
pub struct LocalVariableType {
/// Visibility-range labels (the writer recomputes them into bytes).
/// Метки диапазона видимости (writer пересчитает в байты).
pub start: Label,
pub end: Label,
pub name: String,
@ -151,18 +126,18 @@ pub struct Method {
}
impl Method {
/// `native`/`abstract` methods have no body.
/// `native`/`abstract` тела не имеют.
pub fn has_code(&self) -> bool {
self.code.is_some()
}
}
/// A method body.
/// Тело метода.
#[derive(Debug, Clone, PartialEq)]
pub struct Code {
pub max_stack: u16,
pub max_locals: u16,
/// Label markers + instructions; branches point at a [`Label`].
/// Маркеры меток + инструкции; ветвления указывают на [`Label`].
pub insns: Vec<Insn>,
pub exception_table: Vec<ExceptionHandler>,
pub frames: Vec<StackMapFrame>,
@ -170,7 +145,7 @@ pub struct Code {
}
impl Code {
/// All labels declared in the method body.
/// Все метки, объявленные в теле метода.
pub fn labels(&self) -> Vec<Label> {
self.insns
.iter()
@ -184,15 +159,15 @@ impl Code {
#[derive(Debug, Clone, PartialEq)]
pub struct ExceptionHandler {
/// `None` - catch-all (`finally`).
/// `None` — catch-all (`finally`).
pub start: Label,
pub end: Label,
pub handler: Label,
/// The class's internal name, or `None` for `any`.
/// Внутреннее имя класса или `None` для `any`.
pub catch_type: Option<String>,
}
/// One `.class` in normalized form.
/// Один `.class` в нормализованном виде.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassFile {
pub version: Version,
@ -206,34 +181,34 @@ pub struct ClassFile {
}
impl ClassFile {
/// Finds a method by name and descriptor.
/// Ищет метод по имени и дескриптору.
pub fn method(&self, name: &str, descriptor: &str) -> Option<&Method> {
self.methods
.iter()
.find(|m| m.name == name && m.descriptor == descriptor)
}
/// Finds a method by name and descriptor (mutating access).
/// Ищет метод по имени и дескриптору (мутирующий доступ).
pub fn method_mut(&mut self, name: &str, descriptor: &str) -> Option<&mut Method> {
self.methods
.iter_mut()
.find(|m| m.name == name && m.descriptor == descriptor)
}
/// The `ACC_INTERFACE` flag.
/// Признак `ACC_INTERFACE`.
pub fn is_interface(&self) -> bool {
self.access_flags & 0x0200 != 0
}
}
/// A resource inside the archive (JSON, properties, images, ...).
/// Ресурс внутри архива (JSON, properties, картинки, ...).
#[derive(Debug, Clone, PartialEq)]
pub struct Resource {
pub path: String,
pub data: Vec<u8>,
}
/// The whole input program: classes + resources.
/// Вся входная программа: классы + ресурсы.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Program {
pub classes: Vec<ClassFile>,
@ -241,24 +216,24 @@ pub struct Program {
}
impl Program {
/// A class by internal name (`pkg/Class`).
/// Класс по внутреннему имени (`pkg/Class`).
pub fn class(&self, internal_name: &str) -> Option<&ClassFile> {
self.classes.iter().find(|c| c.this_class == internal_name)
}
/// A class by internal name (mutating access).
/// Класс по внутреннему имени (мутирующий доступ).
pub fn class_mut(&mut self, internal_name: &str) -> Option<&mut ClassFile> {
self.classes
.iter_mut()
.find(|c| c.this_class == internal_name)
}
/// A resource by its path inside the archive.
/// Ресурс по пути внутри архива.
pub fn resource(&self, path: &str) -> Option<&Resource> {
self.resources.iter().find(|r| r.path == path)
}
/// Whether the program is empty.
/// Пустая ли программа.
pub fn is_empty(&self) -> bool {
self.classes.is_empty() && self.resources.is_empty()
}

View file

@ -1,6 +1,6 @@
//! Class-file version (major/minor).
//! Версия классового файла (major/minor).
/// The class-file version.
/// Версия классового файла.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
pub minor: u16,

View file

@ -1,9 +1,9 @@
//! Acceptance for `compute_frames`: fixtures plus emitter edge cases.
//! Приёмка `compute_frames` на фикстурах (`tests/data`).
//!
//! Frames are dropped and recomputed. Judges: determinism + IR round-trip +
//! real `java -Xverify:all` for classes without external dependencies.
//! (The backend's `verify_class` is unfit for acceptance: it expects frames
//! in bytes while `from_bytes` hands out indices - see `todo.md`.)
//! Кадры сносятся и считаются заново. Судьи: детерминизм + round-trip IR +
//! настоящий `java -Xverify:all` для классов без внешних зависимостей.
//! (`verify_class` backend'а для приёмки не годится: он ждёт кадры в байтах,
//! а `from_bytes` отдаёт в индексах — см. `todo.md`.)
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -11,12 +11,9 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use noxis_classfile::{
Arith, BranchCond, ClassBuilder, Code, Cond, Const, Insn, Prim, SlotKind, Version,
{Hierarchy, compute_frames, format},
};
use noxis_classfile::{Hierarchy, compute_frames, format};
/// A `class → superclass` map for LUB.
/// Карта `класс → суперкласс` для LUB.
#[derive(Default)]
struct MapHierarchy {
supers: BTreeMap<String, String>,
@ -28,13 +25,13 @@ impl Hierarchy for MapHierarchy {
}
}
/// JDK-only classes - `java` checks them fully.
/// Классы только на JDK — их `java` проверит полностью.
const JDK_ONLY: [&str; 2] = [
"dev/loki/lorep/util/TimeUtil",
"dev/loki/lorep/util/PaginationUtil",
];
/// Fixtures: drop frames, recompute, check the output.
/// Фикстуры: снести кадры, посчитать заново, проверить выход.
#[test]
fn fixtures_recompute_and_verify() {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
@ -44,7 +41,7 @@ fn fixtures_recompute_and_verify() {
.filter(|path| path.extension().is_some_and(|ext| ext == "class"))
.collect();
names.sort();
assert!(!names.is_empty(), "no fixtures in tests/data");
assert!(!names.is_empty(), "нет фикстур в tests/data");
let mut supers = BTreeMap::new();
let mut parsed = Vec::new();
@ -53,7 +50,7 @@ fn fixtures_recompute_and_verify() {
supers.insert(class.this_class.clone(), class.super_class.clone());
parsed.push(class);
}
// Only `java/lang/Object` has no superclass.
// Без суперкласса — только `java/lang/Object`.
supers.entry("java/lang/Object".to_string()).or_insert(None);
let hierarchy = MapHierarchy {
supers: supers
@ -74,11 +71,11 @@ fn fixtures_recompute_and_verify() {
}
let first = compute_frames(&class.this_class, method, &hierarchy).expect("recompute");
method.code.as_mut().expect("code").frames = first.clone();
// Determinism: a second run yields the same frames.
// Детерминизм: повторный прогон даёт те же кадры.
let second = compute_frames(&class.this_class, method, &hierarchy).expect("recompute");
assert_eq!(first, second, "nondeterministic frames");
assert_eq!(first, second, "недетерминированные кадры");
}
// Round-trip: written bytes read back into the same IR (frames included).
// Round-trip: записанное читается в тот же IR (включая кадры).
let written = format::write(class).expect("write");
assert_eq!(
format::parse(&written).expect("re-parse"),
@ -92,85 +89,7 @@ fn fixtures_recompute_and_verify() {
let _ = std::fs::remove_dir_all(&scratch);
}
/// A join with a `double` below on the stack must emit it as ONE entry.
///
/// Regression: the emitter used to write the slot pair (`[Double, Top]`),
/// like `javac` does for locals - but on the operand stack `javac` writes a
/// bare `[Double]`, and HotSpot rejects the pair with
/// `Inconsistent stackmap frames`.
#[test]
fn wide_stack_join_emits_single_entries() {
// iload_0, i2d, iload_1, <opaque join>, i2d, ddiv, d2i, ireturn.
// At the join the stack holds a double plus an int.
let (dead, into) = (100, 101);
let mut insns = vec![
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Convert(noxis_classfile::Convert::I2D),
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
];
insns.extend([
Insn::Const(Const::Int(7)),
Insn::Dup,
Insn::Binary {
prim: Prim::Int,
op: Arith::Mul,
},
Insn::Const(Const::Int(7)),
Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
},
Insn::Const(Const::Int(1)),
Insn::Binary {
prim: Prim::Int,
op: Arith::And,
},
Insn::Branch(BranchCond::Zero(Cond::Ne), dead),
Insn::Goto(into),
Insn::Mark(dead),
Insn::Nop,
Insn::Mark(into),
Insn::Convert(noxis_classfile::Convert::I2D),
Insn::Binary {
prim: Prim::Double,
op: Arith::Div,
},
Insn::Convert(noxis_classfile::Convert::D2I),
Insn::Return(Some(Prim::Int)),
]);
let code = Code {
max_stack: 6,
max_locals: 2,
insns,
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
};
let class = ClassBuilder::new("demo/Wide", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(0x0009, "calc", "(II)I", code)
.build();
let hierarchy = MapHierarchy::default();
let frames = compute_frames(&class.this_class, &class.methods[0], &hierarchy).expect("frames");
let mut class = class;
class.methods[0].code.as_mut().expect("code").frames = frames;
if !java_available() {
eprintln!("SKIP: no java");
return;
}
let scratch = std::env::temp_dir().join(format!("noxis-wide-{}", std::process::id()));
let bytes = format::write(&class).expect("write");
java_verify(&scratch, &class, &bytes).expect("java -Xverify:all");
let _ = std::fs::remove_dir_all(&scratch);
}
/// Whether `java` is available for checks with the real verifier.
/// Есть ли `java` для проверки настоящим верификатором.
fn java_available() -> bool {
Command::new("java")
.arg("-version")
@ -178,60 +97,8 @@ fn java_available() -> bool {
.is_ok_and(|out| out.status.success())
}
/// A v1.5 (major 49) class must not carry a `StackMapTable`: the old verifier
/// uses type inference, and ASM/Paper reject the attribute on pre-v6 classes
/// ("Class versions V1_5 or less must use F_NEW frames"). Real case: the
/// string-decoder is built at major 49; a later pass recomputes its frames,
/// and the writer used to emit them anyway - Paper then failed to convert the
/// plugin class.
#[test]
fn old_version_class_omits_stack_map_table() {
let insns = vec![
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Branch(BranchCond::Zero(Cond::Ne), 100),
Insn::Const(Const::Int(0)),
Insn::Return(Some(Prim::Int)),
Insn::Mark(100),
Insn::Const(Const::Int(1)),
Insn::Return(Some(Prim::Int)),
];
let code = Code {
max_stack: 1,
max_locals: 1,
insns,
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
};
let class = ClassBuilder::new("demo/Old", Some("java/lang/Object"))
.version(Version {
minor: 0,
major: 49,
})
.method_with_code(0x0009, "pick", "(I)I", code)
.build();
let hierarchy = MapHierarchy::default();
let frames = compute_frames(&class.this_class, &class.methods[0], &hierarchy).expect("frames");
assert!(
!frames.is_empty(),
"the branch must produce at least one frame"
);
let mut class = class;
class.methods[0].code.as_mut().expect("code").frames = frames;
let bytes = format::write(&class).expect("write v1.5 class");
assert!(
!bytes
.windows(b"StackMapTable".len())
.any(|w| w == b"StackMapTable"),
"a major-49 class must not emit StackMapTable"
);
}
/// Write a class into a package tree and run `java -Xverify:all`.
/// Success means loading without verification errors (`main` may be missing).
/// Записать класс в дерево пакетов и прогнать `java -Xverify:all`.
/// Успех — загрузка без ошибок верификации (`main` при этом отсутствует).
fn java_verify(
scratch: &Path,
class: &noxis_classfile::ClassFile,
@ -251,7 +118,7 @@ fn java_verify(
.arg(scratch)
.arg(&dotted)
.output()
.map_err(|e| format!("running java: {e}"))?;
.map_err(|e| format!("запуск java: {e}"))?;
let stderr = String::from_utf8_lossy(&out.stderr);
for bad in [
"VerifyError",

View file

@ -4,7 +4,7 @@
//! сопоставляет запись `LocalVariableTypeTable` с `LocalVariableTable` по
//! сырому `name_index`. Дублирующий `Utf8` для одного имени даёт разные индексы
//! и рушит класс: `ClassFormatError: LVTT entry ... does not match any LVT
//! entry`. Писатель обязан интернировать строки - поэтому в записанном пуле
//! entry`. Писатель обязан интернировать строки — поэтому в записанном пуле
//! каждый `CONSTANT_Utf8` уникален.
#![allow(clippy::expect_used, clippy::unwrap_used)]

View file

@ -2,18 +2,18 @@
//!
//! Пул при записи строится заново (порядок другой), поэтому сравнивается IR,
//! а не байты. Записанные байты обязаны проходить структурный `verify`
//! backend'а - это ловит битые ссылки пула и кривые атрибуты.
//! backend'а — это ловит битые ссылки пула и кривые атрибуты.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{ClassFile, format};
use ristretto_classfile::attributes::{
Attribute as RtAttr, ExceptionTableEntry as RtEntry, Instruction as Rt, LineNumber as RtLine,
StackFrame as RtFrame,
Attribute as RtAttr, BootstrapMethod as RtBsm, ExceptionTableEntry as RtEntry,
Instruction as Rt, LineNumber as RtLine, StackFrame as RtFrame,
};
use ristretto_classfile::{
ClassAccessFlags, ClassFile as RtClass, ConstantPool, Field as RtField, FieldAccessFlags,
FieldType, JAVA_21, Method as RtMethod, MethodAccessFlags,
FieldType, JAVA_21, Method as RtMethod, MethodAccessFlags, ReferenceKind,
};
/// Минимальный класс: версия, флаги, поле с `ConstantValue`, `SourceFile`.
@ -151,6 +151,85 @@ fn code_with_branches_round_trip() {
assert_eq!(code.attributes.len(), 1);
}
/// `BootstrapMethods` + `invokedynamic` переживают round-trip.
#[test]
fn bootstrap_methods_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Lambda").expect("add_class");
let object = pool.add_class("java/lang/Object").expect("add_object");
let owner = pool.add_class("demo/RT").expect("owner");
let method_ref = pool.add_method_ref(owner, "boot", "()V").expect("ref");
let handle = pool
.add_method_handle(ReferenceKind::InvokeStatic, method_ref)
.expect("handle");
let arg = pool.add_string("x").expect("arg");
let bsm_name = pool.add_utf8("BootstrapMethods").expect("attr");
let name = pool.add_utf8("run").expect("name");
let desc = pool.add_utf8("()V").expect("desc");
let code_name = pool.add_utf8("Code").expect("attr");
let dynamic = pool.add_invoke_dynamic(0, "run", "()V").expect("indy");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::STATIC,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::Code {
name_index: code_name,
max_stack: 1,
max_locals: 0,
code: vec![Rt::Invokedynamic(dynamic), Rt::Return],
exception_table: vec![],
attributes: vec![],
}],
}],
attributes: vec![RtAttr::BootstrapMethods {
name_index: bsm_name,
methods: vec![RtBsm {
bootstrap_method_ref: handle,
arguments: vec![arg],
}],
}],
..RtClass::default()
};
let ir = round_trip(&rt);
assert_eq!(ir.attributes.len(), 1);
assert!(format!("{:?}", ir.attributes[0]).contains("BootstrapMethods"));
}
/// `NestMembers` переживает пересборку пула (баг: `ClassFormatError`).
#[test]
fn nest_attributes_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Nest").expect("c");
let object = pool.add_class("java/lang/Object").expect("o");
let member = pool.add_class("demo/Nest$Inner").expect("m");
let mn = pool.add_utf8("NestMembers").expect("n");
let mems = RtAttr::NestMembers {
name_index: mn,
class_indexes: vec![this, member],
};
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
this_class: this,
super_class: object,
attributes: vec![mems],
..RtClass::default()
};
let ir = round_trip(&rt);
assert!(format!("{:?}", ir.attributes).contains("NestMembers"));
}
/// `parse → write → parse` даёт тот же IR; записанное верифицируется.
fn round_trip(rt: &RtClass<'_>) -> ClassFile {
let mut original = Vec::new();
rt.to_bytes(&mut original).expect("to_bytes");
@ -164,10 +243,3 @@ fn round_trip(rt: &RtClass<'_>) -> ClassFile {
assert_eq!(first, second, "IR обязан пережить round-trip");
second
}
/// A bare `0x200` interface (no `ABSTRACT`, as some compilers emit) must
/// survive the round trip: HotSpot tolerates it, so we normalize on parse
/// instead of dying in the backend's strict verifier on write.
mod attrs;
mod code;
mod type_annotations;

View file

@ -1,267 +0,0 @@
//! Attribute round trips: bootstrap methods, nesting, flags, sealing.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::round_trip;
use ristretto_classfile::attributes::{
Attribute as RtAttr, BootstrapMethod as RtBsm, Instruction as Rt,
};
use ristretto_classfile::{
ClassAccessFlags, ClassFile as RtClass, ConstantPool, JAVA_21, Method as RtMethod,
MethodAccessFlags, ReferenceKind,
};
/// `BootstrapMethods` + `invokedynamic` survive the round trip.
#[test]
fn bootstrap_methods_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Lambda").expect("add_class");
let object = pool.add_class("java/lang/Object").expect("add_object");
let owner = pool.add_class("demo/RT").expect("owner");
let method_ref = pool.add_method_ref(owner, "boot", "()V").expect("ref");
let handle = pool
.add_method_handle(ReferenceKind::InvokeStatic, method_ref)
.expect("handle");
let arg = pool.add_string("x").expect("arg");
let bsm_name = pool.add_utf8("BootstrapMethods").expect("attr");
let name = pool.add_utf8("run").expect("name");
let desc = pool.add_utf8("()V").expect("desc");
let code_name = pool.add_utf8("Code").expect("attr");
let dynamic = pool.add_invoke_dynamic(0, "run", "()V").expect("indy");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::STATIC,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::Code {
name_index: code_name,
max_stack: 1,
max_locals: 0,
code: vec![Rt::Invokedynamic(dynamic), Rt::Return],
exception_table: vec![],
attributes: vec![],
}],
}],
attributes: vec![RtAttr::BootstrapMethods {
name_index: bsm_name,
methods: vec![RtBsm {
bootstrap_method_ref: handle,
arguments: vec![arg],
}],
}],
..RtClass::default()
};
let ir = round_trip(&rt);
assert_eq!(ir.attributes.len(), 1);
assert!(format!("{:?}", ir.attributes[0]).contains("BootstrapMethods"));
}
/// `NestMembers` переживает пересборку пула (баг: `ClassFormatError`).
#[test]
fn nest_attributes_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Nest").expect("c");
let object = pool.add_class("java/lang/Object").expect("o");
let member = pool.add_class("demo/Nest$Inner").expect("m");
let mn = pool.add_utf8("NestMembers").expect("n");
let mems = RtAttr::NestMembers {
name_index: mn,
class_indexes: vec![this, member],
};
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
this_class: this,
super_class: object,
attributes: vec![mems],
..RtClass::default()
};
let ir = round_trip(&rt);
assert!(format!("{:?}", ir.attributes).contains("NestMembers"));
}
/// `parse → write → parse` даёт тот же IR; записанное верифицируется.
#[test]
fn bare_interface_flags_normalize_on_parse() {
use ristretto_classfile::ClassAccessFlags;
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Bare").expect("add_class");
let object = pool.add_class("java/lang/Object").expect("add_object");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::INTERFACE,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![],
attributes: vec![],
..RtClass::default()
};
let ir = round_trip(&rt);
assert_eq!(ir.access_flags & 0x0200, 0x0200, "still an interface");
assert_eq!(
ir.access_flags & 0x0400,
0x0400,
"abstract is implied for interfaces"
);
}
/// `PermittedSubclasses` survives the round trip: its pool indices are
/// remapped on write (not copied verbatim), or the backend rejects the
/// rebuilt pool (`bad constant type`).
#[test]
fn permitted_subclasses_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Sealed").expect("add_class");
let object = pool.add_class("java/lang/Object").expect("add_object");
let permitted = pool.add_class("demo/Impl").expect("add permitted");
let attr_name = pool.add_utf8("PermittedSubclasses").expect("attr");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC | ClassAccessFlags::ABSTRACT,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![],
attributes: vec![RtAttr::PermittedSubclasses {
name_index: attr_name,
class_indexes: vec![permitted],
}],
..RtClass::default()
};
let ir = round_trip(&rt);
assert_eq!(ir.this_class, "demo/Sealed");
}
/// Runtime-visible annotations on a method survive the round trip: the
/// pool is rebuilt on write, so raw index blobs would go stale and
/// reflection (`Method.getAnnotation`) would die with
/// `AnnotationFormatError`/`GenericSignatureFormatError`.
#[test]
fn runtime_visible_annotations_round_trip() {
use ristretto_classfile::attributes::{
Annotation as RtAnno, AnnotationElement as RtElem, AnnotationValuePair as RtPair,
};
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Anno").expect("this");
let object = pool.add_class("java/lang/Object").expect("object");
let name = pool.add_utf8("run").expect("name");
let desc = pool.add_utf8("()V").expect("desc");
let code_name = pool.add_utf8("Code").expect("code");
let attr_name = pool.add_utf8("RuntimeVisibleAnnotations").expect("rva");
let marker = pool.add_utf8("Ldemo/Marker;").expect("marker");
let value_key = pool.add_utf8("value").expect("value key");
let hello = pool.add_utf8("hello").expect("hello");
let klass_key = pool.add_utf8("klass").expect("klass key");
let target = pool.add_utf8("Ldemo/Target;").expect("target");
let kind_key = pool.add_utf8("kind").expect("kind key");
let kind_type = pool.add_utf8("Ldemo/Kind;").expect("kind type");
let one = pool.add_utf8("ONE").expect("one");
let nested_key = pool.add_utf8("nested").expect("nested key");
let nested_type = pool.add_utf8("Ldemo/Nested;").expect("nested type");
let arr_key = pool.add_utf8("arr").expect("arr key");
let seven = pool.add_integer(7).expect("seven");
let annotation = RtAnno {
type_index: marker,
elements: vec![
RtPair {
name_index: value_key,
value: RtElem::String {
const_value_index: hello,
},
},
RtPair {
name_index: klass_key,
value: RtElem::Class {
class_info_index: target,
},
},
RtPair {
name_index: kind_key,
value: RtElem::Enum {
type_name_index: kind_type,
const_name_index: one,
},
},
RtPair {
name_index: nested_key,
value: RtElem::Annotation {
annotation: RtAnno {
type_index: nested_type,
elements: vec![],
},
},
},
RtPair {
name_index: arr_key,
value: RtElem::Array {
values: vec![
RtElem::String {
const_value_index: hello,
},
RtElem::Int {
const_value_index: seven,
},
],
},
},
],
};
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::STATIC,
name_index: name,
descriptor_index: desc,
attributes: vec![
RtAttr::Code {
name_index: code_name,
max_stack: 0,
max_locals: 1,
code: vec![Rt::Return],
exception_table: vec![],
attributes: vec![],
},
RtAttr::RuntimeVisibleAnnotations {
name_index: attr_name,
annotations: vec![annotation],
},
],
}],
attributes: vec![],
..RtClass::default()
};
let ir = round_trip(&rt);
let attrs = &ir.methods[0].attributes;
let annos = attrs
.iter()
.find_map(|a| match a {
noxis_classfile::Attribute::RuntimeVisibleAnnotations(list) => Some(list),
_ => None,
})
.expect("annotations modeled");
assert_eq!(annos.len(), 1);
assert_eq!(annos[0].descriptor, "Ldemo/Marker;");
assert_eq!(annos[0].elements.len(), 5);
}

View file

@ -1,108 +0,0 @@
//! Code-level round trips that the IR must survive.
use noxis_classfile::Insn;
use noxis_classfile::format;
use ristretto_classfile::attributes::{Attribute as RtAttr, Instruction as Rt};
use ristretto_classfile::{
ClassAccessFlags, ClassFile as RtClass, ConstantPool, JAVA_21, Method as RtMethod,
MethodAccessFlags,
};
/// `invokestatic` on an *interface* method (`List.of`) needs a
/// `CONSTANT_InterfaceMethodref`: writing a plain `Methodref` passes the
/// verifier's structural check but HotSpot rejects the linkage with
/// `IncompatibleClassChangeError` at first call.
#[test]
fn invokestatic_interface_method_ref_round_trip() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/IfStatic").expect("this");
let object = pool.add_class("java/lang/Object").expect("object");
let name = pool.add_utf8("main").expect("name");
let desc = pool.add_utf8("([Ljava/lang/String;)V").expect("desc");
let code_name = pool.add_utf8("Code").expect("code name");
let list_class = pool.add_class("java/util/List").expect("list");
let of = pool
.add_interface_method_ref(
list_class,
"of",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/List;",
)
.expect("interface ref");
let code = vec![
Rt::Aload_0,
Rt::Aload_0,
Rt::Invokestatic(of),
Rt::Pop,
Rt::Return,
];
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC | ClassAccessFlags::SUPER,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::STATIC,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::Code {
name_index: code_name,
max_stack: 2,
max_locals: 1,
code,
exception_table: vec![],
attributes: vec![],
}],
}],
attributes: vec![],
..RtClass::default()
};
let mut original = Vec::new();
rt.to_bytes(&mut original).expect("to_bytes");
let parsed = format::parse(&original).expect("parse");
let method = &parsed.methods[0];
let invoke = method
.code
.as_ref()
.expect("code")
.insns
.iter()
.find_map(|i| match i {
Insn::Invoke {
kind, owner, itf, ..
} => Some((*kind, owner.clone(), *itf)),
_ => None,
})
.expect("invokestatic");
assert!(invoke.2, "parse must keep the interface flag");
let written = format::write(&parsed).expect("write");
let reparsed = format::parse(&written).expect("re-parse");
let method = &reparsed.methods[0];
let invoke = method
.code
.as_ref()
.expect("code")
.insns
.iter()
.find_map(|i| match i {
Insn::Invoke {
kind, owner, itf, ..
} => Some((*kind, owner.clone(), *itf)),
_ => None,
})
.expect("invokestatic");
assert_eq!(
invoke,
(
noxis_classfile::InvokeKind::Static,
"java/util/List".to_string(),
true
),
"InterfaceMethodref must survive write"
);
}

View file

@ -1,259 +0,0 @@
//! Type annotations and `AnnotationDefault` must be modeled, not passed
//! through as raw bytes: the writer rebuilds the pool, so stale indices
//! point at the wrong utf8 or past the pool end. ASM dies on those with
//! `ArrayIndexOutOfBoundsException` (Paper's plugin converter on real jars).
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::format;
use ristretto_classfile::attributes::{
AnnotationElement as RtElem, AnnotationValuePair as RtPair, Attribute as RtAttr,
Instruction as Rt, TargetType as RtTarget, TypeAnnotation as RtTypeAnno,
};
use ristretto_classfile::{
ClassAccessFlags, ClassFile as RtClass, ConstantPool, JAVA_21, Method as RtMethod,
MethodAccessFlags,
};
/// Method-level `RuntimeVisibleTypeAnnotations` (target `0x14`, method
/// return type): after the write rebuilds the pool, `type_index` and the
/// element references must resolve to the same strings as before.
#[test]
fn method_type_annotation_index_is_rebuilt() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/TA").expect("this");
let object = pool.add_class("java/lang/Object").expect("object");
let name = pool.add_utf8("run").expect("name");
let desc = pool.add_utf8("()Ljava/lang/Object;").expect("desc");
let attr = pool
.add_utf8("RuntimeVisibleTypeAnnotations")
.expect("attr");
let type_desc = pool.add_utf8("Ldemo/Use;").expect("type");
let value_name = pool.add_utf8("value").expect("value");
let enum_desc = pool.add_utf8("Ldemo/Kind;").expect("enum desc");
let enum_const = pool.add_utf8("A").expect("enum const");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC | ClassAccessFlags::SUPER,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::ABSTRACT,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::RuntimeVisibleTypeAnnotations {
name_index: attr,
type_annotations: vec![RtTypeAnno {
target_type: RtTarget::Empty { target_type: 0x14 },
type_path: vec![],
type_index: type_desc,
elements: vec![RtPair {
name_index: value_name,
value: RtElem::Enum {
type_name_index: enum_desc,
const_name_index: enum_const,
},
}],
}],
}],
}],
attributes: vec![],
..RtClass::default()
};
let written = rewritten(&rt);
let back = RtClass::from_bytes(&written).expect("reparse");
let anno = back.methods[0]
.attributes
.iter()
.find_map(|a| match a {
RtAttr::RuntimeVisibleTypeAnnotations {
type_annotations, ..
} => type_annotations.first(),
_ => None,
})
.expect("type annotation modeled, not Raw");
let resolved = back
.constant_pool
.try_get_utf8(anno.type_index)
.expect("type_index valid")
.to_string();
assert_eq!(resolved, "Ldemo/Use;");
let pair = anno.elements.first().expect("one element pair");
let pair_name = back
.constant_pool
.try_get_utf8(pair.name_index)
.expect("element name valid")
.to_string();
assert_eq!(pair_name, "value");
let RtElem::Enum {
type_name_index,
const_name_index,
} = &pair.value
else {
panic!("enum element stays an enum");
};
assert_eq!(
back.constant_pool
.try_get_utf8(*type_name_index)
.expect("enum type valid")
.to_string(),
"Ldemo/Kind;"
);
assert_eq!(
back.constant_pool
.try_get_utf8(*const_name_index)
.expect("enum const valid")
.to_string(),
"A"
);
}
/// Code-level `RuntimeInvisibleTypeAnnotations` (cast type argument,
/// target `0x48`): the attribute lives inside `Code`, same rebuild rule.
#[test]
fn code_type_annotation_index_is_rebuilt() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/CTA").expect("this");
let object = pool.add_class("java/lang/Object").expect("object");
let name = pool.add_utf8("run").expect("name");
let desc = pool.add_utf8("()V").expect("desc");
let code_name = pool.add_utf8("Code").expect("code");
let attr = pool
.add_utf8("RuntimeInvisibleTypeAnnotations")
.expect("attr");
let type_desc = pool.add_utf8("Llocal/Use;").expect("type");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC | ClassAccessFlags::SUPER,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::STATIC,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::Code {
name_index: code_name,
max_stack: 1,
max_locals: 0,
code: vec![Rt::Aconst_null, Rt::Pop, Rt::Return],
exception_table: vec![],
attributes: vec![RtAttr::RuntimeInvisibleTypeAnnotations {
name_index: attr,
type_annotations: vec![RtTypeAnno {
target_type: RtTarget::TypeArgument {
target_type: 0x48,
offset: 0,
type_argument_index: 0,
},
type_path: vec![],
type_index: type_desc,
elements: vec![],
}],
}],
}],
}],
attributes: vec![],
..RtClass::default()
};
let written = rewritten(&rt);
let back = RtClass::from_bytes(&written).expect("reparse");
let code = back.methods[0]
.attributes
.iter()
.find_map(|a| match a {
RtAttr::Code { attributes, .. } => Some(attributes),
_ => None,
})
.expect("code");
let anno = code
.iter()
.find_map(|a| match a {
RtAttr::RuntimeInvisibleTypeAnnotations {
type_annotations, ..
} => type_annotations.first(),
_ => None,
})
.expect("type annotation modeled, not Raw");
let resolved = back
.constant_pool
.try_get_utf8(anno.type_index)
.expect("type_index valid")
.to_string();
assert_eq!(resolved, "Llocal/Use;");
}
/// `AnnotationDefault` holds one `element_value` with pool references -
/// same stale-index hazard as the annotations themselves.
#[test]
fn annotation_default_index_is_rebuilt() {
let mut pool = ConstantPool::default();
let this = pool.add_class("demo/Def").expect("this");
let object = pool.add_class("java/lang/Object").expect("object");
let name = pool.add_utf8("value").expect("name");
let desc = pool.add_utf8("()Ljava/lang/String;").expect("desc");
let attr = pool.add_utf8("AnnotationDefault").expect("attr");
let value = pool.add_utf8("x").expect("value");
let rt = RtClass {
version: JAVA_21,
constant_pool: pool,
access_flags: ClassAccessFlags::PUBLIC
| ClassAccessFlags::INTERFACE
| ClassAccessFlags::ABSTRACT,
this_class: this,
super_class: object,
interfaces: vec![],
fields: vec![],
methods: vec![RtMethod {
access_flags: MethodAccessFlags::PUBLIC | MethodAccessFlags::ABSTRACT,
name_index: name,
descriptor_index: desc,
attributes: vec![RtAttr::AnnotationDefault {
name_index: attr,
element: RtElem::String {
const_value_index: value,
},
}],
}],
attributes: vec![],
..RtClass::default()
};
let written = rewritten(&rt);
let back = RtClass::from_bytes(&written).expect("reparse");
let element = back.methods[0]
.attributes
.iter()
.find_map(|a| match a {
RtAttr::AnnotationDefault { element, .. } => Some(element),
_ => None,
})
.expect("AnnotationDefault modeled, not Raw");
let RtElem::String { const_value_index } = element else {
panic!("default stays a string element");
};
let resolved = back
.constant_pool
.try_get_utf8(*const_value_index)
.expect("const_value_index valid")
.to_string();
assert_eq!(resolved, "x");
}
/// `parse → write` via our IR; the rewritten bytes for re-parsing.
fn rewritten(rt: &RtClass<'_>) -> Vec<u8> {
let mut original = Vec::new();
rt.to_bytes(&mut original).expect("to_bytes");
let ir = format::parse(&original).expect("parse");
format::write(&ir).expect("write")
}

View file

@ -1,8 +1,8 @@
//! Spike, часть 2: доступна ли **генерация** кадров `StackMapTable`.
//!
//! Ключевой вопрос `docs/stack.md` §3: считает ли `ristretto_classfile` кадры
//! сам и отдаёт ли их наружу. Если да - наша работа сводится к записи; если
//! нет - кадры придётся считать (или вендорить их `verifiers::bytecode`).
//! сам и отдаёт ли их наружу. Если да — наша работа сводится к записи; если
//! нет — кадры придётся считать (или вендорить их `verifiers::bytecode`).
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -82,7 +82,7 @@ fn inference_config() -> VerifierConfig {
VerifierConfig::default().with_fallback_strategy(FallbackStrategy::AlwaysInference)
}
/// Без `StackMapTable` inference обязан пройти сам - значит, движок кадров у
/// Без `StackMapTable` inference обязан пройти сам — значит, движок кадров у
/// крейта есть, просто его результат не отдаётся наружу.
#[test]
fn inference_path_verifies_without_stack_map_table() {
@ -94,7 +94,7 @@ fn inference_path_verifies_without_stack_map_table() {
assert_eq!(results[0].path_used, VerificationPath::Inference);
}
/// Строгий режим без кадров обязан упасть - иначе требование `StackMapTable`
/// Строгий режим без кадров обязан упасть — иначе требование `StackMapTable`
/// для классов ≥ 50 не проверяется вовсе.
#[test]
fn strict_mode_rejects_missing_stack_map_table() {
@ -102,7 +102,7 @@ fn strict_mode_rejects_missing_stack_map_table() {
let config = VerifierConfig::default().with_fallback_strategy(FallbackStrategy::Strict);
let outcome = verify_class(&class_file, &Permissive, &config);
// Строгий режим падает либо `Err`, либо `success == false` - оба варианта
// Строгий режим падает либо `Err`, либо `success == false` — оба варианта
// приемлемы, важен сам отказ.
let rejected = match &outcome {
Err(_) => true,
@ -113,13 +113,13 @@ fn strict_mode_rejects_missing_stack_map_table() {
/// Негативный результат spike'а: кадр не на том сдвиге не отдаёт диагностику.
///
/// Ждали `Ok(vec![result])` с заполненным `diagnostic.expected` - тогда
/// Ждали `Ok(vec![result])` с заполненным `diagnostic.expected` — тогда
/// генерация кадров шла бы итеративным путём через публичный API. Фактически
/// `verify_class` в строгом режиме возвращает `Err(VerifyError)`, и ожидаемый
/// кадр до нас не доходит: из крейта достаётся только место ошибки
/// («merge point at offset N»), но не её содержимое.
///
/// Вывод для `docs/stack.md` §3: проверять кадры крейт умеет, отдавать - нет.
/// Вывод для `docs/stack.md` §3: проверять кадры крейт умеет, отдавать — нет.
#[test]
fn diagnostic_exposes_expected_frame_on_failure() {
let mut class_file = branch_class();
@ -127,7 +127,7 @@ fn diagnostic_exposes_expected_frame_on_failure() {
.constant_pool
.add_utf8("StackMapTable")
.expect("utf8");
// Кадр на сдвиге 0, а настоящий якорь - на сдвиге 3.
// Кадр на сдвиге 0, а настоящий якорь — на сдвиге 3.
class_file.attributes.push(Attribute::StackMapTable {
name_index,
frames: vec![StackFrame::SameFrame { frame_type: 0 }],

View file

@ -1,6 +1,6 @@
//! Spike: пригоден ли `ristretto_classfile` как backend для чтения/записи.
//!
//! Критерии - `docs/stack.md` §2. Тест существует, чтобы ответы на вопросы
//! Критерии — `docs/stack.md` §2. Тест существует, чтобы ответы на вопросы
//! spike'а не устаревали: если крейт сломает хотя бы один пункт, сборка упадёт,
//! и решение о backend'е придётся пересмотреть.
//!
@ -59,7 +59,7 @@ fn round_trip_preserves_identity() {
assert_eq!(restored.constant_pool.len(), source.constant_pool.len());
}
/// Кадры `StackMapTable` конструируются и сериализуются публичным API -
/// Кадры `StackMapTable` конструируются и сериализуются публичным API —
/// значит, мы можем **записывать** кадры, а не только читать.
#[test]
fn stack_map_frames_are_constructible() {

View file

@ -61,7 +61,7 @@ pub enum Profile {
Standard,
/// Всё включено, включая агрессивный control-flow.
Paranoid,
/// Ничего не включено явно - только `enable` из конфига.
/// Ничего не включено явно — только `enable` из конфига.
Manual,
}
@ -97,7 +97,7 @@ impl Profile {
#[serde(default, deny_unknown_fields)]
pub struct Config {
pub profile: Profile,
/// Мастер-сид; `None` - случайный, но обязательно попадает в отчёт.
/// Мастер-сид; `None` — случайный, но обязательно попадает в отчёт.
pub seed: Option<u64>,
/// Принудительно включить пассы вне профиля.
pub enable: Vec<PassId>,

View file

@ -1,50 +1,49 @@
//! Config sections: name styles and per-pass settings.
//! Секции конфигурации: стили имён и настройки отдельных пассов.
use serde::{Deserialize, Serialize};
/// Name generation style.
/// Стиль генерации имён.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NameStyle {
/// `a`, `b`, ... `aa` - short Latin.
/// `a`, `b`, ... `aa` — короткие латинские.
ShortLatin,
/// `I`, `l`, `O`, `0` - visually identical.
/// `I`, `l`, `O`, `0` — визуально одинаковые.
IlO0,
/// Random Unicode names (surrogates are valid in modified UTF-8).
/// Случайные unicode-имена (суррогаты допустимы в modified UTF-8).
Unicode,
/// Medium-length mixed-case Latin.
/// Смешанная латиница средней длины.
#[default]
MixedLatin,
/// Pseudo-meaningful words from another project (misdirection).
/// Псевдосмысленные слова из другого проекта (дезориентация).
DecoyWords,
/// Plausible names: `TextureCache`, `resolveToken` - blends in as
/// ordinary application code instead of obvious noise.
/// Правдоподобные имена: `TextureCache`, `resolveToken` — вместо
/// явного мусора маскируется под обычный прикладной код.
Plausible,
}
/// Rename pass settings.
/// Настройки переименования.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RenameConfig {
/// Scatter packages into random paths.
/// Переименовывать пакеты в случайные пути.
pub spread_packages: bool,
/// Size of the random package pool.
/// Размер пула случайных пакетов.
pub package_pool: usize,
/// Name style for classes.
/// Стиль имён классов.
pub class_style: NameStyle,
/// Name style for fields and methods.
/// Стиль имён полей и методов.
pub member_style: NameStyle,
/// Name style for local variables and parameters.
/// Стиль имён локальных переменных и параметров.
pub local_style: NameStyle,
/// Widen members to `public` (so moving to a new package doesn't break
/// inheritance).
/// Делать члены `public` (чтобы не ломать inheritance между пакетами).
pub widen_access: bool,
/// Rename enum constants.
/// Переименовывать enum-константы.
pub rename_enum_constants: bool,
/// Rename local variables and parameters.
/// Переименовывать локальные переменные и параметры.
pub rename_locals: bool,
/// Also rename non-private members (aggressive: safe for applications,
/// dangerous for libraries and reflection-heavy code).
/// Переименовывать и не-private члены (агрессивно: безопасно для приложений,
/// опасно для библиотек и кода с рефлексией).
pub rename_public_members: bool,
}
@ -64,20 +63,19 @@ impl Default for RenameConfig {
}
}
/// String encryption settings.
/// Настройки шифрования строк.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StringsConfig {
/// Cipher schemes strings are rotated across.
/// Схемы шифра, между которыми перемешиваются строки.
pub schemes: Vec<String>,
/// Strings shorter than this are not encrypted.
/// Строки короче этого не шифруются.
pub min_len: usize,
/// Split long strings into chunks (looks less like a string pool).
/// Дробить длинные строки на чанки (меньше похоже на пул).
pub split_above: usize,
/// Don't encrypt strings matching these patterns.
/// Не шифровать строки, совпадающие с этими паттернами.
pub skip: Vec<String>,
/// Derive the key from KDF(class, method, index) instead of placing it
/// next to the ciphertext.
/// Вычислять ключ из KDF(class, method, index), а не класть рядом с текстом.
pub derive_key: bool,
}
@ -93,15 +91,15 @@ impl Default for StringsConfig {
}
}
/// Control-flow obfuscation settings.
/// Настройки обфускации контрольного потока.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FlowConfig {
/// Schemes picked randomly per method.
/// Схемы, между которыми выбирается случайно по методу.
pub schemes: Vec<String>,
/// Don't touch methods larger than this many instructions (size budget).
/// Не трогать методы больше этого числа инструкций (бюджет размера).
pub max_insns: usize,
/// Weave opaque predicates into block bodies.
/// Вплетать opaque-предикаты в тела блоков.
pub encrypt_block_bodies: bool,
}
@ -120,15 +118,15 @@ impl Default for FlowConfig {
}
}
/// Constant encryption settings.
/// Настройки шифрования констант.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConstantsConfig {
/// Splitting schemes (`xor`, `add`, `shift`), picked by RNG per constant.
/// Схемы разбиения (`xor`, `add`, `shift`), выбор по RNG на константу.
pub schemes: Vec<String>,
/// Insert opaque predicates (at most this many per method).
/// Вставлять opaque-предикаты (не больше этого на метод).
pub max_predicates: usize,
/// Don't touch constants in these classes (internal-name prefixes).
/// Не трогать константы в этих классах (префиксы внутренних имён).
pub skip: Vec<String>,
}
@ -142,19 +140,15 @@ impl Default for ConstantsConfig {
}
}
/// Noise pass settings.
/// Настройки шума.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NoiseConfig {
/// How many junk classes per real one (0 = disabled).
/// Сколько junk-классов на каждый настоящий (0 = выключено).
pub junk_ratio: usize,
/// Branching helper methods per junk class (their results feed a
/// static field so the bodies read as live code, not dead weight).
pub junk_methods_per_class: usize,
/// Number of junk annotations per class.
/// Число junk-аннотаций на класс.
pub junk_annotations: usize,
/// Weave junk classes into the reachability graph (required for them to
/// make sense).
/// Вплетать junk-классы в граф достижимости (обязательно для осмысленности).
pub weave_reachable: bool,
}
@ -162,29 +156,23 @@ impl Default for NoiseConfig {
fn default() -> Self {
Self {
junk_ratio: 0,
junk_methods_per_class: 3,
junk_annotations: 0,
weave_reachable: true,
}
}
}
/// Debug info pass settings.
/// Настройки отладочной информации.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DebugConfig {
/// Strip `LineNumberTable`.
/// Удалять `LineNumberTable`.
pub strip_line_numbers: bool,
/// Replace line numbers with plausible-but-wrong ones. Applies only
/// when `strip_line_numbers` is off (stripping wins).
pub fake_line_numbers: bool,
/// Strip `LocalVariableTable`.
/// Удалять `LocalVariableTable`.
pub strip_local_variables: bool,
/// Replace `SourceFile` with a fake name.
/// Подменять `SourceFile` на ложное имя.
pub spoof_source_file: bool,
/// Remove `SourceFile` entirely instead of spoofing it.
pub strip_source_file: bool,
/// Strip `Signature`/`InnerClasses`/`EnclosingMethod`.
/// Удалять `Signature`/`InnerClasses`/`EnclosingMethod`.
pub strip_signatures: bool,
}
@ -192,10 +180,8 @@ impl Default for DebugConfig {
fn default() -> Self {
Self {
strip_line_numbers: true,
fake_line_numbers: false,
strip_local_variables: true,
spoof_source_file: true,
strip_source_file: false,
strip_signatures: false,
}
}

View file

@ -3,7 +3,7 @@
//! Ядро обфускатора: конфигурация, детерминированный seed, маппинги,
//! контекст прогона и контракт пассов ([`pipeline::Pass`]).
//!
//! Ядро ничего не знает о бинарном формате `.class` и о ZIP - только о модели
//! Ядро ничего не знает о бинарном формате `.class` и о ZIP — только о модели
//! [`noxis_classfile::Program`]. Сборка конвейера из пассов живёт в
//! `noxis-passes`, чтобы не было цикла зависимостей.

View file

@ -17,7 +17,7 @@ pub fn field_key(owner: &str, name: &str, descriptor: &str) -> String {
/// Таблицы «оригинал → обфусцированное».
///
/// Нужна по двум причинам: (1) перевод stack trace'ей обратно в читаемые имена
/// (аналог ZKM Stack Trace Translate), (2) аудит - что именно поменялось.
/// (аналог ZKM Stack Trace Translate), (2) аудит — что именно поменялось.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Mapping {
/// internal name класса → новый internal name

View file

@ -31,7 +31,7 @@ impl Context {
/// Детерминированный RNG для домена (`"rename"`, `"strings/0"`, ...).
///
/// Доменное разделение: разные пассы не должны вытягивать одну
/// последовательность - иначе их «случайности» статистически коррелируют.
/// последовательность — иначе их «случайности» статистически коррелируют.
pub fn rng(&self, domain: &str) -> Rng {
Rng::from_seed(derive_seed(self.master_seed, domain, 0))
}

View file

@ -46,7 +46,7 @@ pub trait Pass: Send + Sync {
/// Упорядоченная цепочка пассов.
///
/// Порядок - не деталь: см. `docs/architecture.md` (rename → resources →
/// Порядок — не деталь: см. `docs/architecture.md` (rename → resources →
/// strings → constants → flow → noise → debug), иначе часть техник ломает
/// предыдущие или работает по уже мёртвым именам.
#[derive(Default)]
@ -88,7 +88,7 @@ impl Pipeline {
for pass in &self.passes {
let id = pass.id();
if !ctx.config.is_enabled(id) {
tracing::info!(target: "noxis", pass = %id, "пасс выключен - пропущен");
tracing::info!(target: "noxis", pass = %id, "пасс выключен — пропущен");
continue;
}
tracing::info!(target: "noxis", pass = %id, "пасс запущен");

View file

@ -1,8 +1,8 @@
//! Итог прогона: пассы + счётчики - сериализуется в JSON.
//! Итог прогона: пассы + счётчики — сериализуется в JSON.
use serde::Serialize;
/// Итог прогона: пассы + счётчики - сериализуется в JSON.
/// Итог прогона: пассы + счётчики — сериализуется в JSON.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Report {
pub seed: u64,

View file

@ -1,7 +1,7 @@
//! Детерминированный PRNG и вывод производных seed'ов.
//!
//! Свой генератор, а не `rand`: обфускация должна быть **воспроизводимой между
//! версиями инструмента** - алгоритм замирает в формате, а не в изменении API
//! версиями инструмента** — алгоритм замирает в формате, а не в изменении API
//! чужого крейта. Схема: SplitMix64 для инициализации + xoshiro256++ для генерации.
/// Генератор xoshiro256++.
@ -72,7 +72,7 @@ impl Rng {
}
}
/// Перемешать срез на месте (Fisher-Yates).
/// Перемешать срез на месте (Fisher–Yates).
pub fn shuffle<T>(&mut self, items: &mut [T]) {
for i in (1..items.len()).rev() {
let j = self.below((i + 1) as u64) as usize;
@ -97,7 +97,7 @@ impl Rng {
}
}
/// FNV-1a 64 - детерминированный вывод производного сида.
/// FNV-1a 64 — детерминированный вывод производного сида.
///
/// Разделение доменов обязательно: пассы не должны делить одну и ту же
/// последовательность (иначе переименование и шифрование «случайно»

View file

@ -1,6 +1,6 @@
//! Чтение и запись ZIP-архива JAR.
//!
//! Единственная задача модуля - переместить записи из/в вектор [`Entry`],
//! Единственная задача модуля — переместить записи из/в вектор [`Entry`],
//! сохранив порядок и не потеряв дубликатов молча. Всё, что связано с
//! содержимым (`Program`, маппинги, подпись), живёт в соседних модулях.
@ -30,7 +30,7 @@ pub enum JarError {
/// Одна запись архива: имя + байты.
///
/// Порядок в `[`Entry`]` - это порядок в архиве, он сохраняется при
/// Порядок в `[`Entry`]` — это порядок в архиве, он сохраняется при
/// чтении и записи. Метод сжатия не хранится: всё пишется deflate'ом,
/// что детерминированно и одинаково для одинаковых данных.
#[derive(Debug, Clone, PartialEq, Eq)]
@ -51,7 +51,7 @@ impl Entry {
/// Читает все не-каталожные записи из `reader`, сохраняя порядок.
///
/// Повторяющееся имя - ошибка, а не тихое предупреждение: битый архив
/// Повторяющееся имя — ошибка, а не тихое предупреждение: битый архив
/// с двумя `META-INF/MANIFEST.MF` собрать дороже, чем отказать.
pub fn read_entries<R: Read + Seek>(reader: R) -> Result<Vec<Entry>, JarError> {
let mut archive = zip::ZipArchive::new(reader)?;

View file

@ -4,13 +4,13 @@
//!
//! Слой разделён на три несвязанные задачи:
//!
//! * [`archive`] - чистая работа с ZIP: порядок записей, сжатие, дубликаты;
//! * [`signatures`] - срез невалидных подписей `META-INF/*.SF|RSA|DSA|EC`;
//! * [`loader`] - перевод архива в [`Program`](noxis_classfile::Program)
//! * [`archive`] — чистая работа с ZIP: порядок записей, сжатие, дубликаты;
//! * [`signatures`] — срез невалидных подписей `META-INF/*.SF|RSA|DSA|EC`;
//! * [`loader`] — перевод архива в [`Program`](noxis_classfile::Program)
//! и обратно (классы через [`format`](noxis_classfile::format), остальное
//! как ресурсы).
//!
//! Обфускация ресурсов - пасс `resources` в `noxis-passes`; сюда она не
//! Обфускация ресурсов — пасс `resources` в `noxis-passes`; сюда она не
//! входит, потому что ей нужен маппинг имён, а не I/O.
pub mod archive;

View file

@ -1,11 +1,9 @@
//! Archive to [`Program`] and back.
//! Перевод архива в [`Program`] и обратно.
//!
//! The rule is simple: `*.class` goes to the parser, everything else -
//! to resources. Classes serialize first, then resources: the order inside
//! the archive does not affect behaviour, and a fixed order gives
//! reproducible writes.
use std::collections::BTreeSet;
//! Правило простое: `*.class` уходит в парсер, всё остальное — в ресурсы.
//! Обратно классы сериализуются первыми, затем ресурсы: порядок внутри
//! архива на поведение не влияет, а фиксированный порядок даёт
//! воспроизводимую запись.
use noxis_classfile::Program;
use noxis_classfile::format;
@ -13,22 +11,13 @@ use noxis_classfile::model::Resource;
use crate::archive::{Entry, JarError};
/// Parses archive entries: classes - through the parser, the rest - as resources.
///
/// A name that repeats (multi-release jars carry the same class at the root
/// and under `META-INF/versions/*`) is kept once, first occurrence wins:
/// the flat model cannot hold two classes under one name, and later passes
/// (rename maps, jar writing) assume uniqueness.
/// Разбирает записи архива: классы — через парсер, остальное — как ресурсы.
pub fn load(entries: Vec<Entry>) -> Result<Program, JarError> {
let mut program = Program::default();
let mut seen: BTreeSet<String> = BTreeSet::new();
for entry in entries {
if is_class_entry(&entry.name) && !is_module_info(&entry.name) {
let class = format::parse(&entry.data)?;
if seen.insert(class.this_class.clone()) {
program.classes.push(class);
}
if is_class_entry(&entry.name) {
program.classes.push(format::parse(&entry.data)?);
} else {
program.resources.push(Resource {
path: entry.name,
@ -40,19 +29,13 @@ pub fn load(entries: Vec<Entry>) -> Result<Program, JarError> {
Ok(program)
}
/// Assembles archive entries from [`Program`]: classes first, then resources.
/// Собирает записи архива из [`Program`]: сначала классы, потом ресурсы.
pub fn save(program: &Program) -> Result<Vec<Entry>, JarError> {
let mut entries = Vec::with_capacity(program.classes.len() + program.resources.len());
for class in &program.classes {
let name = format!("{}.class", class.this_class);
let bytes = format::write(class).map_err(|error| {
JarError::Classfile(noxis_classfile::ClassfileError::Write(format!(
"{}: {error}",
class.this_class
)))
})?;
entries.push(Entry::new(name, bytes));
entries.push(Entry::new(name, format::write(class)?));
}
for resource in &program.resources {
entries.push(Entry::new(resource.path.clone(), resource.data.clone()));
@ -61,19 +44,11 @@ pub fn save(program: &Program) -> Result<Vec<Entry>, JarError> {
Ok(entries)
}
/// A class file inside the archive: the path ends in `.class`.
/// Классовый файл внутри архива: путь оканчивается на `.class`.
fn is_class_entry(name: &str) -> bool {
name.len() > ".class".len() && name.ends_with(".class")
}
/// A JPMS descriptor. No class loader ever loads it; parsing would rebuild
/// its pool and leave the unmodeled `Module` attribute with stale indices
/// (ASM then dies in `readModule`), so it travels as a raw resource with
/// its bytes intact.
fn is_module_info(name: &str) -> bool {
name.ends_with("module-info.class")
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -103,7 +78,7 @@ mod tests {
assert_eq!(save(&program).expect("save"), source);
}
/// Class entries go through the parser (round-trip keeps them intact).
/// До P1 `format::parse` — заглушка; после P1 ожидается успешный разбор.
#[test]
fn class_entries_go_through_the_parser() {
let entries = vec![
@ -122,41 +97,4 @@ mod tests {
Err(other) => panic!("unexpected error: {other}"),
}
}
/// Multi-release twins (`demo/App.class` + `META-INF/versions/9/...`):
/// the flat model keeps the first occurrence so no two classes ever
/// share one name downstream.
#[test]
fn duplicate_class_names_keep_first() {
use noxis_classfile::ClassBuilder;
let class = ClassBuilder::new("demo/App", None).build();
let bytes = format::write(&class).expect("write");
let entries = vec![
Entry::new("demo/App.class", bytes.clone()),
Entry::new("META-INF/versions/9/demo/App.class", bytes),
];
let program = load(entries).expect("load");
assert_eq!(program.classes.len(), 1);
assert_eq!(program.classes[0].this_class, "demo/App");
}
/// JPMS descriptors are never class-loaded: they pass through as raw
/// resources (parsing would rebuild their pool and stale the `Module`
/// attribute, which stays unmodeled).
#[test]
fn module_info_passes_through_as_resource() {
let entries = vec![
Entry::new("META-INF/versions/9/module-info.class", vec![0xCA, 0xFE]),
Entry::new("notes.txt", b"hi".to_vec()),
];
let program = load(entries).expect("load");
assert!(program.classes.is_empty());
assert_eq!(program.resources.len(), 2);
assert_eq!(
program.resources[0].path,
"META-INF/versions/9/module-info.class"
);
}
}

View file

@ -2,7 +2,7 @@
//!
//! После перепаковки архива `META-INF/*.SF` и `*.RSA|DSA|EC` описывают
//! **старые** байты: JVM либо отказывается запускать jar, либо ругается на
//! подпись. Вырезать их обязательно - и это делается на уровне записей,
//! подпись. Вырезать их обязательно — и это делается на уровне записей,
//! потому что `MANIFEST.MF` остаётся, а его секции `Name:` тоже нужно
//! выкинуть (ими занимается пасс `resources`).
@ -19,10 +19,10 @@ const META_INF: &str = "META-INF/";
/// Проверяет, является ли запись архива файлом подписи.
///
/// Совпадение - только для файлов, лежащих **непосредственно** в
/// `META-INF/`: вложенный `META-INF/certs/x.SF` - обычный ресурс.
/// Совпадение — только для файлов, лежащих **непосредственно** в
/// `META-INF/`: вложенный `META-INF/certs/x.SF` — обычный ресурс.
///
/// Регистр не важен (`meta-inf/x.sf` - тоже подпись), `MANIFEST.MF`
/// Регистр не важен (`meta-inf/x.sf` — тоже подпись), `MANIFEST.MF`
/// никогда не является подписью.
pub fn is_signature_entry(name: &str) -> bool {
let Some(relative) = name.strip_prefix(META_INF) else {

View file

@ -11,7 +11,6 @@ noxis-analysis = { workspace = true }
noxis-classfile = { workspace = true }
noxis-core = { workspace = true }
noxis-runtime = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }

View file

@ -1,13 +1,14 @@
//! Constant-splitting schemes and opaque predicates.
//! Схемы разбиения констант и opaque-предикаты.
//!
//! Integer constants outside the `iconst` range are replaced by triples
//! (`x^k`, `a+b`, shift); an opaque predicate is an always-true condition with
//! a one-`nop` dead branch (valid, never executed, breaks linear disassembly).
//! Целые константы вне `iconst`-диапазона заменяются тройками (`x^k`,
//! `a+b`, сдвиг); opaque-предикат — всегда истинное условие с мёртвой
//! ветвью из одного `nop` (валидно, не исполняется, ломает линейный
//! дисассемблирование).
use noxis_classfile::{Arith, BranchCond, Cond, Const, Insn, Prim};
use noxis_core::Rng;
/// Splitting scheme (names from `ConstantsConfig::schemes`).
/// Схема разбиения (имена из `ConstantsConfig::schemes`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Scheme {
Xor,
@ -26,7 +27,7 @@ impl Scheme {
}
}
/// Split an `int` constant into a triple that computes it.
/// Разбить `int`-константу на вычисляющую её тройку.
pub(super) fn encrypt_int(value: i32, scheme: Scheme, rng: &mut Rng) -> Vec<Insn> {
let (first, second) = match scheme {
Scheme::Xor => {
@ -49,7 +50,7 @@ pub(super) fn encrypt_int(value: i32, scheme: Scheme, rng: &mut Rng) -> Vec<Insn
}
}
/// Split a `long` constant (the same three schemes on `l*` opcodes).
/// Разбить `long`-константу (те же три схемы на `l*`-опкодах).
pub(super) fn encrypt_long(value: i64, scheme: Scheme, rng: &mut Rng) -> Vec<Insn> {
let (first, second) = match scheme {
Scheme::Xor => {
@ -72,7 +73,7 @@ pub(super) fn encrypt_long(value: i64, scheme: Scheme, rng: &mut Rng) -> Vec<Ins
}
}
/// `(a, b, op)` as three instructions.
/// `(a, b, op)` как три инструкции.
fn binary(first: i32, second: i32, op: Arith, prim: Prim) -> Vec<Insn> {
vec![
Insn::Const(Const::Int(first)),
@ -92,7 +93,7 @@ fn binary_long(first: i64, second: i64, op: Arith) -> Vec<Insn> {
]
}
/// `v = ((v >> 1) << 1) | (v & 1)` - works for any value, including negatives.
/// `v = ((v >> 1) << 1) | (v & 1)` — работает для любых, включая отрицательные.
fn shift_form(value: i32) -> Vec<Insn> {
vec![
Insn::Const(Const::Int(value >> 1)),
@ -109,7 +110,7 @@ fn shift_form(value: i32) -> Vec<Insn> {
]
}
/// The same for `long` (the shift amount is always an `int`!).
/// То же для `long` (величина сдвига — всегда `int`!).
fn shift_form_long(value: i64) -> Vec<Insn> {
vec![
Insn::Const(Const::Long(value >> 1)),
@ -126,18 +127,13 @@ fn shift_form_long(value: i64) -> Vec<Insn> {
]
}
/// Opaque predicate `(C*C + C) & 1 == 0` (true for any `C`).
/// Opaque-предикат `(C*C + C) & 1 == 0` (истина для любого `C`):
/// `[pred, ifne DEAD, goto MERGE, DEAD: nop, MERGE:]`, дальше — оригинал.
///
/// Stack-neutral and leaves control flow unchanged: the computed value is
/// consumed by a branch that never fires; the dead `DEAD: nop` branch only
/// bloats linear disassembly.
///
/// Pattern: `[pred..., ifne DEAD, goto MERGE, DEAD: nop, MERGE:]`.
/// Labels come from the calling code (free method numbers).
/// Метки выдаёт вызывающий код (свободные номера метода).
pub(super) fn opaque_true(dead: u32, merge: u32, rng: &mut Rng) -> Vec<Insn> {
let constant = rng.next_u64() as i32;
vec![
// P = ((C*C) + C) & 1 - even, so always 0.
Insn::Const(Const::Int(constant)),
Insn::Dup,
Insn::Binary {
@ -154,7 +150,6 @@ pub(super) fn opaque_true(dead: u32, merge: u32, rng: &mut Rng) -> Vec<Insn> {
prim: Prim::Int,
op: Arith::And,
},
// P != 0 never holds - the branch into DEAD is not taken, value popped.
Insn::Branch(BranchCond::Zero(Cond::Ne), dead),
Insn::Goto(merge),
Insn::Mark(dead),

View file

@ -1,21 +1,21 @@
//! The constants pass: numbers become arithmetic, plus opaque predicates.
//! Пасс шифрования констант: числа → арифметика, плюс opaque-предикаты.
//!
//! `float`/`double` are left alone (bit-exact paths through integers are
//! separate). Trivia from the `iconst` range (`-1..=5`, `0L/1L`) stays as is:
//! encrypting it only bloats hot code.
//! `float`/`double` не трогаются (битовая точность через целые — отдельно).
//! Мелочь из `iconst`-диапазона (`-1..=5`, `0L/1L`) остаётся как есть:
//! её шифрование только раздувает горячий код.
mod forms;
#[cfg(test)]
mod tests;
use noxis_analysis::{ClassHierarchy, JdkHierarchy};
use noxis_classfile::{Const, Insn, MAX_METHOD_INSNS, Program, compute_frames};
use noxis_analysis::ClassHierarchy;
use noxis_classfile::{Const, Insn, Program, compute_frames};
use noxis_core::{Context, CoreError, Pass, PassId, PassReport};
use forms::{Scheme, encrypt_int, encrypt_long, opaque_true};
/// The constants encryption pass.
/// Пасс шифрования констант.
#[derive(Debug, Default, Clone, Copy)]
pub struct ConstantsPass;
@ -30,18 +30,17 @@ impl Pass for ConstantsPass {
for name in &cfg.schemes {
schemes.push(
Scheme::parse(name)
.ok_or_else(|| pass_error(format!("unknown scheme `{name}`")))?,
.ok_or_else(|| pass_error(format!("неизвестная схема `{name}`")))?,
);
}
if schemes.is_empty() {
return Err(pass_error("no encryption schemes"));
return Err(pass_error("нет схем шифрования"));
}
let mut rng = ctx.rng("constants");
let mut replaced = 0usize;
let mut predicates = 0usize;
let mut skipped = 0usize;
let mut mutated: Vec<(usize, usize)> = Vec::new();
let mut oversized: Vec<(usize, usize)> = Vec::new();
for (ci, class) in program.classes.iter_mut().enumerate() {
if cfg
@ -56,34 +55,25 @@ impl Pass for ConstantsPass {
let Some(code) = method.code.as_mut() else {
continue;
};
let original = std::mem::take(&mut code.insns);
let mut fresh = Vec::with_capacity(original.len());
let mut fresh = Vec::with_capacity(code.insns.len());
let mut touched = false;
for insn in &original {
for insn in code.insns.drain(..) {
match insn {
Insn::Const(Const::Int(value)) if !is_tiny_int(*value) => {
Insn::Const(Const::Int(value)) if !is_tiny_int(value) => {
let scheme = schemes[rng.below(schemes.len() as u64) as usize];
fresh.extend(encrypt_int(*value, scheme, &mut rng));
fresh.extend(encrypt_int(value, scheme, &mut rng));
replaced += 1;
touched = true;
}
Insn::Const(Const::Long(value)) if *value != 0 && *value != 1 => {
Insn::Const(Const::Long(value)) if value != 0 && value != 1 => {
let scheme = schemes[rng.below(schemes.len() as u64) as usize];
fresh.extend(encrypt_long(*value, scheme, &mut rng));
fresh.extend(encrypt_long(value, scheme, &mut rng));
replaced += 1;
touched = true;
}
other => fresh.push(other.clone()),
other => fresh.push(other),
}
}
if fresh.len() > MAX_METHOD_INSNS {
// Would risk the 64KB writer ceiling: keep the original
// code untouched (predicates included) and count a skip.
code.insns = original;
skipped += 1;
oversized.push((ci, mi));
continue;
}
code.insns = fresh;
if touched {
code.max_stack = code.max_stack.saturating_add(2);
@ -94,31 +84,27 @@ impl Pass for ConstantsPass {
insert_predicates(
program,
&mut mutated,
&oversized,
cfg.max_predicates,
&mut rng,
&mut predicates,
)?;
let hierarchy = ClassHierarchy::build(program);
let frames = JdkHierarchy::wrap(&hierarchy);
for (ci, mi) in &mutated {
refresh_frames(program, *ci, *mi, &frames)?;
refresh_frames(program, *ci, *mi, &hierarchy)?;
}
Ok(report(replaced, predicates, skipped))
}
}
/// Trivia that is not worth encrypting (already `iconst`).
/// Мелочь, которую шифровать невыгодно (уже `iconst`).
fn is_tiny_int(value: i32) -> bool {
(-1..=5).contains(&value)
}
/// Opaque predicates at the top of methods with code (at most the limit).
/// Oversized methods stay fully untouched, predicates included.
/// Opaque-предикаты в начало методов с кодом (не больше лимита на метод).
fn insert_predicates(
program: &mut Program,
mutated: &mut Vec<(usize, usize)>,
oversized: &[(usize, usize)],
max_predicates: usize,
rng: &mut noxis_core::Rng,
predicates: &mut usize,
@ -130,9 +116,6 @@ fn insert_predicates(
for ci in 0..classes {
let methods = program.classes[ci].methods.len();
for mi in 0..methods {
if oversized.contains(&(ci, mi)) {
continue;
}
let empty_or_missing = program.classes[ci].methods[mi]
.code
.as_ref()
@ -140,7 +123,7 @@ fn insert_predicates(
if empty_or_missing {
continue;
}
let missing = || pass_error("method vanished while inserting a predicate");
let missing = || pass_error("метод пропал при вставке предиката");
let mut top = program.classes[ci]
.methods
.get(mi)
@ -183,25 +166,25 @@ fn insert_predicates(
Ok(())
}
/// Recompute the frames of a touched method.
/// Пересчитать фреймы затронутого метода.
fn refresh_frames(
program: &mut Program,
ci: usize,
mi: usize,
hierarchy: &JdkHierarchy<'_>,
hierarchy: &ClassHierarchy,
) -> Result<(), CoreError> {
let (name, snapshot) = {
let class = program
.classes
.get(ci)
.ok_or_else(|| pass_error("class vanished"))?;
.ok_or_else(|| pass_error("класс пропал"))?;
(
class.this_class.clone(),
class
.methods
.get(mi)
.cloned()
.ok_or_else(|| pass_error("method vanished"))?,
.ok_or_else(|| pass_error("метод пропал"))?,
)
};
let frames =
@ -211,7 +194,7 @@ fn refresh_frames(
.get_mut(ci)
.and_then(|c| c.methods.get_mut(mi))
.and_then(|m| m.code.as_mut())
.ok_or_else(|| pass_error("method vanished"))?
.ok_or_else(|| pass_error("метод пропал"))?
.frames = frames;
Ok(())
}
@ -222,7 +205,7 @@ fn report(replaced: usize, predicates: usize, skipped: usize) -> PassReport {
transformed: replaced + predicates,
skipped,
notes: vec![format!(
"constants split: {replaced}, predicates: {predicates}"
"констант разбито: {replaced}, предикатов: {predicates}"
)],
}
}

View file

@ -1,14 +1,14 @@
//! Constant-pass tests: forms compute the source value, trivia survives.
//! Тесты пасса констант: формы вычисляют исходник, мелочь цела.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{ClassBuilder, Code, Const, Insn, MAX_METHOD_INSNS, Prim, Program, Version};
use noxis_classfile::{ClassBuilder, Code, Const, Insn, Prim, Program, Version};
use noxis_core::{Config, Context, Pass};
use super::ConstantsPass;
use super::forms::{Scheme, encrypt_int, encrypt_long};
/// Forms round-trip arithmetically (an interpreter for triples/quintuples).
/// Формы обратимы арифметически (интерпретатор троек/пятёрок).
fn eval_int(insns: &[Insn]) -> i32 {
match insns {
[
@ -20,7 +20,7 @@ fn eval_int(insns: &[Insn]) -> i32 {
match op {
Xor => a ^ b,
Add => a.wrapping_add(*b),
_ => panic!("not a triple: {insns:?}"),
_ => panic!("не та тройка: {insns:?}"),
}
}
[
@ -30,7 +30,7 @@ fn eval_int(insns: &[Insn]) -> i32 {
Insn::Const(Const::Int(b)),
Insn::Binary { .. },
] => (a << 1) | (b & 1),
_ => panic!("not a form: {insns:?}"),
_ => panic!("не форма: {insns:?}"),
}
}
@ -84,7 +84,7 @@ fn sample() -> Program {
}
}
/// The pass: big constants are split, trivia and structure survive.
/// Пасс: большие константы разбиты, мелочь и структура целы.
#[test]
fn constants_split_and_predicated() {
let mut program = sample();
@ -96,54 +96,16 @@ fn constants_split_and_predicated() {
.apply(&mut ctx, &mut program)
.expect("constants");
let code = program.classes[0].methods[0].code.as_ref().expect("code");
let code = program.classes[0].methods[0].code.as_ref().expect("код");
let has = |v: i32| code.insns.contains(&Insn::Const(Const::Int(v)));
assert!(!has(100), "source constant survived");
assert!(has(3), "trivia touched");
assert!(!has(100), "исходная константа уцелела");
assert!(has(3), "мелочь тронута");
assert!(
!code.insns.contains(&Insn::Const(Const::Long(10))),
"long survived"
"long уцелел"
);
// Opaque predicate: a dead branch made of `nop`.
assert!(code.insns.contains(&Insn::Nop), "no predicate");
assert!(report.transformed >= 3, "few transforms: {report:?}");
// Opaque-предикат: мёртвая ветвь из `nop`.
assert!(code.insns.contains(&Insn::Nop), "нет предиката");
assert!(report.transformed >= 3, "мало трансформаций: {report:?}");
assert_eq!(report.skipped, 0);
}
/// A method that would blow past the 64KB ceiling stays byte-identical.
#[test]
fn oversized_methods_are_skipped() {
let code = Code {
max_stack: 2,
max_locals: 0,
insns: vec![Insn::Const(Const::Int(1_000_000)); MAX_METHOD_INSNS + 1],
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
};
let mut program = Program {
classes: vec![
ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(0x0009, "run", "()V", code)
.build(),
],
resources: Vec::new(),
};
let mut ctx = Context::new(Config {
seed: Some(9),
..Config::default()
});
let report = ConstantsPass
.apply(&mut ctx, &mut program)
.expect("constants");
let code = program.classes[0].methods[0].code.as_ref().expect("code");
assert!(
code.insns
.iter()
.all(|i| matches!(i, Insn::Const(Const::Int(1_000_000)))),
"oversized method was rewritten"
);
assert_eq!(report.skipped, 1);
}

View file

@ -1,28 +1,26 @@
//! The debug-info pass: removal and false replacement.
//! Пасс отладочной информации: удаление и ложная подмена.
//!
//! Requirements come from `info/evo-weaknesses.md` §3: the dissected sample
//! kept original `SourceFile`s on 160 classes, 10 218 `LineNumberTable`s and
//! local variable names. This is the cheapest thing to fix and the most
//! expensive to give away.
//! Источник требований — `info/evo-weaknesses.md` §3: у разобранного
//! образца оригинальные `SourceFile` у 160 классов, 10 218 `LineNumberTable`
//! и имена локальных переменных. Это дешевле всего чинить и дороже всего
//! отдавать.
//!
//! Removal alone is not enough. Tools (JADX/CFR) trust debug info more than
//! bytecode, so `spoof_source_file` substitutes a **false** name -
//! consistent, but unrelated to the real sources. `fake_line_numbers` does
//! the same to line numbers (a plausible walk instead of the truth), and
//! `strip_source_file` drops the attribute entirely.
//! Важно: удалять недостаточно. Инструменты (JADX/CFR) верят отладке сильнее,
//! чем байткоду, поэтому `spoof_source_file` подставляет **ложное** имя —
//! консистентное, но не связанное с реальным исходником.
use noxis_classfile::{Attribute, ClassFile, Code, Method, Program};
use noxis_core::{Context, CoreError, DebugConfig, Pass, PassId, PassReport, Rng};
use noxis_core::{Context, CoreError, DebugConfig, Pass, PassId, PassReport};
use crate::namegen::NameGenerator;
/// A class/method-level attribute dropped as "raw".
/// Атрибут уровня класса/метода, который мы выкидываем как «сырой».
const ENCLOSING_METHOD: &str = "EnclosingMethod";
/// A method-level attribute holding parameter names (`-parameters`).
/// Атрибут уровня метода с именами параметров (`-parameters`).
const METHOD_PARAMETERS: &str = "MethodParameters";
/// The debug-info pass.
/// Пасс отладочной информации.
#[derive(Debug, Default, Clone, Copy)]
pub struct DebugInfoPass;
@ -36,14 +34,11 @@ impl Pass for DebugInfoPass {
let style = ctx.config.rename.class_style;
let mut source_names =
NameGenerator::new(ctx.rng("debug/source_file"), style).for_classes();
let mut line_rng = ctx.rng("debug/lines");
let mut stripped = 0usize;
let mut spoofed = 0usize;
let mut faked = 0usize;
for class in &mut program.classes {
stripped += strip_source_file(class, &cfg);
spoofed += spoof_source_file(class, &mut source_names, &cfg);
stripped += strip_signatures(&mut class.attributes, &cfg);
@ -52,7 +47,6 @@ impl Pass for DebugInfoPass {
stripped += strip_parameters(method, &cfg);
if let Some(code) = method.code.as_mut() {
stripped += strip_code(code, &cfg);
faked += fake_line_numbers(code, &mut line_rng, &cfg);
}
}
@ -63,32 +57,29 @@ impl Pass for DebugInfoPass {
let mut notes = Vec::new();
if stripped > 0 {
notes.push(format!("attributes removed: {stripped}"));
notes.push(format!("удалено атрибутов: {stripped}"));
}
if spoofed > 0 {
notes.push(format!("SourceFile spoofed: {spoofed}"));
}
if faked > 0 {
notes.push(format!("line numbers faked: {faked}"));
notes.push(format!("подменено SourceFile: {spoofed}"));
}
Ok(PassReport {
pass: PassId::DebugInfo,
transformed: stripped + spoofed + faked,
transformed: stripped + spoofed,
skipped: 0,
notes,
})
}
}
/// Keep only the attributes for which `keep` returns true.
/// Оставляет только атрибуты, для которых `keep` вернул `true`.
fn retain(attrs: &mut Vec<Attribute>, keep: impl FnMut(&Attribute) -> bool) -> usize {
let before = attrs.len();
attrs.retain(keep);
before - attrs.len()
}
/// Method bodies: `LineNumberTable`, `LocalVariableTable`.
/// Тела методов: `LineNumberTable`, `LocalVariableTable`.
fn strip_code(code: &mut Code, cfg: &DebugConfig) -> usize {
retain(&mut code.attributes, |attr| match attr {
Attribute::LineNumberTable(_) => !cfg.strip_line_numbers,
@ -99,7 +90,7 @@ fn strip_code(code: &mut Code, cfg: &DebugConfig) -> usize {
})
}
/// Class/method/field level: `Signature`, `InnerClasses`, `EnclosingMethod`.
/// Уровень класса/метода/поля: `Signature`, `InnerClasses`, `EnclosingMethod`.
fn strip_signatures(attrs: &mut Vec<Attribute>, cfg: &DebugConfig) -> usize {
if !cfg.strip_signatures {
return 0;
@ -112,7 +103,7 @@ fn strip_signatures(attrs: &mut Vec<Attribute>, cfg: &DebugConfig) -> usize {
})
}
/// Method parameter names (`MethodParameters`).
/// Имена параметров метода (`MethodParameters`).
fn strip_parameters(method: &mut Method, cfg: &DebugConfig) -> usize {
if !cfg.strip_local_variables {
return 0;
@ -124,40 +115,7 @@ fn strip_parameters(method: &mut Method, cfg: &DebugConfig) -> usize {
})
}
/// Replace `LineNumberTable` rows with plausible-but-wrong numbers.
///
/// Runs only when stripping is off (a removed table has nothing to fake):
/// a deterministic upward walk, so stack traces still look like traces
/// instead of pointing at the real lines.
fn fake_line_numbers(code: &mut Code, rng: &mut Rng, cfg: &DebugConfig) -> usize {
if !cfg.fake_line_numbers || cfg.strip_line_numbers {
return 0;
}
let mut faked = 0usize;
let mut line = 1 + rng.below(200) as u16;
for attr in &mut code.attributes {
if let Attribute::LineNumberTable(rows) = attr {
for row in rows.iter_mut() {
row.line = line;
line = line.saturating_add(1 + rng.below(8) as u16);
faked += 1;
}
}
}
faked
}
/// Remove `SourceFile` entirely instead of spoofing it.
fn strip_source_file(class: &mut ClassFile, cfg: &DebugConfig) -> usize {
if !cfg.strip_source_file {
return 0;
}
retain(&mut class.attributes, |attr| {
!matches!(attr, Attribute::SourceFile(_))
})
}
/// Replace `SourceFile` with a false but plausible name.
/// Подменяет `SourceFile` ложным, но правдоподобным именем.
fn spoof_source_file(class: &mut ClassFile, names: &mut NameGenerator, cfg: &DebugConfig) -> usize {
if !cfg.spoof_source_file {
return 0;
@ -171,3 +129,118 @@ fn spoof_source_file(class: &mut ClassFile, names: &mut NameGenerator, cfg: &Deb
}
replaced
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{ClassBuilder, Insn, LineNumber, LocalVariable, Resource, Version};
use noxis_core::{Config, Context, RenameConfig};
use super::*;
fn sample() -> Program {
let code = Code {
max_stack: 0,
max_locals: 1,
insns: vec![Insn::Return(None)],
exception_table: Vec::new(),
frames: Vec::new(),
attributes: vec![
Attribute::LineNumberTable(vec![LineNumber { start: 0, line: 12 }]),
Attribute::LocalVariableTable(vec![LocalVariable {
start: 0,
end: 0,
name: "this".into(),
descriptor: "Ldemo/App;".into(),
index: 0,
}]),
],
};
let mut class = ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(0x0001, "run", "()V", code)
.attribute(Attribute::SourceFile("RealApp.java".into()))
.attribute(Attribute::Signature("Ljava/lang/Object;".into()))
.attribute(Attribute::InnerClasses(Vec::new()))
.build();
class.methods[0].attributes.push(Attribute::Raw {
name: METHOD_PARAMETERS.into(),
data: vec![],
});
Program {
classes: vec![class],
resources: vec![Resource {
path: "app.json".into(),
data: br#"{}"#.to_vec(),
}],
}
}
fn run(program: &mut Program, debug: DebugConfig) -> PassReport {
let config = Config {
seed: Some(7),
debug,
rename: RenameConfig {
class_style: noxis_core::NameStyle::ShortLatin,
..RenameConfig::default()
},
..Config::default()
};
let mut ctx = Context::new(config);
DebugInfoPass.apply(&mut ctx, program).expect("debug pass")
}
#[test]
fn default_config_strips_and_spoofs() {
let mut program = sample();
let report = run(&mut program, DebugConfig::default());
let class = &program.classes[0];
let code = class.methods[0].code.as_ref().expect("code");
assert!(code.attributes.is_empty(), "атрибуты кода должны уйти");
assert!(
class.methods[0].attributes.is_empty(),
"MethodParameters уходит"
);
match class.attributes[0] {
Attribute::SourceFile(ref name) => assert_ne!(name, "RealApp.java"),
_ => panic!("SourceFile должен быть первым"),
}
assert_eq!(class.attributes.len(), 3, "Signature/InnerClasses остаются");
assert!(report.transformed > 0);
}
#[test]
fn signatures_and_parameters_survive_when_disabled() {
let debug = DebugConfig {
strip_line_numbers: false,
strip_local_variables: false,
spoof_source_file: false,
strip_signatures: false,
};
let mut program = sample();
run(&mut program, debug);
let class = &program.classes[0];
assert_eq!(class.methods[0].code.as_ref().unwrap().attributes.len(), 2);
assert_eq!(class.methods[0].attributes.len(), 1);
assert_eq!(class.attributes.len(), 3);
assert_eq!(
class.attributes[0],
Attribute::SourceFile("RealApp.java".into())
);
}
#[test]
fn same_seed_gives_the_same_spoofed_name() {
let mut first = sample();
let mut second = sample();
run(&mut first, DebugConfig::default());
run(&mut second, DebugConfig::default());
assert_eq!(first.classes[0].attributes, second.classes[0].attributes);
}
}

View file

@ -1,96 +0,0 @@
//! Entry dispatchers: opaque `switch` prologues and opaque guards.
//!
//! Every emitter here is stack-neutral as a whole: whatever the prologue
//! pushes it also consumes before falling through to `body`. That is what
//! makes prepending safe at method entry (empty stack) without any dataflow
//! analysis - all joins at `body` carry an empty stack, so any computed
//! `StackMapTable` stays consistent.
use noxis_classfile::{Arith, BranchCond, Cond, Const, Insn, Prim, SlotKind};
use noxis_core::Rng;
/// Dense `tableswitch` dispatcher (`state-spread`).
///
/// The opaque key is computed as `a + b` (two constants, never the key
/// itself) and dispatched over `[key-2, key+2]`; only the middle slot reaches
/// `body`, the rest fall into a dead block that jumps back to `body`.
/// Does not emit `Mark(body)` - the caller places it.
pub(super) fn table_dispatch(body: u32, dead: u32, rng: &mut Rng) -> Vec<Insn> {
let key = 100 + (rng.next_u64() % 10_000) as i32;
let half = (rng.next_u64() as i32) & 0x3FFF_FFFF;
let low = key - 2;
vec![
Insn::Const(Const::Int(half)),
Insn::Const(Const::Int(key.wrapping_sub(half))),
Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
},
Insn::TableSwitch {
default: dead,
low,
high: key + 2,
targets: vec![dead, dead, body, dead, dead],
},
Insn::Mark(dead),
Insn::Nop,
Insn::Goto(body),
]
}
/// Sparse `lookupswitch` dispatcher over a counter local (`computed-switch`).
///
/// The counter lives in `slot` (a fresh local owned by the caller): the shape
/// differs from `table_dispatch` on purpose - a sparse switch over a variable
/// instead of a dense range over a stack value. Junk keys never equal `key`.
/// Does not emit `Mark(body)` - the caller places it.
pub(super) fn lookup_dispatch(body: u32, dead: u32, slot: u16, rng: &mut Rng) -> Vec<Insn> {
let key = 100 + (rng.next_u64() % 10_000) as i32;
let mut keys = vec![key];
while keys.len() < 4 {
let candidate = (rng.next_u64() % 20_000) as i32 - 5_000;
if !keys.contains(&candidate) {
keys.push(candidate);
}
}
let mut pairs: Vec<(i32, u32)> = keys
.into_iter()
.map(|k| (k, if k == key { body } else { dead }))
.collect();
// The JVM requires lookupswitch pairs sorted by key.
pairs.sort_by_key(|(k, _)| *k);
vec![
Insn::Const(Const::Int(key)),
Insn::Store {
slot,
kind: SlotKind::Int,
},
Insn::Load {
slot,
kind: SlotKind::Int,
},
Insn::LookupSwitch {
default: dead,
pairs,
},
Insn::Mark(dead),
Insn::Nop,
Insn::Goto(body),
]
}
/// Always-true opaque guard `(C*C + C) & 1 == 0` with a dead `nop` branch.
///
/// Stack-neutral: the computed value is consumed by the branch that never
/// fires. Ends with `Mark(merge)` - execution continues there.
/// Same construction as the constants pass uses; the predicate core is shared
/// with the flow splices (`rewire::opaque_compute`).
pub(super) fn opaque_guard(dead: u32, merge: u32, rng: &mut Rng) -> Vec<Insn> {
let mut guard = super::rewire::opaque_compute(rng);
guard.push(Insn::Branch(BranchCond::Zero(Cond::Ne), dead));
guard.push(Insn::Goto(merge));
guard.push(Insn::Mark(dead));
guard.push(Insn::Nop);
guard.push(Insn::Mark(merge));
guard
}

View file

@ -1,271 +0,0 @@
//! Control-flow obfuscation: dispatcher prologues plus CFG rewiring.
//!
//! One scheme per method (rotation), picked from `FlowConfig::schemes`:
//! - `state-spread`: dense `tableswitch` entry dispatcher;
//! - `computed-switch`: sparse `lookupswitch` over a counter local;
//! - `butterfly`: every branch inverted, stream cut with `goto` splices;
//! - `exception-goto`: dispatcher inside `try`, dead catch-all rejoins body.
//!
//! Every scheme also cuts the stream with a few `goto` splices (intra-method
//! mixing) and recomputes `StackMapTable` afterwards, so the only thing a
//! scheme may assume is an empty stack at method entry - joins stay consistent
//! by construction (see `dispatch`/`rewire` for why each shape is safe).
mod dispatch;
mod rewire;
#[cfg(test)]
mod tests;
use dispatch::{lookup_dispatch, opaque_guard, table_dispatch};
use noxis_analysis::{ClassHierarchy, JdkHierarchy};
use noxis_classfile::{Code, Insn, Label, Program, compute_frames};
use noxis_core::{Context, CoreError, Pass, PassId, PassReport, Rng};
use rewire::{dead_catch, invert_branches, split_blocks};
/// Control-flow obfuscation pass.
#[derive(Debug, Default, Clone, Copy)]
pub struct FlowPass;
/// Dispatcher scheme (names from `FlowConfig::schemes`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scheme {
StateSpread,
ComputedSwitch,
Butterfly,
ExceptionGoto,
}
impl Scheme {
fn parse(name: &str) -> Option<Self> {
match name {
"state-spread" => Some(Scheme::StateSpread),
"computed-switch" => Some(Scheme::ComputedSwitch),
"butterfly" => Some(Scheme::Butterfly),
"exception-goto" => Some(Scheme::ExceptionGoto),
_ => None,
}
}
}
/// Fresh-label allocator over one method body.
pub(crate) struct LabelGen {
next: Label,
}
impl LabelGen {
fn of(code: &Code) -> Self {
let top = code.labels().into_iter().max().unwrap_or(0);
Self {
next: top.saturating_add(1),
}
}
fn next(&mut self) -> Label {
let label = self.next;
self.next = self.next.saturating_add(1);
label
}
}
impl Pass for FlowPass {
fn id(&self) -> PassId {
PassId::Flow
}
fn apply(&self, ctx: &mut Context, program: &mut Program) -> Result<PassReport, CoreError> {
let cfg = ctx.config.flow.clone();
let mut schemes = Vec::with_capacity(cfg.schemes.len());
for name in &cfg.schemes {
schemes.push(
Scheme::parse(name)
.ok_or_else(|| pass_error(format!("unknown scheme `{name}`")))?,
);
}
if schemes.is_empty() {
return Err(pass_error("no control-flow schemes configured"));
}
let mut rng = ctx.rng("flow");
let mut mutated: Vec<(usize, usize)> = Vec::new();
let mut per_scheme = [0usize; 4];
let mut skipped = 0usize;
for (ci, class) in program.classes.iter_mut().enumerate() {
for (mi, method) in class.methods.iter_mut().enumerate() {
let Some(code) = method.code.as_mut() else {
continue;
};
if skippable(&method.name, code, cfg.max_insns) {
skipped += 1;
continue;
}
let scheme = schemes[rng.below(schemes.len() as u64) as usize];
apply_scheme(code, scheme, &cfg, &mut rng);
per_scheme[scheme_index(scheme)] += 1;
mutated.push((ci, mi));
}
}
let hierarchy = ClassHierarchy::build(program);
let frames = JdkHierarchy::wrap(&hierarchy);
for (ci, mi) in &mutated {
refresh_frames(program, *ci, *mi, &frames)?;
}
Ok(report(&per_scheme, mutated.len(), skipped))
}
}
/// Whether a method body is left alone.
fn skippable(name: &str, code: &Code, max_insns: usize) -> bool {
// The super-call-first shape of a constructor must survive: no prologue
// may run before it.
if name == "<init>" {
return true;
}
// Frames are never computed for subroutines - keep them byte-identical.
if code
.insns
.iter()
.any(|insn| matches!(insn, Insn::Jsr(_) | Insn::Ret(_)))
{
return true;
}
let real = code
.insns
.iter()
.filter(|insn| !matches!(insn, Insn::Mark(_)))
.count();
if real < 3 {
return true;
}
if code.insns.len() > max_insns {
return true;
}
false
}
/// Rebuild one method body with the given scheme; prologue stays first.
fn apply_scheme(code: &mut Code, scheme: Scheme, cfg: &noxis_core::FlowConfig, rng: &mut Rng) {
let mut labels = LabelGen::of(code);
let body = labels.next();
let dead = labels.next();
if scheme == Scheme::Butterfly {
invert_branches(&mut code.insns, &mut labels, rng, 100);
}
let real = code
.insns
.iter()
.filter(|insn| !matches!(insn, Insn::Mark(_)))
.count();
let mut prologue = Vec::new();
if cfg.encrypt_block_bodies {
let guard_dead = labels.next();
let guard_merge = labels.next();
prologue.extend(opaque_guard(guard_dead, guard_merge, rng));
}
match scheme {
Scheme::StateSpread => {
prologue.extend(table_dispatch(body, dead, rng));
prologue.push(Insn::Mark(body));
}
Scheme::ComputedSwitch if code.max_locals == u16::MAX => {
// No free local slot - fall back to the stack-based dispatcher.
prologue.extend(table_dispatch(body, dead, rng));
prologue.push(Insn::Mark(body));
}
Scheme::ComputedSwitch => {
let slot = code.max_locals;
prologue.extend(lookup_dispatch(body, dead, slot, rng));
prologue.push(Insn::Mark(body));
code.max_locals = code.max_locals.saturating_add(1);
}
Scheme::Butterfly => {
prologue.push(Insn::Mark(body));
}
Scheme::ExceptionGoto => {
let try_start = labels.next();
let handler = labels.next();
let mut guarded = vec![Insn::Mark(try_start)];
guarded.append(&mut prologue);
guarded.extend(table_dispatch(body, dead, rng));
// No skip-goto after the dead block: the dispatcher's dead
// `Goto(body)` already jumps over the handler. A second goto
// would sit after a terminal with no frame of its own, and
// HotSpot requires a frame at every block start - even an
// unreachable one. try_e IS the dead mark for the same reason.
let (mut handler_code, entry) = dead_catch(try_start, dead, handler, body);
guarded.append(&mut handler_code);
guarded.push(Insn::Mark(body));
prologue = guarded;
code.exception_table.push(entry);
}
}
// A `nop` pads the body mark: the original stream may start with its own
// mark (even a handler entry), and two marks on one offset would merge
// frames from inconsistent states.
prologue.push(Insn::Nop);
let cuts = (real / 16).clamp(1, 8);
let start = prologue.len();
let mut insns = prologue;
insns.append(&mut code.insns);
split_blocks(&mut insns, &mut labels, rng, start, cuts);
code.insns = insns;
code.max_stack = code.max_stack.saturating_add(2);
}
fn scheme_index(scheme: Scheme) -> usize {
match scheme {
Scheme::StateSpread => 0,
Scheme::ComputedSwitch => 1,
Scheme::Butterfly => 2,
Scheme::ExceptionGoto => 3,
}
}
/// Recompute the frames of a touched method.
fn refresh_frames(
program: &mut Program,
ci: usize,
mi: usize,
hierarchy: &JdkHierarchy<'_>,
) -> Result<(), CoreError> {
let (name, snapshot) = {
let class = program
.classes
.get(ci)
.ok_or_else(|| pass_error("class vanished mid-pass"))?;
(
class.this_class.clone(),
class
.methods
.get(mi)
.cloned()
.ok_or_else(|| pass_error("method vanished mid-pass"))?,
)
};
let frames =
compute_frames(&name, &snapshot, hierarchy).map_err(|e| pass_error(e.to_string()))?;
program
.classes
.get_mut(ci)
.and_then(|c| c.methods.get_mut(mi))
.and_then(|m| m.code.as_mut())
.ok_or_else(|| pass_error("method vanished mid-pass"))?
.frames = frames;
Ok(())
}
fn report(per_scheme: &[usize; 4], mutated: usize, skipped: usize) -> PassReport {
PassReport {
pass: PassId::Flow,
transformed: mutated,
skipped,
notes: vec![format!(
"methods rebuilt: {mutated} (state-spread: {}, computed-switch: {}, butterfly: {}, exception-goto: {})",
per_scheme[0], per_scheme[1], per_scheme[2], per_scheme[3]
)],
}
}
fn pass_error(msg: impl Into<String>) -> CoreError {
CoreError::pass(PassId::Flow, msg)
}

View file

@ -1,230 +0,0 @@
//! CFG rewiring: branch inversion, block splitting, exception routing.
//!
//! All rewrites preserve semantics without dataflow analysis:
//! - inverting a branch negates its condition and swaps target/fallthrough;
//! - a `goto` + dead `nop` splice is stack-neutral at any cut point, because
//! both joins carry the same stack the original stream had;
//! - the dead catch-all rejoins `body` with an empty stack after popping the
//! exception, so it merges with the dispatcher's empty-stack edges.
use noxis_classfile::{BranchCond, Cond, ExceptionHandler, Insn};
use noxis_core::Rng;
/// Logical negation of a branch condition.
pub(super) fn negate(cond: BranchCond) -> BranchCond {
match cond {
BranchCond::Zero(c) => BranchCond::Zero(negate_cond(c)),
BranchCond::Int(c) => BranchCond::Int(negate_cond(c)),
BranchCond::Ref { eq } => BranchCond::Ref { eq: !eq },
BranchCond::Null { is_null } => BranchCond::Null { is_null: !is_null },
}
}
fn negate_cond(cond: Cond) -> Cond {
match cond {
Cond::Eq => Cond::Ne,
Cond::Ne => Cond::Eq,
Cond::Lt => Cond::Ge,
Cond::Le => Cond::Gt,
Cond::Gt => Cond::Le,
Cond::Ge => Cond::Lt,
}
}
/// Turn `if-cond T` into `if-not SKIP; goto T; SKIP:` (`butterfly`).
///
/// `rate` is a 0-100 percentage applied per branch. Semantics are unchanged:
/// the inverted branch skips a `goto` to the original target, so the taken /
/// not-taken destinations are exactly the old ones. A `nop` pads the fresh
/// mark: whatever follows (an original mark, even a handler entry with its
/// own stack) must not share a bytecode offset with it, or their frames
/// would merge from inconsistent states.
pub(super) fn invert_branches(
insns: &mut Vec<Insn>,
fresh: &mut crate::flow::LabelGen,
rng: &mut Rng,
rate: u64,
) {
let mut index = 0;
while index < insns.len() {
let (cond, target) = match &insns[index] {
Insn::Branch(cond, target) => (*cond, *target),
_ => {
index += 1;
continue;
}
};
if rng.below(100) >= rate {
index += 1;
continue;
}
let skip = fresh.next();
insns.splice(
index..=index,
[
Insn::Branch(negate(cond), skip),
Insn::Goto(target),
Insn::Mark(skip),
Insn::Nop,
],
);
index += 4;
}
}
/// Cut the stream with opaque-entered splices.
///
/// Each splice computes an always-false opaque predicate `(C*C + C) & 1 != 0`
/// and branches on it: the fallthrough continues the stream, the dead block
/// throws instead of rejoining. Throwing (rather than jumping back) keeps the
/// splice valid at *any* stack depth - `athrow` has no successor, so there is
/// nothing to merge - and the dead block still owns a frame through its entry
/// branch, which HotSpot requires even for code that never executes.
///
/// Cuts land at or after `start` (the entry prologue must stay first) and
/// only at reachable positions: a splice in an unreachable gap would leave
/// its `into` mark without a computed state, and the verifier rejects jump
/// targets without frames.
///
/// A cut is also pushed past a run of consecutive marks. Inserting *before* a
/// targeted mark would reroute its incoming branch edges over the splice,
/// orphaning the splice itself: the mark must keep its edges, so the splice
/// goes after it and inherits its reachability through fallthrough.
pub(super) fn split_blocks(
insns: &mut Vec<Insn>,
fresh: &mut crate::flow::LabelGen,
rng: &mut Rng,
start: usize,
count: usize,
) {
let live = reachable(insns);
let mut cuts = Vec::with_capacity(count);
for _ in 0..count {
let allowed: Vec<usize> = (start..insns.len())
.filter(|c| live.get(*c).copied().unwrap_or(false))
.collect();
if allowed.is_empty() {
break;
}
let mut cut = allowed[rng.below(allowed.len() as u64) as usize];
while cut < insns.len() && matches!(insns[cut], Insn::Mark(_)) {
cut += 1;
}
// A mark run at the very end leaves no stream to cut into.
if cut < insns.len() {
cuts.push(cut);
}
}
cuts.sort_unstable();
cuts.dedup();
for cut in cuts.into_iter().rev() {
let into = fresh.next();
let dead = fresh.next();
let mut splice = opaque_compute(rng);
splice.push(Insn::Branch(BranchCond::Zero(Cond::Ne), dead));
splice.push(Insn::Goto(into));
splice.push(Insn::Mark(dead));
splice.push(Insn::Nop);
splice.push(Insn::AconstNull);
splice.push(Insn::AThrow);
splice.push(Insn::Mark(into));
insns.splice(cut..cut, splice);
}
}
/// The opaque predicate core: computes `(C*C + C) & 1` (always 0) on top of
/// the stack without disturbing what is below it.
pub(super) fn opaque_compute(rng: &mut Rng) -> Vec<Insn> {
use noxis_classfile::{Arith, Const, Prim};
let constant = rng.next_u64() as i32;
vec![
Insn::Const(Const::Int(constant)),
Insn::Dup,
Insn::Binary {
prim: Prim::Int,
op: Arith::Mul,
},
Insn::Const(Const::Int(constant)),
Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
},
Insn::Const(Const::Int(1)),
Insn::Binary {
prim: Prim::Int,
op: Arith::And,
},
]
}
/// Vec positions reachable from method entry via fallthrough and branch
/// targets. Marks are transparent: control flows through them to the next
/// instruction. Deliberately exception-oblivious (handler-only code reads as
/// unreachable): cuts there are skipped rather than risked.
pub(super) fn reachable(insns: &[Insn]) -> Vec<bool> {
use std::collections::{BTreeMap, VecDeque};
let mut at_label: BTreeMap<u32, usize> = BTreeMap::new();
for (index, insn) in insns.iter().enumerate() {
if let Insn::Mark(label) = insn {
at_label.entry(*label).or_insert(index);
}
}
let resolve = |label: u32| at_label.get(&label).copied();
let terminal = |insn: &Insn| {
matches!(
insn,
Insn::Goto(_)
| Insn::Jsr(_)
| Insn::Ret(_)
| Insn::TableSwitch { .. }
| Insn::LookupSwitch { .. }
| Insn::Return(_)
| Insn::AReturn
| Insn::AThrow
)
};
let mut live = vec![false; insns.len()];
let mut queue = VecDeque::new();
if !live.is_empty() {
queue.push_back(0);
}
while let Some(index) = queue.pop_front() {
if live[index] {
continue;
}
live[index] = true;
let insn = &insns[index];
if !terminal(insn) && index + 1 < insns.len() {
queue.push_back(index + 1);
}
for target in insn.targets() {
if let Some(resolved) = resolve(target) {
queue.push_back(resolved);
}
}
}
live
}
/// Dead catch-all over `try_start..try_end`, rejoining `body`.
///
/// The covered prologue cannot throw (constants, switches, gotos), so the
/// handler never fires; if it ever did, popping the exception and jumping to
/// `body` behaves exactly like the fallthrough path.
pub(super) fn dead_catch(
try_start: u32,
try_end: u32,
handler: u32,
body: u32,
) -> (Vec<Insn>, ExceptionHandler) {
let code = vec![Insn::Mark(handler), Insn::Pop, Insn::Nop, Insn::Goto(body)];
let entry = ExceptionHandler {
start: try_start,
end: try_end,
handler,
catch_type: None,
};
(code, entry)
}

View file

@ -1,264 +0,0 @@
//! Unit tests for the control-flow pass: shapes, skips, determinism.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{
Arith, BranchCond, ClassBuilder, Code, Cond, Const, Insn, Prim, Program, SlotKind, Version,
};
use noxis_core::{Config, Context, FlowConfig, Pass, PassId};
use super::{FlowPass, LabelGen};
/// A small branchy method: `acc=0; for(i=0;i<10;i++) acc+=i; return acc`.
fn branchy_code() -> Code {
let (head, end) = (100, 101);
Code {
max_stack: 2,
max_locals: 2,
insns: vec![
Insn::Const(Const::Int(0)),
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(0)),
Insn::Store {
slot: 1,
kind: SlotKind::Int,
},
Insn::Mark(head),
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(10)),
Insn::Branch(BranchCond::Int(Cond::Ge), end),
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
},
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
Insn::Iinc { index: 1, delta: 1 },
Insn::Goto(head),
Insn::Mark(end),
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Return(Some(Prim::Int)),
],
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
}
}
fn program_with(methods: Vec<(String, String, Code)>) -> Program {
let mut builder = ClassBuilder::new("demo/Flow", Some("java/lang/Object"));
for (name, descriptor, code) in methods {
builder = builder.method_with_code(0x0009, name, descriptor, code);
}
Program {
classes: vec![builder.version(Version::JAVA_21).build()],
resources: Vec::new(),
}
}
fn run(program: &mut Program, schemes: &[&str]) -> noxis_core::PassReport {
let config = Config {
seed: Some(42),
flow: FlowConfig {
schemes: schemes.iter().map(|s| s.to_string()).collect(),
max_insns: 4000,
encrypt_block_bodies: false,
},
..Config::default()
};
let mut ctx = Context::new(config);
FlowPass.apply(&mut ctx, program).expect("flow pass")
}
fn code_of(program: &Program, name: &str) -> Code {
program.classes[0]
.method(name, "()I")
.expect("method")
.code
.clone()
.expect("code")
}
fn has_switch(insns: &[Insn]) -> bool {
insns
.iter()
.any(|i| matches!(i, Insn::TableSwitch { .. } | Insn::LookupSwitch { .. }))
}
#[test]
fn state_spread_emits_table_dispatch() {
let mut program = program_with(vec![(
"calc".to_string(),
"()I".to_string(),
branchy_code(),
)]);
let before = code_of(&program, "calc").insns.len();
let report = run(&mut program, &["state-spread"]);
let code = code_of(&program, "calc");
assert!(
code.insns
.iter()
.any(|i| matches!(i, Insn::TableSwitch { .. })),
"no tableswitch in {code:?}"
);
assert!(code.insns.len() > before, "stream did not grow");
assert!(!code.frames.is_empty(), "frames were not recomputed");
assert_eq!(report.pass, PassId::Flow);
assert_eq!(report.transformed, 1);
}
#[test]
fn computed_switch_uses_lookup_and_fresh_local() {
let mut program = program_with(vec![(
"calc".to_string(),
"()I".to_string(),
branchy_code(),
)]);
run(&mut program, &["computed-switch"]);
let code = code_of(&program, "calc");
let pairs = code.insns.iter().find_map(|i| match i {
Insn::LookupSwitch { pairs, .. } => Some(pairs.clone()),
_ => None,
});
let pairs = pairs.expect("no lookupswitch");
let mut sorted = pairs.clone();
sorted.sort_by_key(|(k, _)| *k);
assert_eq!(pairs, sorted, "lookupswitch pairs must be sorted");
assert_eq!(code.max_locals, 3, "counter local was not allocated");
}
#[test]
fn butterfly_inverts_without_switch() {
let mut program = program_with(vec![(
"calc".to_string(),
"()I".to_string(),
branchy_code(),
)]);
run(&mut program, &["butterfly"]);
let code = code_of(&program, "calc");
assert!(!has_switch(&code.insns), "butterfly must not dispatch");
let gotos = code
.insns
.iter()
.filter(|i| matches!(i, Insn::Goto(_)))
.count();
assert!(
gotos >= 3,
"expected inverted branches + splits, got {gotos}"
);
let labels = code.labels();
for insn in &code.insns {
for target in insn.targets() {
assert!(labels.contains(&target), "dangling label {target}");
}
}
// Every branch target must also be reachable: an orphaned splice leaves
// its marks without computed frames and HotSpot rejects the class.
let live = super::rewire::reachable(&code.insns);
let mut at_mark = std::collections::BTreeMap::new();
for (index, insn) in code.insns.iter().enumerate() {
if let Insn::Mark(label) = insn {
at_mark.entry(*label).or_insert(index);
}
}
for insn in &code.insns {
for target in insn.targets() {
let index = at_mark.get(&target).expect("resolved above");
assert!(live[*index], "unreachable branch target {target}");
}
}
}
#[test]
fn exception_goto_adds_catch_all() {
let mut program = program_with(vec![(
"calc".to_string(),
"()I".to_string(),
branchy_code(),
)]);
run(&mut program, &["exception-goto"]);
let code = code_of(&program, "calc");
assert_eq!(code.exception_table.len(), 1);
assert_eq!(code.exception_table[0].catch_type, None);
assert!(
code.insns
.iter()
.any(|i| matches!(i, Insn::TableSwitch { .. })),
"dispatcher missing inside try"
);
}
#[test]
fn skips_init_and_tiny_methods() {
let tiny = Code {
max_stack: 0,
max_locals: 0,
insns: vec![Insn::Return(None)],
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
};
let mut program = program_with(vec![
("<init>".to_string(), "()V".to_string(), tiny.clone()),
("run".to_string(), "()V".to_string(), tiny),
("calc".to_string(), "()I".to_string(), branchy_code()),
]);
let report = run(
&mut program,
&[
"state-spread",
"computed-switch",
"butterfly",
"exception-goto",
],
);
assert_eq!(report.transformed, 1);
assert_eq!(report.skipped, 2);
}
#[test]
fn unknown_scheme_is_rejected() {
let mut program = program_with(vec![(
"calc".to_string(),
"()I".to_string(),
branchy_code(),
)]);
let config = Config {
seed: Some(1),
flow: FlowConfig {
schemes: vec!["death-star".to_string()],
max_insns: 4000,
encrypt_block_bodies: false,
},
..Config::default()
};
let mut ctx = Context::new(config);
assert!(FlowPass.apply(&mut ctx, &mut program).is_err());
}
#[test]
fn labels_are_allocated_above_existing_ones() {
let code = branchy_code();
let top = code.labels().into_iter().max().unwrap_or(0);
let mut labels = LabelGen::of(&code);
assert!(labels.next() > top);
}

View file

@ -1,11 +1,10 @@
//! # noxis-passes
//!
//! Bytecode transformations. The pipeline assembly (`standard_pipeline`)
//! lives here as well: the core (`noxis-core`) only knows the [`Pass`] contract.
//! Трансформации байткода. Сборка конвейера из пассов (`standard_pipeline`)
//! живёт здесь же: ядро (`noxis-core`) знает только контракт [`Pass`].
pub mod constants;
pub mod debug;
pub mod flow;
pub mod namegen;
pub mod noise;
pub mod rename;
@ -16,22 +15,24 @@ use noxis_core::Pass;
pub use constants::ConstantsPass;
pub use debug::DebugInfoPass;
pub use flow::FlowPass;
pub use namegen::NameGenerator;
pub use noise::NoisePass;
pub use rename::RenamePass;
pub use resources::ResourcesPass;
pub use strings::StringsPass;
/// Standard pipeline in [`docs/architecture.md`](../../docs/architecture.md) order:
/// Стандартный конвейер в порядке [`docs/architecture.md`](../../docs/architecture.md):
/// `rename → resources → strings → constants → flow → noise → debug`.
///
/// Нереализованные пассы просто не добавлены — порядок уже соблюдён,
/// поэтому каждый следующий пасс вставляется на своё место, а не
/// дописывается в конец.
pub fn standard_pipeline() -> noxis_core::Pipeline {
noxis_core::Pipeline::new()
.push(Box::new(RenamePass) as Box<dyn Pass>)
.push(Box::new(ResourcesPass) as Box<dyn Pass>)
.push(Box::new(StringsPass) as Box<dyn Pass>)
.push(Box::new(ConstantsPass) as Box<dyn Pass>)
.push(Box::new(FlowPass) as Box<dyn Pass>)
.push(Box::new(NoisePass) as Box<dyn Pass>)
.push(Box::new(DebugInfoPass) as Box<dyn Pass>)
}
@ -69,7 +70,6 @@ mod tests {
fn standard_pipeline_runs_end_to_end_in_order() {
let mut ctx = Context::new(Config {
seed: Some(1),
enable: vec![PassId::Flow],
..Config::default()
});
let mut program = sample();
@ -86,7 +86,6 @@ mod tests {
PassId::Resources,
PassId::Strings,
PassId::Constants,
PassId::Flow,
PassId::Noise,
PassId::DebugInfo
]

View file

@ -1,9 +1,9 @@
//! Alphabets, keywords and forbidden names.
//! Алфавиты, ключевые слова и запрещённые имена.
//!
//! Kept in their own file because both the generator and the rename pass
//! reach into them (reserving keep-listed names before generation starts).
//! Списки вынесены отдельно: к ним обращаются и генератор, и пасс
//! переименования (резервирование keep-имён).
/// Hard Java keywords: a class/method name can never collide with these.
/// Жёсткие ключевые слова Java: имя класса/метода не может им совпадать.
pub(super) const KEYWORDS: &[&str] = &[
"abstract",
"assert",
@ -66,8 +66,8 @@ pub(super) const KEYWORDS: &[&str] = &[
"yield",
];
/// Names not worth overwriting: they'd hurt readability/logging and get
/// flagged by tooling before any deobfuscation even starts.
/// Имена, которые не стоит затирать: мешают читать/логировать и ловятся
/// инструментами до любой деобфускации.
pub(super) const AVOID_CLASS: &[&str] = &[
"Object",
"String",
@ -101,9 +101,9 @@ pub(super) const AVOID_MEMBER: &[&str] = &[
pub(super) const LATIN_LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
pub(super) const LATIN_UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// Visually indistinguishable characters: the core of the `IlO0` style.
/// Визуально неразличимые символы — ядро стиля `IlO0`.
pub(super) const CONFUSABLE: &[u8] = b"IlO01";
/// Unicode letters valid in a Java identifier (Cyrillic/Greek/CJK).
/// Unicode-буквы, валидные как Java-идентификаторы (Cyrillic/Greek/CJK).
pub(super) const UNICODE_LETTERS: &[char] = &[
'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'у', 'ф',
'х', 'ц', 'ч', 'ш', 'щ', 'э', 'ю', 'я', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'λ', 'μ', 'π',
@ -118,58 +118,15 @@ pub(super) const DECOY_RIGHT: &[&str] = &[
"ripple",
];
/// `Plausible` style word bank. Mixes domain-neutral software nouns with
/// terms that are boring, structural scaffolding in the client/mod
/// ecosystem noxis is actually used on (see
/// `/storage/project/jvm/LoVisual/ref/clients/*`: `Module`, `Setting`,
/// `Event`, `Mixin`, `Manager`, `Component`, `Accessor`, `Hud`, `Overlay`,
/// `Theme`, `Timer`, `Animation`, `Rotation` all show up dozens of times
/// across real client codebases). Deliberately excludes anything that
/// itself reads as a "feature flag" worth an analyst's attention (no
/// `Esp`/`Aimbot`/`KillAura`/`Chams`): a decoy name that announces
/// "interesting code lives here" defeats the point of blending in.
/// Стиль `Plausible`: домен-нейтральные существительные для классов/полей —
/// похожи на обычный прикладной код, не привязаны к конкретному проекту.
pub(super) const PLAUSIBLE_NOUN: &[&str] = &[
"Texture",
"Event",
"State",
"Render",
"Asset",
"Config",
"Session",
"Cache",
"Buffer",
"Socket",
"Stream",
"Widget",
"Layout",
"Theme",
"Profile",
"Metric",
"Token",
"Handle",
"Context",
"Registry",
"Request",
"Response",
"Payload",
"Resource",
"Snapshot",
"Pipeline",
"Queue",
"Slot",
"Frame",
"Entry",
"Module",
"Setting",
"Overlay",
"Hud",
"Component",
"Accessor",
"Timer",
"Animation",
"Rotation",
"Texture", "Event", "State", "Render", "Asset", "Config", "Session", "Cache", "Buffer",
"Socket", "Stream", "Widget", "Layout", "Theme", "Profile", "Metric", "Token", "Handle",
"Context", "Registry", "Request", "Response", "Payload", "Resource", "Snapshot", "Pipeline",
"Queue", "Slot", "Frame", "Entry",
];
/// Role suffixes for classes (`NounSuffix`, e.g. `TextureCache`).
/// Суффиксы ролей для классов (`NounSuffix`, напр. `TextureCache`).
pub(super) const PLAUSIBLE_SUFFIX: &[&str] = &[
"Manager",
"Handler",
@ -191,10 +148,8 @@ pub(super) const PLAUSIBLE_SUFFIX: &[&str] = &[
"Processor",
"Context",
"Listener",
"Mixin",
"Component",
];
/// Verbs for methods/fields (`verbNoun`, e.g. `resolveToken`).
/// Глаголы для методов/полей (`verbNoun`, напр. `resolveToken`).
pub(super) const PLAUSIBLE_VERB: &[&str] = &[
"get", "set", "update", "process", "handle", "compute", "resolve", "load", "build", "parse",
"fetch", "apply", "validate", "clear", "reset", "sync", "flush", "bind", "attach", "detach",

View file

@ -1,4 +1,4 @@
//! Name generation: styles, anti-keyword checks, uniqueness within a scope.
//! Генерация имён: стили, анти-ключевые слова, уникальность в scope.
pub mod alphabet;
#[cfg(test)]
@ -13,18 +13,18 @@ use self::alphabet::{
LATIN_UPPER, PLAUSIBLE_NOUN, PLAUSIBLE_SUFFIX, PLAUSIBLE_VERB, UNICODE_LETTERS,
};
/// Name generator with guaranteed uniqueness within a single scope.
/// Генератор имён с гарантированной уникальностью в пределах одного scope.
pub struct NameGenerator {
rng: Rng,
style: NameStyle,
used: HashSet<String>,
/// Fallback counter for when the random pool is exhausted.
/// Счётчик-страховка, если случайные варианты исчерпаны.
fallback: u64,
avoid_class: bool,
}
impl NameGenerator {
/// Generator for the given style.
/// Генератор для указанного стиля.
pub fn new(rng: Rng, style: NameStyle) -> Self {
Self {
rng,
@ -35,18 +35,18 @@ impl NameGenerator {
}
}
/// "Class name" mode: additionally avoid names from the JDK/annotations.
/// Режим «имена классов»: дополнительно избегаем имён из JDK/аннотаций.
pub fn for_classes(mut self) -> Self {
self.avoid_class = true;
self
}
/// Reserve a specific name (protects against collisions with keep-listed names).
/// Занять конкретное имя (защита от коллизий с keep-именами).
pub fn reserve(&mut self, name: impl Into<String>) {
self.used.insert(name.into());
}
/// The next free name.
/// Следующее свободное имя.
pub fn next_name(&mut self) -> String {
for _ in 0..64 {
let candidate = self.candidate();
@ -55,7 +55,7 @@ impl NameGenerator {
return candidate;
}
}
// Fallback: a deterministic counter, guaranteed unique.
// Страховка: детерминированный счётчик, гарантированно уникален.
loop {
self.fallback += 1;
let candidate = format!("{}{}", self.style_prefix(), self.fallback);
@ -95,7 +95,7 @@ impl NameGenerator {
};
let idx = self.rng.below(alpha.len() as u64) as usize;
let ch = alpha[idx] as char;
// First character must be a letter, not a digit.
// Первый символ — только буква (не цифра).
if i == 0 && !ch.is_ascii_alphabetic() {
out.push('a');
} else {
@ -123,9 +123,9 @@ impl NameGenerator {
}
name
}
// Blends in as ordinary application code instead of obvious
// noise: classes get `NounSuffix` (`TextureCache`), members get
// camelCase `verbNoun` (`resolveToken`).
// Маскируется под обычный прикладной код, а не под мусор:
// классы — `NounSuffix` (`TextureCache`), члены — `verbNoun`
// (`resolveToken`) camelCase.
NameStyle::Plausible => {
let noun = PLAUSIBLE_NOUN[self.rng.below(PLAUSIBLE_NOUN.len() as u64) as usize];
if self.avoid_class {

View file

@ -1,4 +1,4 @@
//! Name generator tests: uniqueness, validity, per-style shape.
//! Тесты генератора имён: уникальность, валидность, форма по стилю.
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -15,7 +15,7 @@ fn names_are_unique_and_valid() {
let mut seen = HashSet::new();
for _ in 0..500 {
let name = names.next_name();
assert!(seen.insert(name.clone()), "duplicate name {name}");
assert!(seen.insert(name.clone()), "повтор имени {name}");
assert!(!KEYWORDS.contains(&name.as_str()));
assert!(name.starts_with(|c: char| c.is_ascii_alphabetic()));
}
@ -57,7 +57,7 @@ fn plausible_class_names_look_like_noun_suffix() {
for _ in 0..50 {
let name = names.next_name();
assert!(name.starts_with(|c: char| c.is_ascii_uppercase()), "{name}");
// Two words run together in CamelCase with no separator.
// Два слова подряд слиплись в CamelCase без разделителей.
assert!(
name.chars().filter(|c| c.is_ascii_uppercase()).count() >= 2,
"{name}"

View file

@ -1,259 +0,0 @@
//! Junk method bodies: plausible branching integer code.
//!
//! A helper is `private static int helper()`: two int locals (`acc`, `i`),
//! a counted loop with a few random binary ops plus one even/odd if/else
//! merge for a real branching shape. Everything is stack-neutral by
//! construction and uses only non-throwing integer ops: woven junk really
//! runs, so it must never throw.
//!
//! Labels start at fixed small numbers: bodies are built from scratch, so
//! nothing collides (labels are per-method).
use noxis_classfile::{Arith, BranchCond, Code, Cond, Const, Insn, Prim, SlotKind};
use noxis_core::Rng;
/// Non-throwing integer ops for junk arithmetic (`Div`/`Rem` could trap).
const OPS: [Arith; 8] = [
Arith::Add,
Arith::Sub,
Arith::Mul,
Arith::And,
Arith::Or,
Arith::Xor,
Arith::Shl,
Arith::Shr,
];
/// Fresh-label block for one helper (head, end, odd, merge).
const HEAD: u32 = 1;
const END: u32 = 2;
const ODD: u32 = 3;
const MERGE: u32 = 4;
/// Build one helper body.
pub(super) fn helper_body(rng: &mut Rng) -> Code {
let bound = 4 + rng.below(29) as i32;
let mut insns = vec![
Insn::Const(Const::Int(0)),
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(0)),
Insn::Store {
slot: 1,
kind: SlotKind::Int,
},
Insn::Mark(HEAD),
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(bound)),
Insn::Branch(BranchCond::Int(Cond::Ge), END),
];
// Straight-line accumulator churn: `acc = acc op i`, two to four ops.
for _ in 0..2 + rng.below(3) {
let op = OPS[rng.below(OPS.len() as u64) as usize];
insns.extend([
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
Insn::Binary {
prim: Prim::Int,
op,
},
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
]);
}
// Even/odd merge: `if ((i & 1) == 0) acc += c1 else acc ^= c2`.
let (even, odd) = (rng.next_u64() as i32, rng.next_u64() as i32);
insns.extend([
Insn::Load {
slot: 1,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(1)),
Insn::Binary {
prim: Prim::Int,
op: Arith::And,
},
Insn::Branch(BranchCond::Zero(Cond::Ne), ODD),
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(even)),
Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
},
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
Insn::Goto(MERGE),
Insn::Mark(ODD),
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Const(Const::Int(odd)),
Insn::Binary {
prim: Prim::Int,
op: Arith::Xor,
},
Insn::Store {
slot: 0,
kind: SlotKind::Int,
},
Insn::Mark(MERGE),
]);
insns.extend([
Insn::Iinc { index: 1, delta: 1 },
Insn::Goto(HEAD),
Insn::Mark(END),
Insn::Load {
slot: 0,
kind: SlotKind::Int,
},
Insn::Return(Some(Prim::Int)),
]);
Code {
max_stack: 4,
max_locals: 2,
insns,
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
}
}
/// Build the entry body: call every helper, sum the results into the static
/// field (a bare `void` call with a dropped result is a recognizable junk
/// pattern on its own). With no helpers the entry is a bare return.
pub(super) fn entry_body(callees: &[(String, String)], owner: &str, field: &str) -> Code {
let mut insns = Vec::new();
let mut first = true;
for (callee_owner, callee_name) in callees {
insns.push(Insn::Invoke {
kind: noxis_classfile::InvokeKind::Static,
owner: callee_owner.clone(),
name: callee_name.clone(),
descriptor: "()I".to_string(),
itf: false,
});
if first {
first = false;
} else {
insns.push(Insn::Binary {
prim: Prim::Int,
op: Arith::Add,
});
}
}
if callees.is_empty() {
insns.push(Insn::Return(None));
} else {
insns.push(Insn::PutStatic {
owner: owner.to_string(),
name: field.to_string(),
descriptor: "I".to_string(),
});
insns.push(Insn::Return(None));
}
Code {
max_stack: 2,
max_locals: 0,
insns,
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::*;
/// Helpers branch and loop instead of returning immediately.
#[test]
fn helper_has_branches_and_loop() {
let mut rng = Rng::from_seed(3);
let code = helper_body(&mut rng);
let has = |pred: &dyn Fn(&Insn) -> bool| code.insns.iter().any(pred);
assert!(has(&|i| matches!(i, Insn::Branch(..))), "no branch");
assert!(has(&|i| matches!(i, Insn::Goto(_))), "no loop back-edge");
assert!(has(&|i| matches!(i, Insn::Binary { .. })), "no arithmetic");
assert!(has(&|i| matches!(i, Insn::Iinc { .. })), "no counter");
assert!(
has(&|i| matches!(i, Insn::Return(Some(Prim::Int)))),
"no int return"
);
assert_eq!(code.max_locals, 2);
// Every jump target is declared.
let marks: std::collections::BTreeSet<u32> = code
.insns
.iter()
.filter_map(|i| match i {
Insn::Mark(label) => Some(*label),
_ => None,
})
.collect();
for insn in &code.insns {
for target in insn.targets() {
assert!(marks.contains(&target), "dangling label {target}");
}
}
}
/// Same seed, same body.
#[test]
fn helper_is_deterministic() {
let first = helper_body(&mut Rng::from_seed(9));
let second = helper_body(&mut Rng::from_seed(9));
assert_eq!(first.insns, second.insns);
let third = helper_body(&mut Rng::from_seed(10));
assert_ne!(first.insns, third.insns);
}
/// The entry calls every helper and stores the sum into the field.
#[test]
fn entry_calls_helpers_and_stores() {
let callees = vec![
("junk/A".to_string(), "h0".to_string()),
("junk/A".to_string(), "h1".to_string()),
];
let code = entry_body(&callees, "junk/A", "f");
let invokes = code
.insns
.iter()
.filter(|i| matches!(i, Insn::Invoke { .. }))
.count();
assert_eq!(invokes, 2);
assert!(
code.insns
.iter()
.any(|i| matches!(i, Insn::PutStatic { name, .. } if name == "f")),
"no field store"
);
assert!(matches!(code.insns.last(), Some(Insn::Return(None))));
}
/// No helpers, no calls: a bare return, still valid.
#[test]
fn entry_without_helpers_returns() {
let code = entry_body(&[], "junk/A", "f");
assert_eq!(code.insns, vec![Insn::Return(None)]);
}
}

View file

@ -1,38 +1,26 @@
//! Noise pass: junk classes with real bodies, woven into reachability.
//! Пасс шума: junk-классы и вплетание их в граф достижимости.
//!
//! Dead code gets dropped by shrink analysis, so every junk class gets an
//! edge from live code (an `invokestatic` of its entry). Junk names come
//! from the same generator (and styles) as real code: self-describing
//! `shadow/decoy` names with a uniform `run` entry would be a grep pattern
//! of their own.
//! Мёртвый код выкидывается shrink-анализом, поэтому каждый junk-класс
//! получает ребро из живого метода (`invokestatic shadow/decoyN.run()V`).
//! Junk-аннотации не генерируются: сырые атрибуты не несут свежие индексы пула.
mod body;
mod weave;
#[cfg(test)]
mod tests;
use crate::namegen::NameGenerator;
use crate::rename::assign::parent_package;
use body::{entry_body, helper_body};
use noxis_analysis::{ClassHierarchy, JdkHierarchy};
use noxis_classfile::{ClassBuilder, Field, Program, Version, compute_frames};
use noxis_classfile::{ClassBuilder, Program, Version, empty_code};
use noxis_core::{Context, CoreError, Pass, PassId, PassReport};
use weave::weave_first_reachable;
/// Flags for the junk entry (`public static`, callable from live code).
/// Префикс детерминированных имён junk-классов.
const JUNK_PREFIX: &str = "shadow/decoy";
/// Имя и дескриптор точки входа junk-класса.
const JUNK_ENTRY: (&str, &str) = ("run", "()V");
/// Флаги `public static` для junk-метода.
const ACC_PUBLIC_STATIC: u16 = 0x0009;
/// Flags for helpers and the accumulator field (`private static`).
const ACC_PRIVATE_STATIC: u16 = 0x000A;
/// The entry descriptor (always `()V`).
const ENTRY_DESCRIPTOR: &str = "()V";
/// Helper methods return the accumulator (`int`).
const HELPER_DESCRIPTOR: &str = "()I";
/// The accumulator field type.
const FIELD_DESCRIPTOR: &str = "I";
/// The noise pass.
/// Пасс шума.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoisePass;
@ -43,7 +31,6 @@ impl Pass for NoisePass {
fn apply(&self, ctx: &mut Context, program: &mut Program) -> Result<PassReport, CoreError> {
let ratio = ctx.config.noise.junk_ratio;
let methods_per_class = ctx.config.noise.junk_methods_per_class;
let annotations = ctx.config.noise.junk_annotations;
let weave = ctx.config.noise.weave_reachable;
@ -52,7 +39,7 @@ impl Pass for NoisePass {
pass: PassId::Noise,
transformed: 0,
skipped: 0,
notes: vec!["noise off: junk_ratio=0, junk_annotations=0".to_string()],
notes: vec!["шум выключен: junk_ratio=0, junk_annotations=0".to_string()],
});
}
@ -63,100 +50,45 @@ impl Pass for NoisePass {
let real_classes = program.classes.len();
let count = ratio.saturating_mul(real_classes);
let mut class_names =
NameGenerator::new(ctx.rng("noise/classes"), ctx.config.rename.class_style)
.for_classes();
for class in &program.classes {
class_names.reserve(class.this_class.clone());
let mut junk_names = Vec::with_capacity(count);
let mut suffix = 0usize;
for _ in 0..count {
let name = loop {
let candidate = format!("{JUNK_PREFIX}{suffix}");
suffix = suffix.saturating_add(1);
if program.class(&candidate).is_none() {
break candidate;
}
let mut rng = ctx.rng("noise");
// (class, entry) pairs for weaving, in creation order.
let mut entries: Vec<(String, String)> = Vec::with_capacity(count);
// (class index, method index) of every generated method, for frames.
let mut fresh_methods: Vec<(usize, usize)> = Vec::new();
for index in 0..count {
let package = if real_classes > 0 {
let pick = &program.classes[rng.below(real_classes as u64) as usize].this_class;
parent_package(pick)
} else {
String::new()
};
let simple = class_names.next_name();
let name = if package.is_empty() {
simple
} else {
format!("{package}/{simple}")
};
let mut member_names = NameGenerator::new(
ctx.rng_nth("noise/members", index as u64),
ctx.config.rename.member_style,
);
let entry_name = member_names.next_name();
let field_name = member_names.next_name();
let mut helpers: Vec<(String, String)> = Vec::new();
let mut builder = ClassBuilder::new(name.clone(), None).version(version);
for _ in 0..methods_per_class {
let helper_name = member_names.next_name();
let body = helper_body(&mut rng);
builder = builder.method_with_code(
ACC_PRIVATE_STATIC,
helper_name.clone(),
HELPER_DESCRIPTOR,
body,
);
helpers.push((name.clone(), helper_name));
}
let callees: Vec<(String, String)> = helpers.clone();
let entry = entry_body(&callees, &name, &field_name);
builder = builder.method_with_code(
ACC_PUBLIC_STATIC,
entry_name.clone(),
ENTRY_DESCRIPTOR,
entry,
);
let mut junk = builder.build();
junk.fields.push(Field {
access_flags: ACC_PRIVATE_STATIC,
name: field_name,
descriptor: FIELD_DESCRIPTOR.to_string(),
attributes: Vec::new(),
});
let base = program.classes.len();
for mi in 0..junk.methods.len() {
fresh_methods.push((base, mi));
}
let junk = ClassBuilder::new(name.clone(), None)
.version(version)
.method_with_code(ACC_PUBLIC_STATIC, JUNK_ENTRY.0, JUNK_ENTRY.1, empty_code(0))
.build();
program.classes.push(junk);
entries.push((name, entry_name));
}
let added = entries.len();
// Frames for every generated branching method.
let hierarchy = ClassHierarchy::build(program);
let frames = JdkHierarchy::wrap(&hierarchy);
for (ci, mi) in &fresh_methods {
refresh_frames(program, *ci, *mi, &frames)?;
junk_names.push(name);
}
let added = junk_names.len();
let mut woven = 0usize;
if weave && added > 0 {
woven = weave_first_reachable(program, real_classes, &entries)?;
woven = weave_first_reachable(program, real_classes, &junk_names)?;
}
let mut skipped = 0usize;
let mut notes = Vec::new();
if added > 0 {
notes.push(format!("junk classes added: {added}"));
notes.push(format!("добавлено junk-классов: {added}"));
}
if woven > 0 {
notes.push(format!("woven calls: {woven}"));
notes.push(format!("вплетено вызовов: {woven}"));
}
if added == 0 && woven == 0 {
notes.push("nothing to fuzz: no classes or methods with code".to_string());
notes.push("нечего шуметь: нет классов или методов с кодом".to_string());
}
if annotations > 0 {
skipped = annotations.saturating_mul(program.classes.len());
notes.push(format!(
"junk_annotations skipped: raw attributes cannot carry fresh pool indices (skipped: {skipped})"
"junk_annotations пропущен: сырые атрибуты не могут нести свежие индексы пула (пропущено: {skipped})"
));
}
@ -173,35 +105,85 @@ impl Pass for NoisePass {
}
}
/// Recompute the frames of a generated method.
fn refresh_frames(
program: &mut Program,
ci: usize,
mi: usize,
hierarchy: &JdkHierarchy<'_>,
) -> Result<(), CoreError> {
let (name, snapshot) = {
let class = program
.classes
.get(ci)
.ok_or_else(|| CoreError::pass(PassId::Noise, "class vanished"))?;
(
class.this_class.clone(),
class
.methods
.get(mi)
.cloned()
.ok_or_else(|| CoreError::pass(PassId::Noise, "method vanished"))?,
)
};
let frames = compute_frames(&name, &snapshot, hierarchy)
.map_err(|e| CoreError::pass(PassId::Noise, e.to_string()))?;
program
.classes
.get_mut(ci)
.and_then(|c| c.methods.get_mut(mi))
.and_then(|m| m.code.as_mut())
.ok_or_else(|| CoreError::pass(PassId::Noise, "method vanished"))?
.frames = frames;
Ok(())
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{Insn, InvokeKind, Resource};
use noxis_core::{Config, NoiseConfig};
use super::*;
fn sample() -> Program {
Program {
classes: vec![
ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(ACC_PUBLIC_STATIC, "run", "()V", empty_code(0))
.build(),
],
resources: vec![Resource {
path: "app.json".into(),
data: br#"{}"#.to_vec(),
}],
}
}
fn run(program: &mut Program, noise: NoiseConfig) -> PassReport {
let config = Config {
seed: Some(42),
noise,
..Config::default()
};
let mut ctx = Context::new(config);
NoisePass.apply(&mut ctx, program).expect("noise pass")
}
#[test]
fn adds_junk_and_weaves_call() {
let mut program = sample();
let noise = NoiseConfig {
junk_ratio: 2,
junk_annotations: 0,
weave_reachable: true,
};
let report = run(&mut program, noise);
assert_eq!(program.classes.len(), 3);
assert_eq!(program.classes[1].this_class, "shadow/decoy0");
assert_eq!(program.classes[2].this_class, "shadow/decoy1");
let insns = &program.classes[0].methods[0].code.as_ref().unwrap().insns;
assert_eq!(insns.len(), 2);
match &insns[0] {
Insn::Invoke {
kind,
owner,
name,
descriptor,
itf,
} => {
assert_eq!(*kind, InvokeKind::Static);
assert_eq!(owner, "shadow/decoy0");
assert_eq!(name, "run");
assert_eq!(descriptor, "()V");
assert!(!itf);
}
other => panic!("ожидался Invoke, получено: {other:?}"),
}
assert!(matches!(insns[1], Insn::Return(None)));
assert_eq!(report.transformed, 3);
assert_eq!(report.skipped, 0);
}
#[test]
fn disabled_ratio_changes_nothing() {
let mut program = sample();
let before = program.clone();
let report = run(&mut program, NoiseConfig::default());
assert_eq!(program, before);
assert_eq!(report.transformed, 0);
assert_eq!(report.skipped, 0);
}
}

View file

@ -1,208 +0,0 @@
//! Noise pass tests: junk shape, names, weaving, determinism.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_classfile::{
ClassBuilder, Insn, InvokeKind, Program, Resource, Version, empty_code, format,
};
use noxis_core::{Config, NoiseConfig};
use super::*;
fn sample() -> Program {
Program {
classes: vec![
ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(0x0009, "run", "()V", empty_code(0))
.build(),
],
resources: vec![Resource {
path: "app.json".into(),
data: br#"{}"#.to_vec(),
}],
}
}
fn noisy() -> NoiseConfig {
NoiseConfig {
junk_ratio: 2,
junk_methods_per_class: 2,
junk_annotations: 0,
weave_reachable: true,
}
}
fn run(program: &mut Program, noise: NoiseConfig) -> PassReport {
let config = Config {
seed: Some(42),
noise,
..Config::default()
};
let mut ctx = Context::new(config);
NoisePass.apply(&mut ctx, program).expect("noise pass")
}
fn is_identifier(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(first) if first.is_alphabetic() || first == '_' || first == '$' => {}
_ => return false,
}
chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}
#[test]
fn adds_junk_with_bodies_and_weaves_call() {
let mut program = sample();
let report = run(&mut program, noisy());
assert_eq!(program.classes.len(), 3);
let junks = &program.classes[1..];
let mut names = Vec::new();
for junk in junks {
// No self-describing fingerprints, valid identifiers, unique.
assert!(
!junk.this_class.contains("shadow") && !junk.this_class.contains("decoy"),
"fingerprint survived: {}",
junk.this_class
);
for part in junk.this_class.split('/') {
assert!(is_identifier(part), "bad segment in {}", junk.this_class);
}
names.push(junk.this_class.clone());
// One accumulator field, fed by the entry.
assert_eq!(junk.fields.len(), 1);
assert_eq!(junk.fields[0].descriptor, "I");
let field = junk.fields[0].name.clone();
// Helpers have real branching bodies, not bare returns.
let helpers: Vec<_> = junk
.methods
.iter()
.filter(|m| m.descriptor == HELPER_DESCRIPTOR)
.collect();
assert_eq!(helpers.len(), 2);
for helper in helpers {
let code = helper.code.as_ref().expect("code");
assert!(
code.insns.iter().any(|i| matches!(i, Insn::Branch(..))),
"helper without branches"
);
assert!(
code.insns.iter().any(|i| matches!(i, Insn::Binary { .. })),
"helper without arithmetic"
);
assert!(!code.frames.is_empty(), "helper frames were not computed");
}
// The entry calls the helpers and stores into the field.
let entry = junk
.methods
.iter()
.find(|m| m.descriptor == ENTRY_DESCRIPTOR)
.expect("entry");
let entry_code = entry.code.as_ref().expect("code");
let calls = entry_code
.insns
.iter()
.filter(|i| matches!(i, Insn::Invoke { .. }))
.count();
assert_eq!(calls, 2, "entry must call every helper");
assert!(
entry_code
.insns
.iter()
.any(|i| matches!(i, Insn::PutStatic { name, .. } if name == &field)),
"entry must feed the field"
);
}
assert_ne!(names[0], names[1]);
// The live method opens with a call into the first junk entry.
let live = program.classes[0].methods[0].code.as_ref().unwrap();
match &live.insns[0] {
Insn::Invoke {
kind,
owner,
descriptor,
itf,
..
} => {
assert_eq!(*kind, InvokeKind::Static);
assert_eq!(owner, &names[0]);
assert_eq!(descriptor, "()V");
assert!(!itf);
}
other => panic!("expected Invoke, got: {other:?}"),
}
assert_eq!(report.transformed, 3);
assert_eq!(report.skipped, 0);
}
#[test]
fn disabled_ratio_changes_nothing() {
let mut program = sample();
let before = program.clone();
let report = run(&mut program, NoiseConfig::default());
assert_eq!(program, before);
assert_eq!(report.transformed, 0);
assert_eq!(report.skipped, 0);
}
#[test]
fn junk_is_deterministic() {
let mut first = sample();
let mut second = sample();
run(&mut first, noisy());
run(&mut second, noisy());
assert_eq!(first, second);
}
/// Junk bodies carry real branches: they must verify under a real JVM.
#[test]
fn junk_verifies_under_java() {
if std::process::Command::new("java")
.arg("-version")
.output()
.is_err()
{
eprintln!("SKIP: no java");
return;
}
let mut program = sample();
run(
&mut program,
NoiseConfig {
junk_ratio: 1,
..noisy()
},
);
let dir = std::env::temp_dir().join(format!("noxis-noise-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for class in &program.classes {
let bytes = format::write(class).expect("write");
let mut path = dir.clone();
for part in class.this_class.split('/') {
path.push(part);
}
path.set_extension("class");
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
std::fs::write(&path, bytes).expect("write class");
}
for class in &program.classes {
let dotted = class.this_class.replace('/', ".");
let output = std::process::Command::new("java")
.arg("-Xverify:all")
.arg("-cp")
.arg(&dir)
.arg(&dotted)
.output()
.expect("run java");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.contains("VerifyError") && !stderr.contains("ClassFormatError"),
"{dotted}: {stderr}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}

View file

@ -1,23 +1,22 @@
//! Weaving junk classes into the reachability graph of live methods.
//! Вплетание junk-классов в граф достижимости живых методов.
use noxis_analysis::{ClassHierarchy, JdkHierarchy};
use noxis_analysis::ClassHierarchy;
use noxis_classfile::{Insn, InvokeKind, Program, compute_frames};
use noxis_core::{CoreError, PassId};
/// The woven call descriptor (entries are always `()V`).
const WOVEN_DESCRIPTOR: &str = "()V";
use super::JUNK_ENTRY;
/// Weave a call of the first junk entry into the first method with code.
/// Вплетает вызов первого junk-класса в первый метод с кодом.
///
/// The call lands before the terminal (`Return`/`AReturn`/`AThrow`) so it
/// never strands an unreachable tail without frames; frames are recomputed.
/// Вызов встаёт перед терминалом (`Return`/`AReturn`/`AThrow`), чтобы не
/// породить недостижимый хвост без фреймов; фреймы пересчитываются.
pub(super) fn weave_first_reachable(
program: &mut Program,
real_classes: usize,
entries: &[(String, String)],
junk_names: &[String],
) -> Result<usize, CoreError> {
let missing = || CoreError::pass(PassId::Noise, "weave target vanished");
let Some((owner, entry)) = entries.first() else {
let missing = || CoreError::pass(PassId::Noise, "цель вплетания пропала");
let Some(owner) = junk_names.first() else {
return Err(missing());
};
let target = program.classes[..real_classes.min(program.classes.len())]
@ -40,8 +39,8 @@ pub(super) fn weave_first_reachable(
let call = Insn::Invoke {
kind: InvokeKind::Static,
owner: owner.clone(),
name: entry.clone(),
descriptor: WOVEN_DESCRIPTOR.to_string(),
name: JUNK_ENTRY.0.to_string(),
descriptor: JUNK_ENTRY.1.to_string(),
itf: false,
};
{
@ -68,8 +67,7 @@ pub(super) fn weave_first_reachable(
.cloned()
.ok_or_else(missing)?;
let hierarchy = ClassHierarchy::build(program);
let frames_hierarchy = JdkHierarchy::wrap(&hierarchy);
let frames = compute_frames(&class_name, &snapshot, &frames_hierarchy)
let frames = compute_frames(&class_name, &snapshot, &hierarchy)
.map_err(|e| CoreError::pass(PassId::Noise, e.to_string()))?;
program
.classes

View file

@ -1,23 +1,20 @@
//! Assigning new names: maps, virtual method families, the package pool,
//! and final access widening.
//! Назначение новых имён: карты, семейства виртуальных методов,
//! пул пакетов и финальное ширинирование доступа.
use std::collections::{BTreeMap, BTreeSet};
use noxis_analysis::{Analysis, ClassHierarchy, external_dispatch_families};
use noxis_analysis::{Analysis, ClassHierarchy};
use noxis_classfile::Program;
use noxis_core::{Config, Context, NameStyle, Rng};
use super::{ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC, ACC_STATIC};
use crate::namegen::NameGenerator;
/// `(owner, name, descriptor)` - matches a JVM reference.
/// `(owner, name, descriptor)` — как в JVM-ссылке.
pub(super) type MemberKey = (String, String, String);
/// `(method name, params)` - one virtual family.
pub(super) type FamilyKey = (String, String);
/// Rename maps for one run: `declared` is where a member was declared,
/// `alias` is subclasses that inherit the name without declaring it themselves.
/// Карты переименований одного прогона: `declared` — где объявлено,
/// `alias` — наследники, которые наследуют это имя без своего объявления.
#[derive(Debug, Default)]
pub(super) struct RenameMaps {
pub(super) classes: BTreeMap<String, String>,
@ -44,7 +41,7 @@ impl RenameMaps {
.cloned()
}
/// Aliases: a subclass calls a member declared on a parent class.
/// Псевдоними: наследник вызывает член, объявленный в предке.
pub(super) fn expand(&mut self, hierarchy: &ClassHierarchy, owners: &[String]) {
let methods: Vec<(MemberKey, String)> = self
.methods
@ -88,19 +85,19 @@ impl RenameMaps {
}
}
/// Family = (name, params): the return type is ignored, so covariant
/// returns and bridge methods (`ACC_BRIDGE`) are captured together.
///
/// Also returns the families that must keep their original name: a locked
/// class or a `keep_member` name in the family locks it for everybody -
/// renaming only the other members would split the override chain.
pub(super) fn build_virtual_families(
/// Переименование виртуальных методов «семейством»: одно имя на всю иерархию,
/// включая мостовые методы с ковариантным возвратом.
pub(super) fn rename_virtual_families(
program: &Program,
analysis: &Analysis,
hierarchy: &ClassHierarchy,
) -> (BTreeMap<FamilyKey, Vec<MemberKey>>, BTreeSet<FamilyKey>) {
let mut families: BTreeMap<FamilyKey, Vec<MemberKey>> = BTreeMap::new();
let mut locked: BTreeSet<FamilyKey> = BTreeSet::new();
maps: &mut RenameMaps,
cfg: &Config,
ctx: &mut Context,
) -> usize {
// Семейство = (имя, параметры): возврат игнорируем — так захватываем
// ковариантные возвраты и мостовые методы (`ACC_BRIDGE`) разом.
let mut families: BTreeMap<(String, String), Vec<MemberKey>> = BTreeMap::new();
let mut locked_families: BTreeSet<(String, String)> = BTreeSet::new();
for class in &program.classes {
let locked_class = analysis.is_locked(&class.this_class);
@ -116,7 +113,7 @@ pub(super) fn build_virtual_families(
};
let family = (method.name.clone(), params);
if locked_class || analysis.keep.keeps_member(&method.name) {
locked.insert(family.clone());
locked_families.insert(family.clone());
}
families.entry(family).or_default().push((
class.this_class.clone(),
@ -126,22 +123,6 @@ pub(super) fn build_virtual_families(
}
}
// Семейства, которые диспатчатся через внешние интерфейсы/классы, обязаны
// сохранить имя: внешний вызывающий код не переименовать.
locked.extend(external_dispatch_families(program, hierarchy));
(families, locked)
}
/// Rename virtual methods as a "family": one name for the whole hierarchy,
/// including bridge methods with covariant returns.
pub(super) fn rename_virtual_families(
families: BTreeMap<(String, String), Vec<MemberKey>>,
locked_families: BTreeSet<FamilyKey>,
maps: &mut RenameMaps,
cfg: &Config,
ctx: &mut Context,
) -> usize {
let mut renamed = 0usize;
let mut family_index = 0u64;
for (family_key, members) in families {
@ -168,8 +149,8 @@ pub(super) fn rename_virtual_families(
renamed
}
/// `(<params>)<ret>` → `(<params>)`, or `None` if the descriptor is malformed.
pub(super) fn params_of(descriptor: &str) -> Option<String> {
/// `(<params>)<ret>` → `(<params>)`, либо `None`, если дескриптор кривой.
fn params_of(descriptor: &str) -> Option<String> {
let close = descriptor.find(')')?;
if !descriptor.starts_with('(') {
return None;
@ -177,7 +158,7 @@ pub(super) fn params_of(descriptor: &str) -> Option<String> {
Some(descriptor[..=close].to_string())
}
pub(crate) fn parent_package(internal: &str) -> String {
pub(super) fn parent_package(internal: &str) -> String {
match internal.rfind('/') {
Some(i) => internal[..i].to_string(),
None => String::new(),
@ -191,8 +172,7 @@ pub(super) fn simple_name(internal: &str) -> String {
}
}
/// Pool of random packages (2-3 segments); a single empty one when spreading
/// is turned off.
/// Пул случайных пакетов (2–3 сегмента); при выключенном разбросе — один пустой.
pub(super) fn generate_packages(cfg: &Config, rng: &mut Rng) -> Vec<String> {
if !cfg.rename.spread_packages {
return vec![String::new()];
@ -214,12 +194,7 @@ pub(super) fn generate_packages(cfg: &Config, rng: &mut Rng) -> Vec<String> {
.collect()
}
/// Rewrite a descriptor/signature: `Lpkg/Class;` → the new class name.
///
/// Generic signatures nest (`LMap<LString;LFoo;>;`): the name scan stops at
/// `<` as well as `;`, so type arguments fall back into the main loop and
/// get rewritten in turn. Stopping only at `;` swallowed the inner
/// reference into one unmapped blob (a stale `Comparable<Old>` leak).
/// Переписать дескриптор/сигнатуру: `Lpkg/Class;` → новое имя класса.
pub(super) fn rewrite_descriptor(desc: &str, classes: &BTreeMap<String, String>) -> String {
if !desc.contains('L') {
return desc.to_string();
@ -232,22 +207,20 @@ pub(super) fn rewrite_descriptor(desc: &str, classes: &BTreeMap<String, String>)
continue;
}
let mut name = String::new();
let mut term = ';';
for c in chars.by_ref() {
if c == ';' || c == '<' {
term = c;
if c == ';' {
break;
}
name.push(c);
}
out.push('L');
out.push_str(classes.get(&name).map_or(name.as_str(), String::as_str));
out.push(term);
out.push(';');
}
out
}
/// Widen access to `public` so moving to a different package doesn't break calls.
/// Расширить доступ до `public`, чтобы переезд в другой пакет не ломал вызовы.
pub(super) fn widen_all(program: &mut Program) {
for class in program.classes.iter_mut() {
class.access_flags = widen(class.access_flags);

View file

@ -1,20 +1,20 @@
//! The rename pass: classes, fields, methods, locals, descriptors.
//! Пасс переименования: классы, поля, методы, локальные переменные, дескрипторы.
//!
//! The cheapest technique with the highest payoff (see `info/evo-weaknesses.md`:
//! EvoVis never renamed members at all, so the class read plainly via `javap -p`).
//! Это самая дешёвая и самая отдающая техника (см. `info/evo-weaknesses.md`:
//! у EvoVis члены не переименовывались вообще, и класс читался по `javap -p`).
//!
//! Subtleties handled here:
//! - a `Sub.staticMethod()` call may name a subclass as the owner - aliases
//! (`alias`) are needed across the hierarchy;
//! - bridge methods (`ACC_BRIDGE`) and covariant returns live in one method
//! "family" - they must be renamed together;
//! - `serialVersionUID`, JNI, reflection, serialization stay untouched.
//! Тонкости, которые здесь учитываются:
//! - вызов `Sub.staticMethod()` может указывать владельцем подкласс — нужны
//! псевдонимы (`alias`) для всей иерархии;
//! - мостовые методы (`ACC_BRIDGE`) и ковариантные возвраты живут в одном
//! «семействе» метода — переименовывать их нужно разом;
//! - `serialVersionUID`, JNI, рефлексия, сериализация — не трогаем.
/// Name maps and the assignment strategy.
pub(crate) mod assign;
/// Rewriting method bodies and attributes.
/// Карты и стратегия назначения имён.
mod assign;
/// Переписывание тел методов и атрибутов.
mod rewrite;
/// Pass integration tests.
/// Интеграционные тесты пасса.
#[cfg(test)]
mod tests;
@ -23,8 +23,7 @@ use noxis_classfile::Program;
use noxis_core::{Context, CoreError, Pass, PassId, PassReport, field_key, method_key};
use self::assign::{
RenameMaps, build_virtual_families, generate_packages, params_of, parent_package,
rename_virtual_families, simple_name, widen_all,
RenameMaps, generate_packages, parent_package, rename_virtual_families, simple_name, widen_all,
};
use self::rewrite::rewrite_class;
use crate::namegen::NameGenerator;
@ -36,7 +35,7 @@ const ACC_STATIC: u16 = 0x0008;
const ACC_FINAL: u16 = 0x0010;
const ACC_ENUM: u16 = 0x4000;
/// The rename pass.
/// Пасс переименования.
#[derive(Debug, Default, Clone, Copy)]
pub struct RenamePass;
@ -59,14 +58,7 @@ impl Pass for RenamePass {
let mut maps = RenameMaps::default();
let mut renamed_classes = 0usize;
// Family membership up front: step 2 must not rename a method that
// belongs to a shared or locked family on its own - a per-class
// rename splits the override chain (the JVM then fails dispatch
// with AbstractMethodError, real case: shaded gson's package-private
// `ReflectionHelper$RecordHelper.isRecord` chain).
let (families, locked_families) = build_virtual_families(program, &analysis, &hierarchy);
// 1. Class names.
// 1. Имена классов.
{
let packages = generate_packages(&cfg, &mut ctx.rng("rename/packages"));
let mut names =
@ -99,7 +91,7 @@ impl Pass for RenamePass {
}
}
// 2. Simple (non-virtual) members: private/static/final.
// 2. Простые (не-виртуальные) члены: private/static/final.
let mut renamed_methods = 0usize;
let mut renamed_fields = 0usize;
@ -125,35 +117,6 @@ impl Pass for RenamePass {
method_names.reserve(method.name.clone());
continue;
}
// A method shared with another class must not get its
// name here: the family pass assigns one common name
// (aggressive mode), or the whole family keeps the
// original when it is locked. A per-class rename splits
// the override chain - the JVM then fails dispatch with
// `AbstractMethodError` (real case: shaded gson's
// package-private `ReflectionHelper$RecordHelper.isRecord`
// chain, each class renamed apart).
if let Some(params) = params_of(&method.descriptor) {
let key = (method.name.clone(), params);
if let Some(members) = families.get(&key) {
let hierarchy_related = members.iter().any(|(other, _, _)| {
other != &owner
&& (hierarchy.is_subclass_of(other, &owner)
|| hierarchy.is_subclass_of(&owner, other))
});
// Aggressive mode renames every shared family
// uniformly. Without it the family pass does not
// run, so only hierarchy-related members must stay
// together; unrelated same-name methods never meet
// at dispatch and may rename individually.
let shared = members.len() > 1
&& (cfg.rename.rename_public_members || hierarchy_related);
if shared || locked_families.contains(&key) {
method_names.reserve(method.name.clone());
continue;
}
}
}
let safety = method_rename_safety(
program,
&hierarchy,
@ -175,8 +138,8 @@ impl Pass for RenamePass {
);
renamed_methods += 1;
}
// Non-final virtual: renamed only together with the whole
// family (see rename_virtual_families).
// Виртуальный не-final: переименовывается только вместе
// со всем семейством (см. rename_virtual_families).
_ => method_names.reserve(method.name.clone()),
}
}
@ -216,29 +179,28 @@ impl Pass for RenamePass {
}
}
// 3. Virtual families - aggressive mode only.
// 3. Виртуальные семейства — только в агрессивном режиме.
if cfg.rename.rename_public_members {
renamed_methods +=
rename_virtual_families(families, locked_families, &mut maps, &cfg, ctx);
renamed_methods += rename_virtual_families(program, &analysis, &mut maps, &cfg, ctx);
}
// 4. Aliases for subclasses.
// 4. Псевдоними для наследников.
maps.expand(&hierarchy, &owners);
// 5. Rewrite definitions and all references.
// 5. Переписать определения и все ссылки.
let mut local_counter = 0u64;
for class in &mut program.classes {
let orig_owner = class.this_class.clone();
rewrite_class(class, &orig_owner, &maps, &cfg, &mut local_counter, ctx);
}
// 6. Access widening: moving across packages could otherwise
// cause IllegalAccessError.
// 6. Ширинирование доступа: после переезда в другие пакеты иначе
// возможен IllegalAccessError.
if cfg.rename.widen_access {
widen_all(program);
}
// 7. Mappings for the report (stack-trace deobfuscation).
// 7. Маппинги в отчёт (обратная деобфускация stack trace'ей).
for ((owner, name, desc), new_name) in maps.methods.iter() {
ctx.mapping
.methods
@ -255,7 +217,7 @@ impl Pass for RenamePass {
let locked = analysis.locked_classes.len();
if locked > 0 {
ctx.note(format!("rename: {locked} keep-listed classes (untouched)"));
ctx.note(format!("rename: {locked} классов в keep (не тронуты)"));
}
Ok(PassReport {
@ -263,7 +225,7 @@ impl Pass for RenamePass {
transformed: renamed_classes + renamed_methods + renamed_fields,
skipped: locked,
notes: vec![format!(
"classes: {renamed_classes}, methods: {renamed_methods}, fields: {renamed_fields}"
"классов: {renamed_classes}, методов: {renamed_methods}, полей: {renamed_fields}"
)],
})
}

View file

@ -1,60 +0,0 @@
//! Annotation rewriting: class descriptors follow the mapping, string
//! values are data and stay put.
use noxis_classfile::{Annotation, AnnotationValue, TypeAnnotation};
use super::super::assign::{RenameMaps, rewrite_descriptor};
/// A list of annotations (visible or invisible) - same rewrite for both.
pub(super) fn rewrite_annotations(annotations: &mut [Annotation], maps: &RenameMaps) {
for anno in annotations.iter_mut() {
rewrite_annotation(anno, maps);
}
}
/// Per-parameter annotation lists (`RuntimeVisibleParameterAnnotations`).
pub(super) fn rewrite_parameter_annotations(params: &mut [Vec<Annotation>], maps: &RenameMaps) {
for param in params.iter_mut() {
rewrite_annotations(param, maps);
}
}
/// Type-use annotations (`RuntimeVisibleTypeAnnotations` and friends):
/// the annotated type descriptor follows the mapping, the opaque
/// `target_info`/`type_path` bytes carry no pool references at all.
pub(super) fn rewrite_type_annotations(annos: &mut [TypeAnnotation], maps: &RenameMaps) {
for anno in annos.iter_mut() {
anno.descriptor = rewrite_descriptor(&anno.descriptor, &maps.classes);
for (_, value) in anno.elements.iter_mut() {
rewrite_value(value, maps);
}
}
}
fn rewrite_annotation(anno: &mut Annotation, maps: &RenameMaps) {
anno.descriptor = rewrite_descriptor(&anno.descriptor, &maps.classes);
for (_, value) in anno.elements.iter_mut() {
rewrite_value(value, maps);
}
}
pub(super) fn rewrite_value(value: &mut AnnotationValue, maps: &RenameMaps) {
match value {
// The `'e'` tag: enum type descriptor moves, the constant name does not.
AnnotationValue::Enum { descriptor, .. } => {
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
// The `'c'` tag: class-info descriptor (`LFoo;` or a primitive `I`).
AnnotationValue::Class(desc) => {
*desc = rewrite_descriptor(desc, &maps.classes);
}
AnnotationValue::Nested(anno) => rewrite_annotation(anno, maps),
AnnotationValue::Array(values) => {
for value in values.iter_mut() {
rewrite_value(value, maps);
}
}
// Scalars and strings hold no class references.
_ => {}
}
}

View file

@ -1,12 +1,11 @@
//! Переписывание тела метода: инструкции, кадры, handler'ы, атрибуты кода.
use noxis_classfile::{Code, Insn};
use noxis_classfile::{Code, Const, Insn};
use noxis_core::{Config, Context};
use super::super::assign::{RenameMaps, rewrite_descriptor};
use super::rewrite_attributes;
use super::rewrite_frame;
use super::rewrite_method_ref;
pub(super) fn rewrite_code(
code: &mut Code,
@ -23,8 +22,10 @@ pub(super) fn rewrite_code(
}
for insn in code.insns.iter_mut() {
match insn {
Insn::Const(value) => {
super::rewrite_const(value, maps);
Insn::Const(Const::Class(name)) => {
if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
}
Insn::GetStatic {
owner,
@ -60,33 +61,22 @@ pub(super) fn rewrite_code(
descriptor,
..
} => {
rewrite_method_ref(owner, name, descriptor, maps);
if let Some(new_name) = maps.method(owner, name, descriptor) {
*name = new_name;
}
if let Some(mapped) = maps.classes.get(owner.as_str()) {
*owner = mapped.clone();
}
// The call-site name belongs to the functional interface and
// stays; the descriptor (captured receiver types) is rewritten,
// and the bootstrap table entry is handled with the attributes.
Insn::InvokeDynamic { descriptor, .. } => {
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
Insn::New(name) => {
Insn::New(name)
| Insn::CheckCast(name)
| Insn::InstanceOf(name)
| Insn::ANewArray(name) => {
if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
}
// Type operands may be array descriptors (`[Lpkg/Cls;`, `[B`):
// the element class inside follows the mapping, while a plain
// name takes the exact entry. A stale descriptor is worse than
// useless - later frame merges treat it as a ghost supertype.
Insn::CheckCast(name) | Insn::InstanceOf(name) | Insn::ANewArray(name) => {
if name.starts_with('[') {
*name = rewrite_descriptor(name, &maps.classes);
} else if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
}
Insn::MultiANewArray { descriptor, .. } => {
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
_ => {}
}
}

View file

@ -1,58 +0,0 @@
//! Constant-pool references: owners and descriptors follow the mapping.
use noxis_classfile::Const;
use super::super::assign::{RenameMaps, rewrite_descriptor};
/// A method reference (invoke/bootstrap/method-handle): the owner follows
/// class renames, the name follows member renames, the descriptor is
/// rewritten. Array owners (`[Lpkg/C;` - e.g. `clone` on arrays) name the
/// element class inside a descriptor, so they take the descriptor path.
pub(super) fn rewrite_method_ref(
owner: &mut String,
name: &mut String,
descriptor: &mut String,
maps: &RenameMaps,
) {
if owner.starts_with('[') {
*owner = rewrite_descriptor(owner, &maps.classes);
} else {
if let Some(new_name) = maps.method(owner, name, descriptor) {
*name = new_name;
}
if let Some(mapped) = maps.classes.get(owner.as_str()) {
*owner = mapped.clone();
}
}
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
/// A constant-pool reference inside code or bootstrap arguments: class
/// literals (plain or array), method types, method handles, condy payloads.
/// Anything else (numbers, strings) has no references to follow.
pub(super) fn rewrite_const(value: &mut Const, maps: &RenameMaps) {
match value {
Const::Class(name) => {
if name.starts_with('[') {
*name = rewrite_descriptor(name, &maps.classes);
} else if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
}
Const::MethodType(descriptor) => {
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
Const::MethodHandle {
owner,
name,
descriptor,
..
} => {
rewrite_method_ref(owner, name, descriptor, maps);
}
Const::Dynamic { descriptor, .. } => {
*descriptor = rewrite_descriptor(descriptor, &maps.classes);
}
_ => {}
}
}

View file

@ -1,13 +1,7 @@
//! Переписывание одного класса: имена, дескрипторы, код, атрибуты.
mod annotations;
mod code;
mod consts;
use annotations::{
rewrite_annotations, rewrite_parameter_annotations, rewrite_type_annotations, rewrite_value,
};
use consts::{rewrite_const, rewrite_method_ref};
use noxis_classfile::{Attribute, ClassFile, StackMapFrame, VerificationType};
use noxis_core::{Config, Context};
@ -140,42 +134,6 @@ fn rewrite_attributes(
}
}
}
Attribute::PermittedSubclasses(classes) => {
for name in classes.iter_mut() {
if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
}
}
Attribute::RuntimeVisibleAnnotations(annos)
| Attribute::RuntimeInvisibleAnnotations(annos) => {
rewrite_annotations(annos, maps);
}
Attribute::RuntimeVisibleParameterAnnotations(params)
| Attribute::RuntimeInvisibleParameterAnnotations(params) => {
rewrite_parameter_annotations(params, maps);
}
Attribute::RuntimeVisibleTypeAnnotations(annos)
| Attribute::RuntimeInvisibleTypeAnnotations(annos) => {
rewrite_type_annotations(annos, maps);
}
Attribute::AnnotationDefault(value) => rewrite_value(value, maps),
Attribute::BootstrapMethods(methods) => {
for bsm in methods.iter_mut() {
rewrite_method_ref(&mut bsm.owner, &mut bsm.name, &mut bsm.descriptor, maps);
for arg in bsm.args.iter_mut() {
rewrite_const(arg, maps);
}
}
}
Attribute::EnclosingMethod { class, method } => {
if let Some((name, descriptor)) = method.as_mut() {
rewrite_method_ref(class, name, descriptor, maps);
}
if let Some(mapped) = maps.classes.get(class.as_str()) {
*class = mapped.clone();
}
}
Attribute::LocalVariableTable(vars) => {
for var in vars.iter_mut() {
var.descriptor = rewrite_descriptor(&var.descriptor, &maps.classes);

Some files were not shown because too many files have changed in this diff Show more