Compare commits

...

26 commits

Author SHA1 Message Date
1ebbca10fa
analysis: lock mixin classes and plugin again (revert mixin rename)
Renaming mixin classes and patching mixins.json (90506a4) breaks Fabric
mods at runtime, proven on LoVisual (2026-10-13):

- When obfuscated packages are randomized per class the config patcher
  computes an empty common prefix and writes `package: ""`. Fabric/Mixin
  then drops every mixin as "orphaned", so `RenderPipelineMixin
  implements IRenderPipeline` never applies, the interface is not
  injected into `RenderPipeline`, and the entrypoint dies with
  `ClassCastException: RenderPipeline cannot be cast to IRenderPipeline`.
- `IMixinConfigPlugin.shouldApplyMixin` compares the runtime mixin class
  name against string literals (`Set.of("dev.loki...Mixin")`); renaming
  desyncs those sets and optional sodium/iris/xaero mixins get applied
  when the target mod is absent.

Re-enable absorb_mixins: mixin entry classes and the config plugin keep
their names, and locking a class freezes its members too (needed for
@Accessor/@Invoker/@Overwrite name lookups). Calls from locked mixin
bytecode are still rewritten consistently, and the family mechanism keeps
interface method names (IRenderPipeline) in sync with the frozen mixin
methods. patch_mixins_json stays but is identity for locked classes.

Verified: LoVisual obf jar loads all 221 mixins (0 orphaned), the main
menu renders, the entrypoint runs.
2026-10-13 13:18:13 +02:00
01afa6af37
jar: pass module-info.class through as a raw resource
JPMS descriptors are never loaded by a class loader; parsing one and
rebuilding its pool left the unmodeled Module attribute with stale
indices, and ASM died in readModule on the rewritten jar (caught by the
ASM probe on Loreport, which ships META-INF/versions module-infos).
Byte-for-byte resource passthrough keeps the descriptor valid.
2026-10-13 10:23:19 +02:00
15cd31252e
classfile,passes: model RuntimeVisibleTypeAnnotations and AnnotationDefault
Type annotations (method- and code-level) and annotation defaults were
passed through as Raw bytes with the original pool indices; the writer
rebuilds the pool, so those indices pointed at the wrong utf8 or past
the pool end. HotSpot tolerates the garbage (lazy reflection parsing),
but ASM's ClassReader dies with ArrayIndexOutOfBoundsException while
Paper's plugin converter reads every method - 76 of 275 LoParkour
classes failed to convert. Target_info and type_path carry no pool
references and stay opaque bytes; type descriptors and element values
are modeled and rewritten by rename like plain annotations.
2026-10-13 10:17:10 +02:00
3f92b72c8b
remove stray luac.out 2026-10-12 14:19:46 +02:00
90506a4736
passes: rename mixin classes + patch mixins.json/refmap like OBF
- Remove absorb_mixins keep rule (mixin classes now renameable)
- Add mixins.rs: patch_mixins_json rewrites package + entries via
  common prefix of mapped names; patch_refmap_json rewrites all strings
- Resources pass routes *.mixins.json and *refmap.json to specialized
  patchers, falls back to generic text remap

Reference: OBF fabric-obfuscator patchMixinsJson/patchRefmapJson.
2026-10-12 14:18:19 +02:00
b73c72d56d
classfile: model RuntimeVisible/InvisibleParameterAnnotations (fixes ASM AIOOBE on write)
Parameter annotations were unmodeled and fell through to Raw with stale
constant-pool indices after the pool rebuild. ASM (Paper converter, Fabric
mixin transformer) then failed with ArrayIndexOutOfBoundsException in
readParameterAnnotations. Now parsed and rewritten like class-level
annotations.
2026-10-12 13:19:12 +02:00
045cd3ed9c
passes: gate step-2 renames on the virtual family index (fixes override-chain split) 2026-10-12 10:38:55 +02:00
2069aa6646
analysis: drop shaded-package lock heuristic (superseded by the family-split fix) 2026-10-12 10:38:55 +02:00
3709d3ad35
analysis: lock shaded reflective packages (gson TypeAdapter-style dispatch) 2026-10-11 13:42:08 +02:00
48a5bc23a9
classfile,passes: model runtime-visible annotations, rewrite their descriptors 2026-10-11 13:02:26 +02:00
4b14eeb40f
classfile: writer honors itf flag for invokestatic on interfaces 2026-10-11 12:24:50 +02:00
5901c9eb69
passes: rename rewrites EnclosingMethod and array-owner method refs 2026-10-11 11:22:11 +02:00
8fcecee849
passes: rename rewrites invokedynamic descriptors and BootstrapMethods refs 2026-10-11 10:34:42 +02:00
9a33cef9b1
classfile,passes,jar: model PermittedSubclasses, normalize interface flags, name class in write errors 2026-10-10 14:22:03 +02:00
e9d5e44b9e
verify,cli: jadx decompile-quality metric with analyze --decompile 2026-10-10 13:32:23 +02:00
2655f83d3c
passes: generic signatures rewrite nested references; rename tests split 2026-10-10 13:13:58 +02:00
63630dd223
frames: JDK hierarchy fallback, array-operand rewrite, aaload fixes; LoVisual 131 to 0 FAIL 2026-10-10 13:00:58 +02:00
1c417f596c
classfile: aaload on 1-dim ref arrays yields element type; passes: minimizer example 2026-10-10 11:47:06 +02:00
21a7c3df1a
analysis: keep-lock mixin classes and plugins from mixins.json configs 2026-10-10 10:02:38 +02:00
6a68c9d69b
passes,core: debug fakes - line numbers and source removal
DebugConfig gains fake_line_numbers (deterministic upward walk
replacing LineNumberTable rows when stripping is off; strip wins)
and strip_source_file (drops SourceFile entirely, beating spoof).
Debug tests moved to passes/tests/debug_info.rs with new cases
for both flags and their precedence.
2026-10-09 14:08:08 +02:00
2cbb9db31e
passes: junk classes with real bodies and no fingerprint
NoisePass now builds branching helper methods (counted int loop,
random arithmetic, even/odd merge, non-throwing ops only) whose
results the entry sums into a private static field, instead of an
empty run()V. Names come from the same NameGenerator styles as
real code and live in a random real package (no more shadow/decoy
uniformity for grep to catch); every generated method gets fresh
StackMapTable frames. weave_first_reachable takes (class, entry)
pairs. New NoiseConfig.junk_methods_per_class (default 3).

Tests assert invariants (unique valid identifiers, calls, field
store, determinism) plus real-JVM verification of junk classes;
paranoid+junk_ratio=1 smoke on lorep: 18 junk classes, all load.
2026-10-09 14:04:24 +02:00
74ad4552e4
analysis,verify: databind field lock and locked-class share
KeepRules::absorb_databind finds X.class literals before Gson /
Jackson / fastjson2 / Moshi calls and locks every field of X
(reflection-bound names never reach the string-based detection).
The class itself still renames. Test in analysis/tests/dto.rs;
keep unit tests moved to tests/keep.rs.

ProgramStats gains locked_classes + locked_share() so analyst-bait
source names are loud in the report instead of surfacing later.
2026-10-09 13:53:30 +02:00
c3acc0baf4
analysis: lock DTO fields passed as X.class to databind calls
Gson/Jackson/fastjson2/Moshi bind fields by reflection from a Class
literal, with no field-name string for the string-based detection:
renaming such a field silently breaks deserialization. Absorb_databind
finds the nearest Const::Class before fromJson/readValue/parseObject/
adapter calls (10-insn window, control-flow boundaries stop the search)
and keeps every field of that class; the class itself still renames.

Tests: noxis-analysis/tests/dto.rs (red first), keep unit tests moved
to tests/keep.rs (file budget). Code comments migrated to English.
2026-10-09 13:51:35 +02:00
139aea9a8f
frames,jar,passes: verifier-driven hardening from real jars
Proven by paranoid runs over lorep (17 classes, fully green),
LoVisual (4081 classes) and oc2r (1278 classes) with per-class
java -Xverify:all, each fix first reproduced as a red test:

- merge: Top absorbs instead of Top-wins (javac declares Top for
  slots unwritten on some inflow; precise types reject those edges).
  Regression: loop_head_keeps_top_for_loop_local.
- emit: collapse [Long|Double, Top] pairs on operand stacks
  (javac writes one entry; the pair is rejected). Regression:
  wide_stack_join_emits_single_entries.
- xfer ArrayLoad: push the wide pair, fixing lcmp underflow.
  Regression: array_load_wide_pushes_pair.
- xfer <init>: convert only the receiver's own allocation site
  instead of every Uninitialized (nested construction clobbered
  the outer object). Regression: nested_construction_keeps_outer.
- xfer ANewArray: array operands gain one dimension ([B] -> [[B)
  instead of an illegal L-wrap ([L[B;). Covered by the same test.
- jar load: duplicate class names (multi-release module-info
  twins) keep the first occurrence instead of crashing save.
  Test: duplicate_class_names_keep_first.
- strings/constants: skip methods past MAX_METHOD_INSNS (8000)
  so giants cannot overflow the 64KB writer ceiling. Tests:
  oversized_methods_are_skipped in both passes.
- merge errors now name both types being merged.

Also: em-dash removed repo-wide (724 spots, rule added to
todo.md), allow-lints only in tests (scratch example deleted),
code comments migrated to English in every file this change
touches.
2026-10-09 13:47:27 +02:00
2172206e83
passes: implement control-flow pass (4 schemes + rotation)
FlowPass rebuilds one method per scheme picked from FlowConfig:
state-spread (dense tableswitch dispatcher), computed-switch
(sparse lookupswitch over a counter local), butterfly (branch
inversion), exception-goto (dispatcher under try with a dead
catch-all), plus opaque goto-splices inside every method and
StackMapTable recomputation afterwards. Now in standard_pipeline
(between constants and noise); --no-flow is an honest off-flag.

Acceptance is real JVM, not shapes: per-scheme verify, rotation
spread, calc-prints-45 execution, paranoid smoke on lorep-1.1.0
(131 methods rebuilt, no new failures over standard).

Two verifier rules learned the hard way are now construction
invariants: no inserted mark shares a bytecode offset with a
foreign one (nop pads), and no frameless gap follows a terminal
(dead blocks are opaque-entered and throw).

Also fixes a latent frame-emitter bug the pass exposed: wide
stack values were written as slot pairs ([Double, Top]) while
javac writes one entry ([Double]); HotSpot rejects the pair.
Stacks now collapse like locals (emit::stack_vars), with a
regression test in classfile/tests/frames.rs.
2026-10-09 11:11:55 +02:00
39178420e4
structure-check: gate counts code lines, docs and comments in English
Gate ignores blank and full-line comment lines so the 250-line limit
measures code bulk, not documentation weight; docs/README.md synced.
Translate code comments to English in classfile, core config, namegen,
rename assign, constants forms. Expand Plausible word bank with
client-ecosystem terms (Module, Setting, Mixin, ...). cargo fmt clean,
check.sh green.
2026-10-09 10:31:02 +02:00
147 changed files with 7762 additions and 1802 deletions

2
Cargo.lock generated
View file

@ -310,6 +310,7 @@ dependencies = [
"noxis-core",
"noxis-structure-check",
"regex",
"serde_json",
"thiserror",
"tracing",
]
@ -355,6 +356,7 @@ dependencies = [
"noxis-core",
"noxis-runtime",
"noxis-structure-check",
"serde_json",
"thiserror",
"tracing",
]

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 (кадры готовы, схем флаттенинга пока нет) | 🚧 |
| пасс flow (кадры готовы, 4 схемы: state-spread, computed-switch, butterfly, exception-goto) | ✅ |
Подробности в [`docs/architecture.md`](docs/architecture.md), план в [`todo.md`](todo.md).
@ -50,12 +50,8 @@ cargo run -p noxis -- patterns --input output.jar
```
`obfuscate` по умолчанию включает все готовые пассы. Флаги `--no-rename`,
`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`
выключают их по отдельности. `--no-flow` честно падает с ошибкой: пасса пока нет.
Одно `cargo build` уже гоняет проверку структуры кода: `.rs`-файл длиннее
250 строк или директория с больше чем 4 `.rs`-файлами ломают сборку.
Документация (`docs/**`) под это правило не попадает. Правила в [`docs/README.md`](docs/README.md).
`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`,
`--no-flow` выключают их по отдельности.
## Структура

View file

@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
regex = { workspace = true }
serde_json = { workspace = true }
noxis-classfile = { workspace = true }
noxis-core = { workspace = true }
thiserror = { workspace = true }

View file

@ -0,0 +1,34 @@
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

@ -0,0 +1,195 @@
//! JDK superclass fallback for frame merging.
//!
//! [`ClassHierarchy`] only knows program classes - deliberately so: rename
//! safety must stay conservative outside the program. Frame merging has the
//! opposite need: joins over JDK types (`Reader`/`BufferedReader`, a
//! multi-catch over `NoSuchMethodException`/`SecurityException`) degrade to
//! `Object` without the true superclass chain, and the verifier rejects the
//! poisoned frame at the first typed use (`putfield Reader`, a `Throwable`
//! parameter). This wrapper answers program classes from the built
//! hierarchy and asks the running JDK about the rest: one `java` process
//! (single-file launch, no `javac` needed), a line protocol, answers cached.
//! Without `java` every answer is `None` - exactly the old behaviour.
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use noxis_classfile::Hierarchy;
use super::hierarchy::ClassHierarchy;
const HELPER: &str = include_str!("JdkHierarchy.java");
/// Frame-time hierarchy: program first, running JDK second.
pub struct JdkHierarchy<'a> {
inner: &'a ClassHierarchy,
shared: RefCell<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

@ -0,0 +1,86 @@
//! Внешний диспатч: семейства методов, которые программный код зовёт через
//! внешние интерфейсы/классы (не из артефакта). Их нельзя переименовывать -
//! внешний вызывающий код не переписать, и JVM получит `AbstractMethodError`.
use std::collections::{BTreeSet, HashSet};
use noxis_classfile::{Insn, InvokeKind, Program};
use crate::hierarchy::ClassHierarchy;
/// Семейства `(name, params)`, которые нельзя переименовывать: программа
/// вызывает их виртуально/интерфейсно на внешнем владельце, а некоторый
/// класс в предках этого владельца (внутри артефакта) объявляет то же
/// `(name, params)`. Переименование разорвало бы диспатч через внешний
/// интерфейс/класс - JVM упала бы с `AbstractMethodError ... is abstract`
/// (реальный случай: шадоуed gson `LinkedTreeMap$EntrySet$1`, который
/// JDK `Map.forEach` зовёт через `invokeinterface Iterator.hasNext`).
pub fn external_dispatch_families(
program: &Program,
hierarchy: &ClassHierarchy,
) -> BTreeSet<(String, String)> {
let in_program: HashSet<&str> = program
.classes
.iter()
.map(|c| c.this_class.as_str())
.collect();
// Виртуальные/интерфейсные вызовы на внешнем владельце (дедуплицированно).
let mut external_calls: BTreeSet<(String, String, String)> = BTreeSet::new();
for class in &program.classes {
for method in &class.methods {
let Some(code) = &method.code else { continue };
for insn in &code.insns {
if let Insn::Invoke {
kind,
owner,
name,
descriptor,
..
} = insn
&& matches!(kind, InvokeKind::Virtual | InvokeKind::Interface)
&& !in_program.contains(owner.as_str())
&& let Some(params) = params_part(descriptor)
{
external_calls.insert((owner.clone(), name.clone(), params.to_string()));
}
}
}
}
if external_calls.is_empty() {
return BTreeSet::new();
}
// Для каждого класса - внешние предки, достижимые сквозь внутренние
// суперклассы/интерфейсы (цепочка обрывается на внешнем узле).
let mut locked: BTreeSet<(String, String)> = BTreeSet::new();
for class in &program.classes {
let mut externals: HashSet<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,12 +1,19 @@
//! Keep-правила: что нельзя переименовывать (glob-паттерны + entrypoint'ы).
//! Keep rules: what must not be renamed (glob patterns + entrypoints).
use noxis_classfile::{Attribute, Const, Program};
use std::collections::BTreeSet;
use noxis_classfile::Program;
use regex::Regex;
use crate::entrypoints::Entrypoints;
use noxis_core::Config;
/// Скомпилированный glob: `*` — любые символы кроме `/`, `**` — всё, `?` — один.
mod dispatch;
mod scans;
pub use dispatch::external_dispatch_families;
/// Compiled glob: `*` - anything but `/`, `**` - anything, `?` - one char.
fn compile(pattern: &str) -> Result<Regex, regex::Error> {
let mut out = String::from("^");
let chars: Vec<char> = pattern.chars().collect();
@ -36,19 +43,19 @@ fn compile(pattern: &str) -> Result<Regex, regex::Error> {
Regex::new(&out)
}
/// Правила «не трогать»: явные паттерны конфига + entrypoint'ы.
/// "Do not touch" rules: explicit config patterns + entrypoints.
#[derive(Debug, Default, Clone)]
pub struct KeepRules {
class_patterns: Vec<Regex>,
resource_patterns: Vec<Regex>,
/// Точные имена, которые нельзя трогать (entrypoint'ы, рефлексия, ...).
fixed: std::collections::BTreeSet<String>,
/// Имена членов, защищённые рефлексией.
fixed_members: std::collections::BTreeSet<String>,
/// Exact names to keep (entrypoints, reflection, ...).
fixed: BTreeSet<String>,
/// Member names protected by reflection.
fixed_members: 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 {
@ -67,22 +74,22 @@ impl KeepRules {
Ok(Self {
class_patterns,
resource_patterns,
fixed: std::collections::BTreeSet::new(),
fixed_members: std::collections::BTreeSet::new(),
fixed: BTreeSet::new(),
fixed_members: BTreeSet::new(),
})
}
/// Запретить переименование члена с таким именем (в любом классе).
/// Forbid renaming a member with this name (in any class).
pub fn keep_member(&mut self, name: impl Into<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());
}
/// Объединить с найденными entrypoint'ами.
/// Absorb found entrypoints.
pub fn absorb(&mut self, entrypoints: &Entrypoints) {
for name in &entrypoints.main_classes {
self.keep_exact(name.clone());
@ -104,30 +111,7 @@ impl KeepRules {
}
}
/// Методы, на которые ссылаются `BootstrapMethods` (`invokedynamic`).
///
/// Переименование такого метода без правки bootstrap-записи ломает класс,
/// а правка — задача P2 (см. `todo.md`): пока просто не трогаем имена.
pub fn absorb_bootstrap(&mut self, program: &Program) {
for class in &program.classes {
for method in &class.methods {
for attr in &method.attributes {
if let Attribute::BootstrapMethods(methods) = attr {
for bsm in methods {
self.keep_member(bsm.name.clone());
for arg in &bsm.args {
if let Const::MethodHandle { name, .. } = arg {
self.keep_member(name.clone());
}
}
}
}
}
}
}
}
/// Нужно ли оставить класс с данным внутренним именем.
/// Whether the class with this internal name stays.
pub fn keeps_class(&self, internal_name: &str) -> bool {
self.fixed.contains(internal_name)
|| self
@ -136,17 +120,17 @@ impl KeepRules {
.any(|re| re.is_match(internal_name))
}
/// Нужно ли оставить член с таким именем (не переименовывать).
/// Whether a member with this name stays (is not renamed).
pub fn keeps_member(&self, name: &str) -> bool {
self.fixed_members.contains(name)
}
/// Нужно ли оставить ресурс с данным путём.
/// Whether the resource at this path stays unrewritten.
pub fn keeps_resource(&self, path: &str) -> bool {
self.resource_patterns.iter().any(|re| re.is_match(path))
}
/// Число правил (для отчёта).
/// Rule count (for the report).
pub fn len(&self) -> usize {
self.class_patterns.len()
+ self.resource_patterns.len()
@ -154,35 +138,37 @@ impl KeepRules {
+ self.fixed_members.len()
}
/// Есть ли вообще правила.
/// Whether there are any rules at all.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Ошибка компиляции паттерна.
/// A pattern compilation error.
#[derive(Debug, thiserror::Error)]
pub enum RuleError {
#[error("некорректный паттерн `{pattern}`: {msg}")]
#[error("malformed pattern `{pattern}`: {msg}")]
Pattern { pattern: String, msg: String },
}
/// Полный анализ перед обфускацией.
/// The full pre-obfuscation analysis.
#[derive(Debug, Clone)]
pub struct Analysis {
pub entrypoints: Entrypoints,
pub keep: KeepRules,
/// Классы, которые не переименовываются.
pub locked_classes: std::collections::BTreeSet<String>,
/// Classes that are not renamed.
pub locked_classes: 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
@ -198,40 +184,8 @@ impl Analysis {
})
}
/// Класс запрещено переименовывать.
/// Renaming this class is forbidden.
pub fn is_locked(&self, internal_name: &str) -> bool {
self.locked_classes.contains(internal_name)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::*;
#[test]
fn glob_semantics() {
let rules = KeepRules {
class_patterns: vec![
compile("com/example/*").unwrap(),
compile("**/internal/**").unwrap(),
],
resource_patterns: vec![compile("META-INF/services/*").unwrap()],
fixed: std::collections::BTreeSet::new(),
fixed_members: std::collections::BTreeSet::new(),
};
assert!(rules.keeps_class("com/example/Main"));
assert!(!rules.keeps_class("com/example/sub/Main"));
assert!(rules.keeps_class("x/internal/y/Z"));
assert!(rules.keeps_resource("META-INF/services/a.b.C"));
assert!(!rules.keeps_resource("assets/mc/mod.json"));
}
#[test]
fn exact_names_win() {
let mut rules = KeepRules::default();
rules.keep_exact("app/Main");
assert!(rules.keeps_class("app/Main"));
assert!(!rules.keeps_class("app/Other"));
}
}

View file

@ -0,0 +1,204 @@
//! Program scans feeding keep rules: bootstrap methods, databind literals, mixins.
use noxis_classfile::{Attribute, Const, Insn, Program};
use super::KeepRules;
impl KeepRules {
/// Methods referenced by `BootstrapMethods` (`invokedynamic`).
///
/// Renaming such a method without patching the bootstrap record breaks
/// the class, and patching is a P2 task (see `todo.md`): keep the names.
pub fn absorb_bootstrap(&mut self, program: &Program) {
for class in &program.classes {
for method in &class.methods {
for attr in &method.attributes {
if let Attribute::BootstrapMethods(methods) = attr {
for bsm in methods {
self.keep_member(bsm.name.clone());
for arg in &bsm.args {
if let Const::MethodHandle { name, .. } = arg {
self.keep_member(name.clone());
}
}
}
}
}
}
}
}
/// Lock every Mixin class (and the plugin) listed in the configs.
///
/// The Mixin framework resolves mixin classes and their members by name
/// at runtime, so renaming them breaks the mod at startup. Locking the
/// class also freezes its members (locked classes skip member renaming
/// entirely), which the `@Accessor`/`@Invoker`/`@Overwrite` name lookups
/// and `IMixinConfigPlugin.shouldApplyMixin` string sets both need.
///
/// Renaming mixins and patching the config was tried and reverted: when
/// obfuscated packages are randomized per class the config patcher writes
/// an empty `package`, and Fabric/Mixin drops every mixin as "orphaned"
/// (real case: injected-interface cast fails with `ClassCastException`).
/// Entries use simple names relative to `package`, which generic text
/// patching can never see - locking is the only sound answer. Mixin
/// configs are found two ways: any resource ending in `mixins.json`,
/// plus whatever `fabric.mod.json` lists.
pub fn absorb_mixins(&mut self, program: &Program) {
let mut listed: Vec<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,13 +5,15 @@
//!
//! Из этих данных пасс переименования узнаёт, **что** трогать нельзя.
//! Урок из `info/evo-weaknesses.md`: у EvoVis рефлексия по имени была
//! открытым текстом, а entrypoint'ы — в `fabric.mod.json`; здесь они
//! открытым текстом, а entrypoint'ы - в `fabric.mod.json`; здесь они
//! обязаны попадать в keep-набор автоматически.
pub mod entrypoints;
pub mod hierarchy;
pub mod jdk;
pub mod keep;
pub use entrypoints::Entrypoints;
pub use hierarchy::{ClassHierarchy, RenameSafety, method_rename_safety};
pub use keep::{Analysis, KeepRules, RuleError};
pub use jdk::JdkHierarchy;
pub use keep::{Analysis, KeepRules, RuleError, external_dispatch_families};

View file

@ -0,0 +1,70 @@
//! Databinding keep: `X.class` passed to Gson/Jackson locks the fields of `X`.
//!
//! JSON libraries bind fields by reflection from a `Class` literal, with no
//! field-name string in the bytecode for the existing string-based detection
//! to catch. Renaming such a field silently breaks deserialization, so every
//! field of the literal's class stays.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_analysis::Analysis;
use noxis_classfile::{ClassBuilder, Code, Const, Field, Insn, InvokeKind, Program, Version};
use noxis_core::Config;
/// `gson.fromJson(reader, State.class)`: `State` has a private field.
fn sample() -> Program {
let caller = Code {
max_stack: 3,
max_locals: 2,
insns: vec![
Insn::Load {
slot: 1,
kind: noxis_classfile::SlotKind::Ref,
},
Insn::Const(Const::Class("demo/State".to_string())),
Insn::Invoke {
kind: InvokeKind::Virtual,
owner: "com/google/gson/Gson".to_string(),
name: "fromJson".to_string(),
descriptor: "(Ljava/io/Reader;Ljava/lang/Class;)Ljava/lang/Object;".to_string(),
itf: false,
},
Insn::Pop,
Insn::Return(None),
],
exception_table: Vec::new(),
frames: Vec::new(),
attributes: Vec::new(),
};
let mut state = ClassBuilder::new("demo/State", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build();
state.fields.push(Field {
access_flags: 0x0002,
name: "nickname".to_string(),
descriptor: "Ljava/lang/String;".to_string(),
attributes: Vec::new(),
});
let app = ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.method_with_code(0x0009, "load", "()V", caller)
.build();
Program {
classes: vec![state, app],
resources: Vec::new(),
}
}
#[test]
fn databind_class_literal_locks_fields() {
let program = sample();
let analysis = Analysis::run(&program, &Config::default()).expect("analysis");
assert!(
analysis.keep.keeps_member("nickname"),
"DTO field must survive renaming"
);
assert!(
!analysis.keep.keeps_member("load"),
"unrelated members must still rename"
);
}

View file

@ -0,0 +1,33 @@
//! Keep-rule unit tests: globs and exact names.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_analysis::KeepRules;
use noxis_core::Config;
fn rules_with_patterns() -> KeepRules {
KeepRules::from_config(&Config {
keep: vec!["com/example/*".to_string(), "**/internal/**".to_string()],
keep_resources: vec!["META-INF/services/*".to_string()],
..Config::default()
})
.expect("patterns")
}
#[test]
fn glob_semantics() {
let rules = rules_with_patterns();
assert!(rules.keeps_class("com/example/Main"));
assert!(!rules.keeps_class("com/example/sub/Main"));
assert!(rules.keeps_class("x/internal/y/Z"));
assert!(rules.keeps_resource("META-INF/services/a.b.C"));
assert!(!rules.keeps_resource("assets/mc/mod.json"));
}
#[test]
fn exact_names_win() {
let mut rules = KeepRules::default();
rules.keep_exact("app/Main");
assert!(rules.keeps_class("app/Main"));
assert!(!rules.keeps_class("app/Other"));
}

View file

@ -0,0 +1,93 @@
//! Mixin keep: classes listed in `*.mixins.json` are locked, not renamed.
//!
//! Real-world proof (LoVisual, 2026-10-13): renaming mixin classes and
//! patching the config breaks the mod at runtime. Two independent failures:
//! 1. When obf packages are randomized per class, the config patcher writes
//! `package: ""`, and Fabric/Mixin then drops *every* mixin as "orphaned"
//! (`RenderPipelineMixin implements IRenderPipeline` never applies, so the
//! injected-interface cast fails with `ClassCastException`).
//! 2. `IMixinConfigPlugin.shouldApplyMixin` compares the runtime mixin class
//! name against string literals (`Set.of("dev.loki...Mixin")`); renaming
//! the mixins desyncs those sets and optional mixins get applied when the
//! target mod is absent.
//!
//! So mixin classes and their plugin stay under their original names, and
//! locking the class freezes its members too - which `@Accessor`/`@Invoker`/
//! `@Overwrite` name lookups require. Other program classes still rename, and
//! calls from locked mixin bytecode are rewritten consistently.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use noxis_analysis::Analysis;
use noxis_classfile::{ClassBuilder, Program, Resource, Version};
use noxis_core::Config;
const MIXINS: &str = r#"{
"package": "demo.mixin",
"plugin": "demo.mixin.Plugin",
"mixins": ["TargetMixin", "other.Helper"],
"client": ["ClientMixin"]
}"#;
const FABRIC: &str = r#"{
"id": "demo",
"mixins": ["demo.mixins.json"]
}"#;
fn sample() -> Program {
let mut program = Program {
classes: vec![
ClassBuilder::new("demo/mixin/TargetMixin", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build(),
ClassBuilder::new("demo/mixin/other/Helper", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build(),
ClassBuilder::new("demo/mixin/ClientMixin", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build(),
ClassBuilder::new("demo/mixin/Plugin", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build(),
ClassBuilder::new("demo/App", Some("java/lang/Object"))
.version(Version::JAVA_21)
.build(),
],
resources: Vec::new(),
};
program.resources.push(Resource {
path: "demo.mixins.json".into(),
data: MIXINS.as_bytes().to_vec(),
});
program.resources.push(Resource {
path: "fabric.mod.json".into(),
data: FABRIC.as_bytes().to_vec(),
});
program
}
#[test]
fn mixin_classes_and_plugin_are_locked() {
let program = sample();
let analysis = Analysis::run(&program, &Config::default()).expect("analysis");
// Mixin entry points and the config plugin are resolved by name at
// runtime and must keep their names (and, being locked, their members).
for locked in [
"demo/mixin/TargetMixin",
"demo/mixin/other/Helper",
"demo/mixin/ClientMixin",
"demo/mixin/Plugin",
] {
assert!(analysis.is_locked(locked), "{locked} should be locked");
}
}
#[test]
fn non_mixin_classes_stay_renameable() {
let program = sample();
let analysis = Analysis::run(&program, &Config::default()).expect("analysis");
// Plain program classes are not named by any mixin config.
assert!(!analysis.is_locked("demo/App"));
}

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,8 +1,9 @@
//! Эмиссия компактных кадров в точках, где их ждёт верификатор.
//! Emitting compact frames at the points where the verifier expects them.
//!
//! Вид кадра выбирается сравнением с предыдущим кадром (`Same`/`Append`/
//! `Chop`/`SameLocals`, иначе `Full`) — как у `javac`. Хвостовые `Top`
//! при сравнении и записи отрезаются: пустой слот — не тип.
//! A frame's kind is chosen by comparing with the previous frame
//! (`Same`/`Append`/`Chop`/`SameLocals`, otherwise `Full`) - like `javac`.
//! Trailing `Top`s are trimmed both when comparing and when writing: an empty
//! slot is not a type.
use std::collections::BTreeSet;
@ -11,10 +12,10 @@ use super::xfer::State;
use super::{StackMapFrame, VerificationType};
use crate::error::ClassfileError;
/// Кадры во всех точках `targets` (отсортированы — дельты по порядку).
/// Frames at every point in `targets` (sorted - deltas in order).
///
/// Дельты — в номерах инструкций (как backend после чтения); writer сам
/// пересчитает их в байты.
/// Deltas are in instruction numbers (like the backend after reading); the writer
/// recomputes them into bytes itself.
pub(super) fn emit_frames(
states: &[Option<State>],
targets: &BTreeSet<u32>,
@ -34,7 +35,7 @@ pub(super) fn emit_frames(
Some(previous) => target
.checked_sub(previous)
.and_then(|delta| delta.checked_sub(1))
.ok_or_else(|| merger.invalid("кадры не по порядку"))?,
.ok_or_else(|| merger.invalid("frames out of order"))?,
};
out.push(select(delta, &state.locals, &previous_locals, &state.stack));
previous_locals = state.locals.clone();
@ -49,17 +50,21 @@ fn select(
previous: &[VerificationType],
stack: &[VerificationType],
) -> StackMapFrame {
// Сравнение — на гранулярности переменных (`long` — одна запись,
// как у `javac`): иначе половины пар дают `Append{[Top, Long]}`.
// Comparison is at variable granularity (`long` - one entry, like `javac`);
// otherwise halves would produce `Append{[Top, Long]}`.
let current = vars(locals);
let base = vars(previous);
// The operand stack needs the same collapsing: a `long`/`double` is one
// entry (`javac` writes `[Double, Integer]`, not `[Double, Top, Integer]`);
// an explicit half without its value is rejected by HotSpot.
let stack = stack_vars(stack);
if current == base {
if stack.is_empty() {
return StackMapFrame::Same {
offset_delta: delta,
};
}
if let [local] = stack {
if let [local] = stack.as_slice() {
return StackMapFrame::SameLocals {
offset_delta: delta,
local: local.clone(),
@ -93,10 +98,34 @@ fn select(
}
}
/// Слоты → переменные: `[Long, Top]` — одна запись; хвостовые `Top` — прочь.
/// Stack entries → values: `[Double, Top]` - one entry (like `javac`).
///
/// Одиночные `Top` внутри (дыры) сохраняются: в `Full` это легальный тип,
/// а в `Append` мы их не пускаем (см. `select`).
/// Unlike [`vars`], no trailing-`Top` trimming: every stack entry is live by
/// construction, and dropping one would corrupt the depth.
fn stack_vars(stack: &[VerificationType]) -> Vec<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`).
fn vars(locals: &[VerificationType]) -> Vec<VerificationType> {
let mut out = Vec::with_capacity(locals.len());
let mut index = 0;

View file

@ -1,4 +1,4 @@
//! CFG тела метода: метки, рёбра, точки кадров, диапазоны handler'ов.
//! A method body's CFG: labels, edges, frame points, handler ranges.
use std::collections::{BTreeMap, BTreeSet};
@ -7,7 +7,7 @@ use crate::error::ClassfileError;
use crate::insn::{Insn, Label};
use crate::model::ExceptionHandler;
/// Метки → номера инструкций без маркеров.
/// Labels → instruction numbers, without the markers.
pub(super) fn strip_marks<'a>(
insns: &'a [Insn],
merger: &Merger<'_>,
@ -31,7 +31,7 @@ pub(super) fn strip_marks<'a>(
Ok((labels, bare))
}
/// Рёбра CFG без исключений: продолжение + цели переходов.
/// CFG edges without exceptions: fallthrough + branch targets.
pub(super) fn successors(
insn: &Insn,
index: u32,
@ -40,8 +40,8 @@ pub(super) fn successors(
merger: &Merger<'_>,
) -> Result<Vec<u32>, ClassfileError> {
let mut out = Vec::new();
// Без продолжения: переходы без возврата и выходы из метода.
// `Jsr`/`Ret` сюда не доходят (их отвергает `transfer`), но рёбра есть.
// No fallthrough: jumps that don't return and method exits.
// `Jsr`/`Ret` never reach here (rejected by `transfer`), but the edges exist.
let terminal = matches!(
insn,
Insn::Goto(..)
@ -67,7 +67,7 @@ pub(super) fn successors(
Ok(out)
}
/// Точки, где верификатор требует кадры: цели переходов + входы handler'ов.
/// Points where the verifier requires frames: branch targets + handler entries.
pub(super) fn frame_targets(
bare: &[&Insn],
labels: &BTreeMap<Label, u32>,
@ -91,12 +91,12 @@ pub(super) fn frame_targets(
Ok(targets)
}
/// Точка handler'а в номерах инструкций: `(start, end, handler, тип перехвата)`.
/// A handler point in instruction numbers: `(start, end, handler, catch type)`.
///
/// Диапазоны полуоткрытые `[start, end)`, как в JVMS.
/// Ranges are half-open `[start, end)`, as in the JVMS.
pub(super) type HandlerRange = (u32, u32, u32, Option<String>);
/// Handler'ы в номерах инструкций для рёбер исключений.
/// Handlers in instruction numbers, for exception edges.
pub(super) fn handler_ranges(
table: &[ExceptionHandler],
labels: &BTreeMap<Label, u32>,

View file

@ -1,12 +1,12 @@
//! Разбор дескрипторов типов (`(...)V`, `[L...;`).
//! Descriptor parsing (`(...)V`, `[L...;`).
use super::super::VerificationType;
/// Ошибка разбора дескриптора (контекст добавляет вызывающий код).
/// Descriptor parse error (context is added by the caller).
#[derive(Debug)]
pub(crate) struct DescError(pub String);
/// Уложить слоты значения в locals с позиции; вернуть следующую позицию.
/// Write value slots into `locals` at position; return next position.
pub(crate) fn write_local(
locals: &mut [VerificationType],
slot: usize,
@ -22,7 +22,7 @@ pub(crate) fn write_local(
Ok(slot + width)
}
/// Разобрать дескриптор массива на (глубина, элемент без `;`).
/// Parse an array descriptor into (depth, element without `;`).
pub(crate) fn split_array(descriptor: &str) -> Option<(usize, &str)> {
let dims = descriptor.bytes().take_while(|&b| b == b'[').count();
if dims == 0 {
@ -31,7 +31,7 @@ pub(crate) fn split_array(descriptor: &str) -> Option<(usize, &str)> {
Some((dims, descriptor[dims..].trim_end_matches(';')))
}
/// Слоты одного полевого дескриптора (`long`/`double` — парой с `Top`).
/// Slots for a single field descriptor (`long`/`double` - pair with `Top`).
pub(crate) fn field_slots(descriptor: &str) -> Result<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
}
}
/// Слоты параметров и возврата (`None` — `void`).
/// Parameter and return slots (`None` - `void`).
type MethodSlots = (Vec<Vec<VerificationType>>, Option<Vec<VerificationType>>);
/// Дескриптор метода: слоты параметров и слоты возврата (`None` — `void`).
/// Method descriptor: parameter slots and return slots (`None` - `void`).
pub(crate) fn method_slots(descriptor: &str) -> Result<MethodSlots, DescError> {
let (params, ret) = descriptor
.split_once('(')
@ -128,24 +128,43 @@ 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(format!("[{elem};")),
_ => VerificationType::Object(
elem.strip_prefix('L')
.unwrap_or("java/lang/Object")
.to_string(),
),
};
}
match kind {

View file

@ -1,12 +1,12 @@
//! Слияние типов (LUB) и разбор дескрипторов.
//! Type merging (LUB) and descriptor parsing.
//!
//! Решётка: `Top` — «пусто» (берётся сосед), `Null` впитывается в ссылку,
//! одинаковые — сами в себя, ссылки — наименьший общий предок по иерархии.
//! Несочетаемые инициализированные типы (`int` vs ссылка после `astore`
//! в handler'е) дают `Top`, как обрезанные кадры `javac`: `Top` в кадре
//! принимает любое фактическое значение, поэтому это всегда sound.
//! Исключение — неинициализированные типы: их слияние означает сломанный
//! поток конструирования, здесь честная ошибка, а не молчаливый `Top`.
//! The lattice: `Top` absorbs (a slot unwritten on any inflow stays `Top`,
//! like `javac` - a precise type would reject the inflow that never wrote
//! it). `Null` is absorbed into a reference, equal types map to themselves,
//! references take the least upper bound over the hierarchy. Incompatible
//! initialized types (`int` vs a reference) yield `Top`. The exception is
//! uninitialized types: merging them means a broken construction flow -
//! here an honest error, not a silent `Top`.
pub(super) mod descs;
@ -17,13 +17,13 @@ use crate::model::Method;
use descs::write_local;
/// Иерархия классов для LUB: достаточно цепочки суперклассов.
/// The class hierarchy for LUB: the superclass chain is enough.
pub trait Hierarchy {
/// Прямой суперкласс (`None` — `java/lang/Object` или неизвестный).
/// The direct superclass (`None` - `java/lang/Object` or unknown).
fn superclass(&self, class: &str) -> Option<String>;
}
/// Контекст слияния: имена для ошибок + иерархия для LCA.
/// Merge context: names for errors + hierarchy for LCA.
pub(super) struct Merger<'h> {
pub class: String,
pub method: String,
@ -38,7 +38,7 @@ impl Merger<'_> {
}
}
/// Влить входящее состояние; `true` — слот изменился.
/// Merge an incoming state; `true` - the slot changed.
pub fn merge_into(
&self,
slot: &mut Option<State>,
@ -61,7 +61,7 @@ impl Merger<'_> {
}
}
/// Начальное состояние: параметры (+ `this`) поверх `Top`.
/// The initial state: parameters (+ `this`) over `Top`.
pub fn initial(&self, method: &Method, max_locals: u16) -> Result<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("параметры не влезают в locals"))?;
.map_err(|_| self.invalid("parameters do not fit into locals"))?;
}
for param in params {
slot = write_local(&mut locals, slot, param)
.map_err(|_| self.invalid("параметры не влезают в locals"))?;
.map_err(|_| self.invalid("parameters do not fit into locals"))?;
}
Ok(State {
locals,
@ -89,10 +89,10 @@ impl Merger<'_> {
fn lub_states(&self, first: &State, second: &State) -> Result<State, ClassfileError> {
if first.locals.len() != second.locals.len() {
return Err(self.invalid("разная длина locals при слиянии"));
return Err(self.invalid("locals length differs across the merge"));
}
if first.stack.len() != second.stack.len() {
return Err(self.invalid("разная глубина стека при слиянии"));
return Err(self.invalid("stack depth differs across the merge"));
}
Ok(State {
locals: first
@ -120,26 +120,31 @@ impl Merger<'_> {
return Ok(first.clone());
}
match (first, second) {
(Top, other) | (other, Top) => Ok(other.clone()),
// A slot unwritten on any inflow stays `Top` (like `javac`): the
// frame keeps accepting every inflow, while a precise type would
// reject the one that never wrote the slot.
(Top, _) | (_, Top) => Ok(Top),
(Null, other @ Object(_)) | (other @ Object(_), Null) => Ok(other.clone()),
(Null, Null) => Ok(Null),
(Integer, Integer) | (Float, Float) | (Long, Long) | (Double, Double) => {
Ok(first.clone())
}
(Object(a), Object(b)) => Ok(Object(self.common_superclass(a, b))),
// Одинаковые уже разобраны выше; здесь неинициализированные
// всегда разные — это сломанный поток конструирования.
// Equal ones are handled above; here uninitialized are always
// different - that's a broken construction flow.
(VerificationType::UninitializedThis | VerificationType::Uninitialized(_), _)
| (_, VerificationType::UninitializedThis | VerificationType::Uninitialized(_)) => {
Err(self.invalid("слияние неинициализированных типов"))
Err(self.invalid(&format!(
"merging uninitialized types ({first:?} with {second:?})"
)))
}
// Несочетаемые инициализированные (например, `int` из тела `try`
// и `Throwable` из handler'а в одном слоте): `Top`, как у `javac`.
// Incompatible initialized (e.g. `int` from the `try` body and
// `Throwable` from a handler in one slot): `Top`, like `javac`.
_ => Ok(Top),
}
}
/// Наименьший общий предок: подъём по цепочкам, запасной — `Object`.
/// Least common ancestor: climb the chains, fallback - `Object`.
fn common_superclass(&self, first: &str, second: &str) -> String {
if first == second {
return first.to_string();
@ -176,7 +181,7 @@ impl Merger<'_> {
"java/lang/Object".to_string()
}
/// LCA массивов: та же размерность + LCA элементов, иначе `Object`.
/// Arrays' LCA: same dimensionality + element LCA, otherwise `Object`.
fn array_lca(&self, first: &str, second: &str) -> String {
let (dims_a, elem_a) = descs::split_array(first).unwrap_or((0, first));
let (dims_b, elem_b) = descs::split_array(second).unwrap_or((0, second));

View file

@ -1,12 +1,12 @@
//! `StackMapTable`: представление фреймов и вычисление после трансформаций.
//! `StackMapTable`: frame representation and computation after transformations.
//!
//! Фреймы — самая дорогая часть любого обфускатора на Rust: JVM-верификатор
//! (class version ≥ 50) требует точного `StackMapTable`, иначе класс не грузится.
//! Варианты реализации и их цены — `docs/stack.md`.
//! Frames are the most expensive part of any Rust obfuscator: the JVM verifier
//! (class version ≥ 50) demands an exact `StackMapTable`, or the class won't load.
//! Implementation options and their costs - `docs/stack.md`.
//!
//! Метод: CFG по меткам → worklist с типами (`xfer`) → слияние LUB (`merge`)
//! → эмиссия компактных кадров (`emit`). Байтовые смещения берутся тем же
//! преобразованием, что использует writer, — иначе кадры разъедутся с байтами.
//! Method: CFG over labels → worklist with types (`xfer`) → LUB merge (`merge`)
//! → emit compact frames (`emit`). Byte offsets come from the same encoding the
//! writer uses - otherwise frames would drift apart from the bytes.
mod emit;
mod flow;
@ -27,7 +27,7 @@ pub use merge::Hierarchy;
use merge::Merger;
use xfer::{State, transfer};
/// Тип верификации из JVMS §4.10.1.
/// A verification type from JVMS §4.10.1.
#[derive(Debug, Clone, PartialEq)]
pub enum VerificationType {
Top,
@ -37,14 +37,14 @@ pub enum VerificationType {
Long,
Null,
UninitializedThis,
/// Внутреннее имя класса (`java/lang/Object`) или дескриптор массива.
/// The class's internal name (`java/lang/Object`) or an array descriptor.
Object(String),
/// Байтовое смещение инструкции `new`.
/// The byte offset of the `new` instruction.
Uninitialized(u16),
}
impl VerificationType {
/// Тип, соответствующий примитиву.
/// The type matching a primitive.
pub fn of_prim(p: Prim) -> Self {
match p {
Prim::Int => VerificationType::Integer,
@ -55,7 +55,7 @@ impl VerificationType {
}
}
/// Запись `StackMapTable` (JVMS §4.7.4).
/// A `StackMapTable` entry (JVMS §4.7.4).
#[derive(Debug, Clone, PartialEq)]
pub enum StackMapFrame {
Same {
@ -80,10 +80,11 @@ pub enum StackMapFrame {
},
}
/// Вычислить фреймы для тела метода после всех трансформаций.
/// Compute the frames for a method body after all transformations.
///
/// Кадры нужны только классам версии ≥ 50; `jsr`/`ret` отвергаются (такие
/// классы старше и кадры им не нужны). Иерархия — для LUB ссылочных типов.
/// Frames are needed only for version ≥ 50 classes; `jsr`/`ret` are rejected
/// (such classes are older and need no frames). The hierarchy is for the LUB of
/// reference types.
pub fn compute_frames(
class: &str,
method: &Method,
@ -112,7 +113,7 @@ pub fn compute_frames(
emit::emit_frames(&states, &targets, &initial.locals, &merger)
}
/// Байтовое смещение каждой инструкции — тем же кодированием, что в writer'е.
/// The byte offset of each instruction - using the same encoding as the writer.
fn layout(
bare: &[&Insn],
labels: &BTreeMap<Label, u32>,
@ -144,7 +145,7 @@ fn layout(
.collect()
}
/// Основной цикл: состояния текут по рёбрам CFG до неподвижной точки.
/// Main loop: states flow along CFG edges to a fixed point.
fn run_worklist(
merger: &Merger<'_>,
bare: &[&Insn],
@ -187,7 +188,7 @@ fn run_worklist(
Ok(())
}
/// Влить состояние в инструкцию; `true` — изменилось, продолжить обход.
/// Merge a state into an instruction; `true` - changed, keep walking.
fn flow_into(
merger: &Merger<'_>,
states: &mut [Option<State>],
@ -218,8 +219,8 @@ fn flow_into(
Ok(())
}
/// Рёбра CFG без исключений: продолжение + цели переходов.
/// Тип исключения на входе в handler (`catch-all` — любое throwable).
/// CFG edges without exceptions: fallthrough + branch targets.
/// The exception type at a handler's entry (`catch-all` - any throwable).
fn catch_type(catch: &Option<String>) -> VerificationType {
match catch {
Some(name) => VerificationType::Object(name.clone()),

View file

@ -0,0 +1,155 @@
//! Join-shape tests: loop heads, wide array loads, nested construction.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::super::super::{StackMapFrame, VerificationType, compute_frames};
use super::super::{NoHierarchy, code_method, load_ref, store_ref};
use crate::insn::{ArrayKind, BranchCond, Cond, Const, Insn};
#[test]
fn anewarray_of_array_keeps_descriptor() {
let method = code_method(
"make",
"()Ljava/lang/Object;",
2,
1,
vec![
Insn::Mark(0),
Insn::Const(Const::Int(3)),
Insn::ANewArray("[B".to_string()),
store_ref(0),
load_ref(0),
Insn::Branch(BranchCond::Null { is_null: false }, 1),
Insn::AconstNull,
store_ref(0),
Insn::Goto(2),
Insn::Mark(1),
Insn::Mark(2),
load_ref(0),
Insn::AReturn,
],
vec![],
);
let frames = compute_frames("demo/Make", &method, &NoHierarchy).expect("frames");
assert_eq!(
frames,
vec![StackMapFrame::Append {
offset_delta: 8,
locals: vec![VerificationType::Object("[[B".to_string())],
},]
);
}
/// A loop head keeps `Top` for a slot written only inside the loop.
///
/// Inflows: entry (never wrote it) and back edge (wrote `Integer`). Like
/// `javac`, the join declares `Top`: a precise type would reject the inflow
/// that never wrote the slot (`Type top is not assignable`).
/// `aaload` on a one-dimensional reference array yields the element type.
///
/// Real-world shape (`V8ValueObject.bind` family): one join inflow carries
/// the loaded element (`Method`), the other the array itself (`Method[]`).
/// The join must declare their LUB (`Object`); declaring the array rejects
/// the element inflow (`Type ... is not assignable to ...`).
#[test]
fn aaload_on_ref_array_yields_element() {
let method = code_method(
"pick",
"([Ljava/lang/reflect/Method;)Ljava/lang/Object;",
2,
2,
vec![
Insn::Mark(0),
Insn::Const(Const::Int(0)),
Insn::Branch(BranchCond::Zero(Cond::Eq), 1),
load_ref(0),
Insn::Const(Const::Int(0)),
Insn::ArrayLoad(ArrayKind::Reference),
store_ref(1),
Insn::Goto(2),
Insn::Mark(1),
load_ref(0),
store_ref(1),
Insn::Mark(2),
load_ref(1),
Insn::AReturn,
],
vec![],
);
let frames = compute_frames("demo/Pick", &method, &NoHierarchy).expect("frames");
// The join declares locals[1]; whatever the frame kind, it must be the
// LUB (`Object`), never the array the other inflow carried.
let mut saw_join = false;
for frame in &frames {
let locals: Vec<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

@ -0,0 +1,151 @@
//! Join-shape tests: loop heads, wide array loads, nested construction.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::super::{StackMapFrame, VerificationType, compute_frames};
use super::{NoHierarchy, code_method, load, load_ref, store, store_ref};
use crate::insn::{BranchCond, Cond, Const, Insn, Prim};
mod arrays;
#[test]
fn loop_head_keeps_top_for_loop_local() {
let method = code_method(
"sum",
"()I",
2,
3,
vec![
Insn::Mark(0),
Insn::Const(Const::Int(0)),
store(0),
Insn::Const(Const::Int(0)),
store(1),
Insn::Mark(1),
load(1),
Insn::Const(Const::Int(10)),
Insn::Branch(BranchCond::Int(Cond::Ge), 2),
load(1),
store(2),
load(2),
store(0),
Insn::Iinc { index: 1, delta: 1 },
Insn::Goto(1),
Insn::Mark(2),
load(0),
Insn::Return(Some(Prim::Int)),
],
vec![],
);
let frames = compute_frames("demo/Sum", &method, &NoHierarchy).expect("frames");
assert_eq!(
frames,
vec![
StackMapFrame::Append {
offset_delta: 4,
locals: vec![VerificationType::Integer, VerificationType::Integer],
},
StackMapFrame::Same { offset_delta: 8 },
]
);
}
/// A nested construction (`new Outer(new Inner())`) initializes only the
/// inner object: the outer `Uninitialized` survives with its own offset, so
/// a later join still sees it instead of a clobbered `Object(Inner)`.
#[test]
fn nested_construction_keeps_outer_uninitialized() {
let method = code_method(
"make",
"()I",
4,
1,
vec![
Insn::Mark(0),
Insn::New("demo/Outer".to_string()),
Insn::Dup,
Insn::New("demo/Inner".to_string()),
Insn::Dup,
Insn::Invoke {
kind: crate::insn::InvokeKind::Special,
owner: "demo/Inner".to_string(),
name: "<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 @@
//! Unit-тесты `compute_frames` на синтезированном IR.
//! Unit tests for `compute_frames` on synthesized IR.
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -7,8 +7,8 @@ use crate::Hierarchy;
use crate::insn::{BranchCond, Cond, Const, Insn, Prim, SlotKind};
use crate::model::{Code, ExceptionHandler, Method};
/// Пустая иерархия: всё неизвестное — наследники `Object` (для LUB хватает).
struct NoHierarchy;
/// Empty hierarchy: everything unknown descends from `Object` (enough for LUB).
pub(super) struct NoHierarchy;
impl Hierarchy for NoHierarchy {
fn superclass(&self, _class: &str) -> Option<String> {
@ -16,7 +16,7 @@ impl Hierarchy for NoHierarchy {
}
}
fn code_method(
pub(super) fn code_method(
name: &str,
descriptor: &str,
max_stack: u16,
@ -40,7 +40,7 @@ fn code_method(
}
}
/// Ветвь → два кадра (`Same`, `SameLocals`).
/// A branch emits two frames (`Same`, `SameLocals`).
#[test]
fn branch_emits_same_frames() {
let mut method = code_method(
@ -76,7 +76,11 @@ fn branch_emits_same_frames() {
);
}
/// `try/catch`: handler получает `Full`, продолжение — `Append`.
/// `try/catch`: the handler gets `Full`, the continuation - `Same`.
///
/// Slot 1 is written only inside the handler, so the join keeps `Top` there
/// (like `javac`): a precise type would reject the inflow that never wrote
/// it (`Type top is not assignable`).
#[test]
fn handler_emits_full_frame() {
let method = code_method(
@ -115,15 +119,12 @@ fn handler_emits_full_frame() {
locals: vec![VerificationType::Integer],
stack: vec![VerificationType::Object("java/lang/Exception".to_string())],
},
StackMapFrame::Append {
offset_delta: 2,
locals: vec![VerificationType::Object("java/lang/Exception".to_string())],
},
StackMapFrame::Same { offset_delta: 2 },
]
);
}
/// Два `new` на разных ветвях нельзя слить — честная ошибка, не `Top`.
/// Two `new` on different branches cannot merge - an honest error, not `Top`.
#[test]
fn uninitialized_merge_is_rejected() {
let method = code_method(
@ -150,28 +151,37 @@ fn uninitialized_merge_is_rejected() {
],
vec![],
);
let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("слияние");
let err = compute_frames("demo/Pick", &method, &NoHierarchy).expect_err("merge");
assert!(
err.to_string().contains("неинициализированных"),
"не тот текст: {err}"
err.to_string().contains("uninitialized"),
"wrong message: {err}"
);
}
fn load(slot: u16) -> Insn {
mod joins;
pub(super) fn load(slot: u16) -> Insn {
Insn::Load {
slot,
kind: SlotKind::Int,
}
}
fn store(slot: u16) -> Insn {
pub(super) fn load_ref(slot: u16) -> Insn {
Insn::Load {
slot,
kind: SlotKind::Ref,
}
}
pub(super) fn store(slot: u16) -> Insn {
Insn::Store {
slot,
kind: SlotKind::Int,
}
}
fn store_ref(slot: u16) -> Insn {
pub(super) fn store_ref(slot: u16) -> Insn {
Insn::Store {
slot,
kind: SlotKind::Ref,

View file

@ -1,4 +1,4 @@
//! Вызовы и константы: дескрипторы, `<init>`, слоты значений.
//! Calls and constants: descriptors, `<init>`, value slots.
use super::super::VerificationType;
use super::super::merge::descs::{DescError, field_slots, method_slots};
@ -34,18 +34,12 @@ pub(super) fn invoke(
descriptor: &str,
) -> Result<(), ClassfileError> {
let (params, ret) = method_slots(descriptor).map_err(|e| context(class, method, e))?;
super::stack::pop_slots(
state,
count_slots(&params),
class,
method,
"аргументы вызова",
)?;
super::stack::pop_slots(state, count_slots(&params), class, method, "call arguments")?;
let mut receiver = None;
if kind != InvokeKind::Static {
receiver = super::stack::pop_slots(state, 1, class, method, "objectref")?.pop();
}
// `<init>` инициализирует получателя во ВСЕХ его копиях.
// `<init>` initializes the receiver in ALL its copies.
if name == "<init>" {
match receiver {
Some(VerificationType::UninitializedThis) => {
@ -55,9 +49,11 @@ pub(super) fn invoke(
&initialized(class),
);
}
Some(VerificationType::Uninitialized(_)) => {
// Only the receiver's own allocation site: an enclosing `new`
// whose `<init>` has not run yet must stay uninitialized.
Some(VerificationType::Uninitialized(offset)) => {
let fresh = VerificationType::Object(owner.to_string());
replace_uninit(state, &fresh);
replace(state, &VerificationType::Uninitialized(offset), &fresh);
}
_ => {}
}
@ -68,12 +64,12 @@ pub(super) fn invoke(
Ok(())
}
/// Число слотов всех параметров.
/// Slot count across all parameters.
pub(super) fn count_slots(params: &[Vec<VerificationType>]) -> usize {
params.iter().map(Vec::len).sum()
}
/// Заменить все вхождения типа новым (инициализация через `<init>`).
/// Replace every occurrence of a type with a new one (init via `<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 {
@ -82,15 +78,6 @@ fn replace(state: &mut State, from: &VerificationType, to: &VerificationType) {
}
}
/// Любой `Uninitialized` (кроме `this`) → тип владельца (созданный `new`).
fn replace_uninit(state: &mut State, to: &VerificationType) {
for slot in state.locals.iter_mut().chain(state.stack.iter_mut()) {
if matches!(slot, VerificationType::Uninitialized(_)) {
*slot = to.clone();
}
}
}
fn initialized(class: &str) -> VerificationType {
VerificationType::Object(class.to_string())
}
@ -115,7 +102,7 @@ pub(super) fn prim_push(prim: Prim) -> Vec<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 @@
//! Состояние типов и transfer-функции инструкций.
//! Type states and per-instruction transfer functions.
//!
//! Стек растёт вправо (`push` — в конец). `long`/`double` занимают два слота:
//! значение + `Top`. Проверяется только ФОРМА (глубина, категории), не
//! соответствие типов — неверные типы честно упадут на верификаторе JVM.
//! The stack grows right (`push` appends). `long`/`double` take two slots:
//! value + `Top`. Only the SHAPE is checked (depth, categories), not
//! type agreement - wrong types honestly fail on the JVM verifier.
pub(super) mod calls;
pub(super) mod stack;
@ -15,14 +15,14 @@ use crate::insn::{Arith, ArrayKind, BranchCond, Insn, SlotKind};
use calls::{const_slots, context, convert_shapes, count_slots, invoke, prim_push, prim_slots};
use stack::{dup, dup2, local_get, pop_slots, push, store_local, wide_push};
/// Типы locals + operand stack в одной точке программы.
/// Local types plus the operand stack at one program point.
#[derive(Debug, Clone, Default, PartialEq)]
pub(super) struct State {
pub locals: Vec<VerificationType>,
pub stack: Vec<VerificationType>,
}
/// Применить инструкцию к состоянию (на месте).
/// Apply one instruction to the state (in place).
pub(super) fn transfer(
class: &str,
method: &str,
@ -31,7 +31,11 @@ pub(super) fn transfer(
state: &mut State,
) -> Result<(), ClassfileError> {
match insn {
Insn::Mark(label) => Err(invalid(class, method, &format!("маркер {label} не снят"))),
Insn::Mark(label) => Err(invalid(
class,
method,
&format!("marker {label} was not stripped"),
)),
Insn::Nop => Ok(()),
Insn::AconstNull => push(state, vec![VerificationType::Null]),
Insn::Const(value) => {
@ -51,29 +55,29 @@ pub(super) fn transfer(
Insn::Iinc { index, .. } => {
let current = local_get(state, *index, class, method)?;
if current != VerificationType::Integer {
return Err(invalid(class, method, "iinc не по int"));
return Err(invalid(class, method, "iinc over a non-int"));
}
Ok(())
}
Insn::ArrayLoad(kind) => {
pop_slots(state, 1, class, method, "индекс массива")?;
let array = pop_slots(state, 1, class, method, "массив")?.remove(0);
push(state, vec![array_element(&array, *kind)])
pop_slots(state, 1, class, method, "array index")?;
let array = pop_slots(state, 1, class, method, "array")?.remove(0);
push(state, wide_push(array_element(&array, *kind)))
}
Insn::ArrayStore(kind) => {
let count = match kind {
ArrayKind::Long | ArrayKind::Double => 2,
_ => 1,
};
pop_slots(state, count, class, method, "значение")?;
pop_slots(state, 1, class, method, "индекс массива")?;
pop_slots(state, 1, class, method, "массив")?;
pop_slots(state, count, class, method, "value")?;
pop_slots(state, 1, class, method, "array index")?;
pop_slots(state, 1, class, method, "array")?;
Ok(())
}
Insn::Pop => {
let top = pop_slots(state, 1, class, method, "pop")?.remove(0);
if top == VerificationType::Top {
return Err(invalid(class, method, "pop половины long/double"));
return Err(invalid(class, method, "pop of a long/double half"));
}
Ok(())
}
@ -90,7 +94,7 @@ pub(super) fn transfer(
Insn::Swap => {
let mut taken = pop_slots(state, 2, class, method, "swap")?;
if taken.contains(&VerificationType::Top) {
return Err(invalid(class, method, "swap с половиной"));
return Err(invalid(class, method, "swap with a half"));
}
taken.reverse();
push(state, taken)
@ -100,7 +104,7 @@ pub(super) fn transfer(
if *op == Arith::Neg {
pop_slots(state, slots as usize, class, method, "neg")?;
} else if matches!(op, Arith::Shl | Arith::Shr | Arith::Ushr) {
// Сдвиг берёт (значение, int), а не два значения.
// A shift takes (value, int), not two values.
pop_slots(state, slots as usize + 1, class, method, "shift")?;
} else {
pop_slots(state, 2 * slots as usize, class, method, "arith")?;
@ -128,7 +132,7 @@ pub(super) fn transfer(
Insn::Jsr(_) | Insn::Ret(_) => Err(invalid(
class,
method,
"подпрограммы jsr/ret не поддерживаются",
"jsr/ret subroutines are not supported",
)),
Insn::TableSwitch { .. } | Insn::LookupSwitch { .. } => {
pop_slots(state, 1, class, method, "switch")?;
@ -192,7 +196,7 @@ pub(super) fn transfer(
ArrayKind::Int => "[I",
ArrayKind::Long => "[J",
ArrayKind::Reference => {
return Err(invalid(class, method, "newarray ссылочного типа"));
return Err(invalid(class, method, "newarray of a reference type"));
}
};
push(
@ -202,7 +206,16 @@ pub(super) fn transfer(
}
Insn::ANewArray(name) => {
pop_slots(state, 1, class, method, "anewarray")?;
push(state, vec![VerificationType::Object(format!("[L{name};"))])
// `anewarray` adds one dimension: a plain class becomes
// `[L...;`, an already-array operand (`anewarray [B` for a
// partially bound multi-dim) gains one more `[`. Wrapping an
// array operand in `L...;` (`[L[B;`) is not a class.
let descriptor = if name.starts_with('[') {
format!("[{name}")
} else {
format!("[L{name};")
};
push(state, vec![VerificationType::Object(descriptor)])
}
Insn::MultiANewArray { descriptor, dims } => {
pop_slots(state, *dims as usize, class, method, "multianewarray")?;

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,5 +1,6 @@
//! Чтение/запись бинарного формата `.class` (JVMS §4) через backend
//! `ristretto_classfile`: обзор кандидатов и решение — `docs/stack.md`.
//! Reading/writing the binary `.class` format (JVMS §4) through the
//! `ristretto_classfile` backend: candidate review and decision in
//! `docs/stack.md`.
mod frames;
mod parse;
@ -10,20 +11,21 @@ pub use frames::{Hierarchy, StackMapFrame, VerificationType, compute_frames};
use crate::error::ClassfileError;
use crate::model::ClassFile;
/// Разобрать один `.class` в [`ClassFile`].
/// Parse one `.class` into a [`ClassFile`].
pub fn parse(bytes: &[u8]) -> Result<ClassFile, ClassfileError> {
parse::class::parse_class(bytes)
}
/// Записать [`ClassFile`] в байты, включая пересчёт `Code`/`StackMapTable`.
/// Write a [`ClassFile`] to bytes, including `Code`/`StackMapTable` recompute.
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".
///
/// Это дешевле и безопаснее, чем round-trip через наш IR: нет риска потерять
/// неизвестный атрибут. Реализация зависит от решения по backend (P1).
/// This is cheaper and safer than a round-trip through our IR: no risk of
/// losing an unknown attribute. The implementation depends on the backend
/// decision (P1).
pub fn passthrough_needed(class: &ClassFile) -> bool {
class.methods.is_empty() && class.fields.is_empty()
}

View file

@ -0,0 +1,179 @@
//! Annotation attributes → IR: names instead of pool indices.
//!
//! Split out of `pool.rs`: these structures carry pool references that go
//! stale the moment the writer rebuilds the pool, so every one of them is
//! modeled (raw bytes made ASM die with `ArrayIndexOutOfBoundsException`).
use ristretto_classfile::ConstantPool;
use super::pool::{const_from, utf8};
use crate::error::ClassfileError;
use crate::insn::Const;
use crate::model::{Annotation, AnnotationValue, TypeAnnotation};
/// A list of `annotation` structures (`RuntimeVisibleAnnotations`).
pub(super) fn annos(
pool: &ConstantPool<'_>,
list: &[ristretto_classfile::attributes::Annotation],
) -> Result<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,21 +1,22 @@
//! Атрибуты backend'а → атрибуты нашего IR.
//! Backend attributes → our IR attributes.
//!
//! `BootstrapMethods`, `EnclosingMethod`, `MethodParameters` и `ConstantValue`
//! моделируются явно (в них лежат ссылки пула, переживающие пересборку);
//! остальное структурированное, но нам ненужное, уезжает в `Raw` как есть.
//! `Code` и `StackMapTable` здесь не обрабатываются — их разбирает вызывающий
//! код метода (см. `super::class`).
//! `BootstrapMethods`, `EnclosingMethod`, `MethodParameters` and `ConstantValue`
//! are modeled explicitly (they hold pool references that survive rebuilding);
//! everything else that is structured but unneeded by us goes to `Raw` as-is.
//! `Code` and `StackMapTable` are not handled here - the calling method code
//! parses them (see `super::class`).
use ristretto_classfile::ConstantPool;
use ristretto_classfile::attributes::Attribute as RtAttr;
use super::annos::{annos, element_value, params, type_annos};
use super::pool::{
class_name, const_from, is_interface, kind_code, name_and_type, ref_parts, utf8,
};
use crate::error::ClassfileError;
use crate::model::{Attribute, BootstrapMethod, InnerClass, MethodParameter, RecordComponent};
/// Один атрибут backend'а → наш атрибут (кроме `Code`/`StackMapTable`).
/// One backend attribute → our attribute (except `Code`/`StackMapTable`).
pub(super) fn convert(attr: &RtAttr, pool: &ConstantPool<'_>) -> Result<Attribute, ClassfileError> {
Ok(match attr {
RtAttr::SourceFile {
@ -47,6 +48,12 @@ 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,
@ -101,11 +108,34 @@ 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)?,
})
}
/// Несмоделированный атрибут → `Raw`: имя + байты `info` (без заголовка).
/// An unmodeled attribute → `Raw`: name + `info` bytes (without the header).
pub(super) fn raw(attr: &RtAttr) -> Result<Attribute, ClassfileError> {
let mut bytes = Vec::new();
attr.to_bytes(&mut bytes)
@ -131,7 +161,7 @@ fn inner(
})
}
/// Метод объемлющего класса (`0` — только класс, без метода).
/// The enclosing class's method (`0` - class only, no method).
fn enclosing_method(
pool: &ConstantPool<'_>,
index: u16,
@ -194,7 +224,7 @@ fn bootstrap(
})
}
/// Индекс пула, где `0` означает отсутствие значения.
/// A pool index where `0` means the value is absent.
fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)
@ -203,7 +233,7 @@ fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>,
}
}
/// Индекс `CONSTANT_Utf8`, где `0` означает отсутствие значения.
/// A `CONSTANT_Utf8` index where `0` means the value is absent.
fn optional_utf8(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)

View file

@ -1,4 +1,4 @@
//! Класс целиком: backend `ClassFile` → наш [`ClassFile`](crate::model::ClassFile).
//! The whole class: backend `ClassFile` → our [`ClassFile`](crate::model::ClassFile).
use ristretto_classfile::attributes::Attribute as RtAttr;
use ristretto_classfile::{
@ -11,7 +11,22 @@ use super::pool::{class_name, utf8};
use crate::error::ClassfileError;
use crate::model::{Attribute, ClassFile, Code, Field, Method, Version};
/// Разобрать байты `.class` в наш IR.
/// JVMS 4.1: an interface implies `ABSTRACT` and ignores `SUPER`. Some
/// compilers emit a bare `0x200` that HotSpot tolerates, but the strict
/// backend verifier rejects it on write (after widening, as `0x201`) - so
/// normalize once on parse. Interfaces are abstract by definition: no
/// behaviour changes.
fn normalize_class_flags(flags: u16) -> u16 {
const INTERFACE: u16 = 0x0200;
const SUPER: u16 = 0x0020;
const ABSTRACT: u16 = 0x0400;
if flags & INTERFACE == 0 {
return flags;
}
(flags | ABSTRACT) & !SUPER
}
/// Parse `.class` bytes into our IR.
pub(crate) fn parse_class(bytes: &[u8]) -> Result<ClassFile, ClassfileError> {
let rt = RtClass::from_bytes(bytes).map_err(|e| ClassfileError::Parse(e.to_string()))?;
let pool = &rt.constant_pool;
@ -25,7 +40,7 @@ pub(crate) fn parse_class(bytes: &[u8]) -> Result<ClassFile, ClassfileError> {
minor: rt.version.minor(),
major: rt.version.major(),
},
access_flags: rt.access_flags.bits(),
access_flags: normalize_class_flags(rt.access_flags.bits()),
this_class: class_name(pool, rt.this_class)?,
super_class: optional_class(pool, rt.super_class)?,
interfaces,
@ -99,7 +114,7 @@ fn convert_attrs(
.collect()
}
/// Индекс суперкласса, где `0` — его отсутствие (`java/lang/Object`).
/// The superclass index, where `0` means absent (`java/lang/Object`).
fn optional_class(pool: &ConstantPool<'_>, index: u16) -> Result<Option<String>, ClassfileError> {
if index == 0 {
Ok(None)

View file

@ -1,7 +1,8 @@
//! Кадры `StackMapTable` при чтении: вариант в вариант, дельты как есть.
//! `StackMapTable` frames on read: variant to variant, deltas as-is.
//!
//! Backend хранит кадры в номерах инструкций (см. `from_bytes_code_attributes`),
//! наш IR — тоже: writer сам пересчитает их в байты при `to_bytes`.
//! The backend stores frames in instruction indices (see
//! `from_bytes_code_attributes`), and so does our IR: the writer recomputes them
//! into bytes on `to_bytes`.
use ristretto_classfile::ConstantPool;
use ristretto_classfile::attributes::{StackFrame, VerificationType as RtType};
@ -10,7 +11,7 @@ use super::super::pool::class_name;
use crate::error::ClassfileError;
use crate::format::{StackMapFrame, VerificationType};
/// Кадры backend'а → наши (индексные дельты — как есть).
/// Backend frames → ours (index deltas - as-is).
pub(super) fn to_frames(
frames: &[StackFrame],
pool: &ConstantPool<'_>,
@ -66,7 +67,7 @@ fn to_frame(frame: &StackFrame, pool: &ConstantPool<'_>) -> Result<StackMapFrame
})
}
/// Единственный элемент стека кадра (`same_locals_1_stack_item`).
/// The frame's single stack element (`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()) {
@ -84,7 +85,7 @@ fn types(
values.iter().map(|value| vtype(value, pool)).collect()
}
/// Тип верификации backend'а → наш тип (имя класса берётся из constant pool).
/// Backend verification type → our type (the class name comes from the constant pool).
fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result<VerificationType, ClassfileError> {
Ok(match value {
RtType::Top => VerificationType::Top,
@ -99,7 +100,7 @@ fn vtype(value: &RtType, pool: &ConstantPool<'_>) -> Result<VerificationType, Cl
})
}
/// Тип перехвата (`0` — catch-all для `finally`/`any`).
/// The catch type (`0` - catch-all for `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.
//!
//! Backend нумерует инструкции по порядку — метки ставятся прямо на номера,
//! без байтовых смещений.
//! The backend numbers instructions in order - labels are placed directly on the
//! numbers, without byte offsets.
use std::collections::{BTreeMap, BTreeSet};
@ -11,10 +11,10 @@ use ristretto_classfile::attributes::{ExceptionTableEntry, Instruction};
use crate::error::ClassfileError;
use crate::insn::Label;
/// Номера инструкций, на которых обязана стоять метка.
/// Instruction numbers that must carry a label.
///
/// `extra` — позиции отладочных таблиц (уже номерами): вставки пассов
/// не должны оставлять их без меток.
/// `extra` - debug-table positions (already as numbers): pass insertions must
/// not leave them without a label.
pub(super) fn label_indexes(
code: &[Instruction],
exception_table: &[ExceptionTableEntry],
@ -36,7 +36,7 @@ pub(super) fn label_indexes(
Ok(indexes)
}
/// Цели ветвлений backend'а: для `if*`/`goto` — абсолютный номер, для `switch` — дельта.
/// Backend branch targets: for `if*`/`goto` an absolute number, for `switch` a delta.
fn branch_indexes(instruction: &Instruction, index: u16) -> Vec<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} мимо инструкции")))
}
/// Конец диапазона `[start, start+length)`: индекс за концом.
/// End of the range `[start, start+length)`: the index past the end.
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 @@
//! `Code` backend'а → тело метода нашего IR: метки, исключения, кадры.
//! Backend `Code` → our IR method body: labels, exceptions, frames.
//!
//! Backend уже перевёл байтовые смещения в номера инструкций — конвертеры
//! работают прямо с ними: метки ставятся на целях переходов, границах
//! try-блоков и позициях отладочных таблиц; кадры переносятся как есть
//! (индексные дельты). Позиции `LineNumberTable`/`LocalVariableTable` —
//! тоже метки, поэтому вставки пассов их не ломают (байты досчитает writer).
//! The backend already turned byte offsets into instruction indices - the
//! converters work directly with them: labels are placed on branch targets,
//! try-block boundaries and debug-table positions; frames are carried over as-is
//! (index deltas). `LineNumberTable`/`LocalVariableTable` positions are labels
//! too, so pass insertions don't break them (the writer recomputes the bytes).
mod frames;
mod labels;
@ -27,7 +27,7 @@ use crate::model::{
use frames::{catch_type, to_frames};
use labels::{assign, collect_debug_labels, label_indexes, lookup, resolve_byte, resolve_end};
/// Тело метода целиком: backend `Code` → наш [`Code`].
/// The whole method body: backend `Code` → our [`Code`].
pub(super) fn convert_code(
max_stack: u16,
max_locals: u16,
@ -150,7 +150,7 @@ pub(super) fn convert_code(
})
}
/// Байтовые смещения инструкций и длина тела метода.
/// Instruction byte offsets and the method body length.
fn layout(code: &[Instruction]) -> Result<(Vec<u16>, u16), ClassfileError> {
let mut cursor = Cursor::new(Vec::new());
let mut offsets = Vec::with_capacity(code.len());

View file

@ -1,4 +1,4 @@
//! Простые инструкции без ссылок на пул (кроме `ldc`) и без ветвлений.
//! Simple instructions with no pool references (except `ldc`) and no branches.
use ristretto_classfile::ConstantPool;
use ristretto_classfile::attributes::Instruction;
@ -7,7 +7,7 @@ use super::super::pool::const_from;
use crate::error::ClassfileError;
use crate::insn::{Arith, ArrayKind, Const, Convert, Insn, Prim, SlotKind};
/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам.
/// `Some` - the instruction is covered; `None` - hand it to the next converters.
pub(super) fn convert_basic(
instruction: &Instruction,
pool: &ConstantPool<'_>,

View file

@ -1,4 +1,4 @@
//! Ветвления, `switch` и возвраты: абсолютные/относительные цели → метки.
//! Branches, `switch` and returns: absolute/relative targets → labels.
use ristretto_classfile::attributes::{Instruction, LookupSwitch, TableSwitch};
@ -6,7 +6,7 @@ use super::Resolver;
use crate::error::ClassfileError;
use crate::insn::{BranchCond, Cond, Insn, Label, Prim};
/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам.
/// `Some` - the instruction is covered; `None` - hand it to the next converters.
pub(super) fn convert_flow(
instruction: &Instruction,
index: u16,
@ -52,7 +52,7 @@ fn branch(cond: BranchCond, target: u16, resolve: &Resolver<'_>) -> Result<Insn,
Ok(Insn::Branch(cond, resolve(target)?))
}
/// Цель `switch` — номер инструкции: база плюс относительная дельта backend'а.
/// A `switch` target - an instruction number: base plus the backend's relative delta.
fn abs(index: u16, delta: i32, resolve: &Resolver<'_>) -> Result<Label, ClassfileError> {
let absolute = i32::from(index)
.checked_add(delta)

View file

@ -1,9 +1,8 @@
//! `Instruction` backend'а → [`Insn`](crate::insn::Insn) нашего IR.
//! Backend `Instruction` → [`Insn`](crate::insn::Insn) of our IR.
//!
//! Смещения ветвлений приходят из backend'а (абсолютные для `if*`/`goto`,
//! относительные от начала инструкции для `switch`), поэтому конвертация
//! принимает резолвер смещения в [`Label`](crate::insn::Label) — метки
//! назначает вызывающий код.
//! Branch offsets come from the backend (absolute for `if*`/`goto`, relative to
//! the instruction start for `switch`), so conversion takes a resolver from an
//! offset to a [`Label`](crate::insn::Label) - the calling code assigns labels.
mod basic;
mod flow;
@ -15,10 +14,10 @@ use ristretto_classfile::attributes::Instruction;
use crate::error::ClassfileError;
use crate::insn::{Insn, Label};
/// Резолвит абсолютное смещение байткода в метку.
/// Resolves an absolute bytecode offset into a label.
pub(super) type Resolver<'a> = dyn Fn(u16) -> Result<Label, ClassfileError> + 'a;
/// Конвертировать одну инструкцию. `index` — её номер в теле метода (нужно `switch`).
/// Convert one instruction. `index` - its number in the method body (`switch` needs it).
pub(super) fn convert(
instruction: &Instruction,
index: u16,

View file

@ -1,4 +1,4 @@
//! Поля, вызовы и создание объектов: индексы пула → строки IR.
//! Fields, calls and object creation: pool indices → IR strings.
use ristretto_classfile::ConstantPool;
use ristretto_classfile::attributes::{ArrayType, Instruction};
@ -7,7 +7,7 @@ use super::super::pool::{class_name, dynamic_parts, expect_kind, is_interface, r
use crate::error::ClassfileError;
use crate::insn::{ArrayKind, Insn, InvokeKind};
/// `Some` — инструкция покрыта, `None` — отдать следующим конвертерам.
/// `Some` - the instruction is covered; `None` - hand it to the next converters.
pub(super) fn convert_ref(
instruction: &Instruction,
pool: &ConstantPool<'_>,

View file

@ -1,10 +1,11 @@
//! Backend `ristretto_classfile` → наш IR: пул, инструкции, тела методов.
//! Backend `ristretto_classfile` → our IR: pool, instructions, method bodies.
//!
//! Пока ниоткуда не подключён (P1): `format` вернёт `Unimplemented`, пока не
//! будут готовы `parse`/`write` классового уровня поверх этих конвертеров.
//! Дерево уже разбито по ответственностям, чтобы подключение было одним
//! `mod parse` без рефакторинга.
//! Not wired in from anywhere yet (P1): `format` returns `Unimplemented` until
//! class-level `parse`/`write` are ready on top of these converters. The tree
//! is already split by responsibility so wiring is a single `mod parse` with no
//! refactoring.
pub(super) mod annos;
pub(super) mod attrs;
pub(super) mod class;
pub(super) mod code;

View file

@ -1,11 +1,11 @@
//! Разрешение индексов constant pool в строки нашего IR.
//! Resolving constant-pool indices into strings of our IR.
use ristretto_classfile::{Constant, ConstantPool, ReferenceKind};
use crate::error::ClassfileError;
use crate::insn::{Const, InvokeKind};
/// Имя класса по `CONSTANT_Class`.
/// The class name from a `CONSTANT_Class`.
pub(super) fn class_name(pool: &ConstantPool<'_>, index: u16) -> Result<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)` для `CONSTANT_Fieldref`/`_Methodref`.
/// `(owner, name, descriptor)` for a `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)` для `CONSTANT_NameAndType`.
/// `(name, descriptor)` for a `CONSTANT_NameAndType`.
pub(super) fn name_and_type(
pool: &ConstantPool<'_>,
index: u16,
@ -58,7 +58,7 @@ pub(super) fn name_and_type(
Ok((name, descriptor))
}
/// Строка из `CONSTANT_Utf8`.
/// The string from a `CONSTANT_Utf8`.
pub(super) fn utf8(pool: &ConstantPool<'_>, index: u16) -> Result<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())
}
/// Константа для `ldc`/`ldc_w`/`ldc2_w`.
/// The constant for `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)` для `CONSTANT_InvokeDynamic`.
/// `(name, descriptor, bootstrap)` for a `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: номер `reference_kind` для `CONSTANT_MethodHandle`.
/// JVMS §5.4.3.5: the `reference_kind` number for a `CONSTANT_MethodHandle`.
pub(super) fn kind_code(kind: &ReferenceKind) -> u8 {
match kind {
ReferenceKind::GetField => 1,
@ -154,11 +154,11 @@ pub(super) fn kind_code(kind: &ReferenceKind) -> u8 {
}
}
/// Проверка, что `Invoke` действительно ссылается на ожидаемый вид.
/// Checks that an `Invoke` really refers to the expected kind.
///
/// JVM принимает `Methodref` и `InterfaceMethodref` для всех видов вызова,
/// кроме `invokeinterface` (там только интерфейсная); строгость сверх JVM
/// ломает чтение реальных классов (статические методы интерфейсов).
/// The JVM accepts both `Methodref` and `InterfaceMethodref` for every call
/// kind except `invokeinterface` (interface reference only there); being
/// stricter than the JVM breaks reading real classes (interface static methods).
pub(super) fn expect_kind(
pool: &ConstantPool<'_>,
index: u16,

View file

@ -0,0 +1,149 @@
//! Runtime-visible/invisible annotations: IR → backend structures.
use ristretto_classfile::attributes::{
Annotation as RtAnno, AnnotationElement as RtElem, AnnotationValuePair as RtPair,
ParameterAnnotation as RtParamAnno, TargetPath as RtPath, TargetType as RtTarget,
TypeAnnotation as RtTypeAnno,
};
use ristretto_classfile::byte_reader::ByteReader;
use super::pool::Pool;
use crate::error::ClassfileError;
use crate::insn::Const;
use crate::model::{Annotation, AnnotationValue, TypeAnnotation};
/// The `annotations` list of a visible/invisible annotation attribute.
pub(super) fn list(annos: &[Annotation], pool: &mut Pool) -> Result<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,26 +1,27 @@
//! Атрибуты нашего IR → атрибуты backend'а.
//! Our IR attributes → backend attributes.
//!
//! Имена атрибутов (`SourceFile`, …) интернируются в пул здесь же — backend
//! хранит только `name_index`, строка восстанавливается при чтении.
//! Attribute names (`SourceFile`, …) are interned into the pool right here - the
//! backend stores only `name_index`, and the string is recovered on read.
use ristretto_classfile::attributes::{
Attribute as RtAttr, LineNumber as RtLine, LocalVariableTable as RtLocal,
LocalVariableTypeTable as RtLocalType, Record as RtRecord,
};
use super::annotations;
use super::helpers;
use super::pool::Pool;
use crate::error::ClassfileError;
use crate::insn::Label;
use crate::model::{Attribute, LineNumber, LocalVariable, LocalVariableType};
/// Позиции таблиц кода: метки → байты текущего layout.
/// Code-table positions: labels → bytes of the current layout.
pub(super) struct Positions<'a> {
pub resolve: &'a dyn Fn(Label) -> Result<u32, ClassfileError>,
pub byte_of: &'a dyn Fn(u32) -> Result<u16, ClassfileError>,
}
/// `LineNumberTable`: backend хранит номера инструкций и маппит сам.
/// `LineNumberTable`: the backend stores instruction numbers and maps them itself.
pub(super) fn line_number_table(
lines: &[LineNumber],
pool: &mut Pool,
@ -43,7 +44,7 @@ pub(super) fn line_number_table(
})
}
/// `LocalVariableTable`/`TypeTable` с пересчётом диапазона.
/// `LocalVariableTable`/`TypeTable` with the range recomputed.
pub(super) fn local_table(
vars: &[LocalVariable],
pool: &mut Pool,
@ -66,7 +67,7 @@ pub(super) fn local_table(
.collect::<Result<_, ClassfileError>>()?,
})
}
/// Та же таблица для типов (`signature` вместо дескриптора).
/// The same table for types (`signature` instead of a descriptor).
pub(super) fn local_type_table(
vars: &[LocalVariableType],
pool: &mut Pool,
@ -103,7 +104,7 @@ fn range(
Ok((first, length))
}
/// Один наш атрибут → атрибут backend'а.
/// One of our attributes → a backend attribute.
pub(super) fn convert(attr: &Attribute, pool: &mut Pool) -> Result<RtAttr, ClassfileError> {
Ok(match attr {
Attribute::SourceFile(name) => RtAttr::SourceFile {
@ -145,6 +146,13 @@ 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)?,
@ -171,6 +179,40 @@ 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` при записи: вариант в вариант, дельты по инструкциям.
//! `StackMapTable` frames on write: variant to variant, deltas per instruction.
//!
//! Наш IR хранит `offset_delta` в номерах инструкций; backend при `to_bytes`
//! сам пересчитает их в байты. Компактный формат (`Same`/`SameLocals`) годен
//! только когда **байтовая** дельта ≤ 63 — иначе нужен расширенный вариант.
//! Выбор делаем по байтовой дельте: байты считаются от layout текущего метода.
//! Our IR stores `offset_delta` in instruction numbers; the backend recomputes
//! them into bytes on `to_bytes`. The compact form (`Same`/`SameLocals`) is valid
//! only when the **byte** delta is ≤ 63 - otherwise the extended form is needed.
//! We choose by the byte delta: bytes are computed from the current method's layout.
use ristretto_classfile::attributes::{StackFrame as RtFrame, VerificationType as RtType};
@ -11,10 +11,10 @@ use super::super::pool::Pool;
use crate::error::ClassfileError;
use crate::format::{StackMapFrame, VerificationType};
/// Байтовое смещение начала инструкции (для расчёта дельт кадров).
/// The byte offset of an instruction's start (for computing frame deltas).
type ByteOf<'a> = &'a (dyn Fn(u32) -> Result<u16, ClassfileError> + 'a);
/// Кадры IR → кадры backend'а (индексные дельты — как есть).
/// IR frames → backend frames (index deltas - as-is).
pub(super) fn convert_frames(
frames: &[StackMapFrame],
pool: &mut Pool,
@ -32,7 +32,7 @@ pub(super) fn convert_frames(
last_instruction + delta + 1
};
let byte = byte_of(instruction)?;
// Байтовая дельта относительно конца предыдущего кадра.
// Byte delta relative to the end of the previous frame.
let byte_delta = if first {
byte
} else {
@ -48,7 +48,7 @@ pub(super) fn convert_frames(
Ok(out)
}
/// `byte_delta` — истинная байтовая дельта; компактный вид годен лишь при ≤ 63.
/// `byte_delta` is the true byte delta; the compact form is valid only when ≤ 63.
fn build_frame(
frame: &StackMapFrame,
pool: &mut Pool,
@ -60,8 +60,8 @@ fn build_frame(
Ok(match frame {
StackMapFrame::Same { .. } => {
if byte_delta <= 63 {
// Backend при verify()/to_bytes читает frame_type как дельту по
// ИНСТРУКЦИЯМ и сам пересчитает её в байты (≤ 63 — влезает).
// The backend, in verify()/to_bytes, reads frame_type as a delta by
// INSTRUCTION and recomputes it into bytes itself (≤ 63 fits).
RtFrame::SameFrame {
frame_type: delta as u8,
}
@ -97,7 +97,7 @@ fn build_frame(
})?;
if !(1..=3).contains(&count) {
return Err(ClassfileError::Write(format!(
"append-кадр на {count} local'ов (нужно 1–3)"
"append-кадр на {count} local'ов (нужно 1-3)"
)));
}
RtFrame::AppendFrame {

View file

@ -1,8 +1,8 @@
//! Наш [`Insn`](crate::insn::Insn) → `Instruction` backend'а.
//! Our [`Insn`](crate::insn::Insn) → the backend's `Instruction`.
//!
//! Обратная сторона `super::super::parse::insns`: метки резолвятся в
//! абсолютные номера инструкций (`switch` — в дельты от себя), константы
//! и ссылки уходят в пул через [`Pool`](super::super::pool::Pool).
//! The reverse side of `super::super::parse::insns`: labels resolve into
//! absolute instruction numbers (`switch` - into deltas from itself), constants
//! and references go to the pool via [`Pool`](super::super::pool::Pool).
use indexmap::IndexMap;
use ristretto_classfile::attributes::{Instruction as RtInsn, LookupSwitch, TableSwitch};
@ -13,9 +13,9 @@ use super::{branch, delta, fit_index, ret_op};
use crate::error::ClassfileError;
use crate::insn::{Insn, Label, SlotKind};
/// Одна инструкция IR → инструкция backend'а (`None` — маркер метки).
/// One IR instruction → a backend instruction (`None` - a label marker).
///
/// `index` — номер инструкции в методе (нужен `switch`-дельтам).
/// `index` - the instruction's number in the method (needed for `switch` deltas).
pub(crate) fn convert(
insn: &Insn,
index: u32,
@ -96,8 +96,9 @@ pub(crate) fn convert(
owner,
name,
descriptor,
itf,
..
} => invoke(*kind, owner, name, descriptor, pool)?,
} => invoke(*kind, owner, name, descriptor, *itf, pool)?,
Insn::InvokeDynamic {
name,
descriptor,
@ -178,7 +179,7 @@ fn store(slot: u16, kind: SlotKind) -> RtInsn {
}
}
/// Короткая форма при слоте ≤255, иначе `wide`-форма.
/// The short form when the slot is ≤255, otherwise the `wide` form.
fn narrow(slot: u16, short: fn(u8) -> RtInsn, wide: fn(u16) -> RtInsn) -> RtInsn {
u8::try_from(slot).map(short).unwrap_or_else(|_| wide(slot))
}

View file

@ -1,7 +1,7 @@
//! Тело метода нашего IR → атрибут `Code` backend'а.
//! Our IR method body → the backend `Code` attribute.
//!
//! Метки резолвятся в номера инструкций один раз здесь; дальше backend сам
//! пересчитывает номера в байтовые смещения при `to_bytes`.
//! Labels resolve into instruction numbers once, here; then the backend
//! recomputes numbers into byte offsets on `to_bytes`.
mod frames;
pub(crate) mod insns;
@ -22,8 +22,15 @@ use crate::model::{Attribute, Code, ExceptionHandler};
use frames::convert_frames;
/// Тело метода → готовый атрибут `Code` (с логическими номерами инструкций).
pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result<RtAttr, ClassfileError> {
/// 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> {
let (labels, bare) = split_marks(&code.insns)?;
let resolve = |label: Label| -> Result<u32, ClassfileError> {
labels
@ -55,11 +62,15 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result<RtAttr, Class
resolve: &resolve,
byte_of: &byte_of,
};
let frames = convert_frames(&code.frames, pool, &byte_of)?;
let frames = if emit_frames {
convert_frames(&code.frames, pool, &byte_of)?
} else {
Vec::new()
};
let mut attributes = Vec::with_capacity(code.attributes.len() + 1);
for attr in &code.attributes {
attributes.push(match attr {
// Backend хранит номера строк в индексах и маппит сам.
// The backend stores line numbers as indices and maps them itself.
Attribute::LineNumberTable(lines) => attrs::line_number_table(lines, pool, &positions)?,
Attribute::LocalVariableTable(vars) => attrs::local_table(vars, pool, &positions)?,
Attribute::LocalVariableTypeTable(vars) => {
@ -68,7 +79,7 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result<RtAttr, Class
other => attrs::convert(other, pool)?,
});
}
if !frames.is_empty() {
if emit_frames && !frames.is_empty() {
attributes.push(RtAttr::StackMapTable {
name_index: pool.utf8("StackMapTable")?,
frames,
@ -84,7 +95,7 @@ pub(super) fn convert_code(code: &Code, pool: &mut Pool) -> Result<RtAttr, Class
})
}
/// Метки → номера инструкций; сами маркеры из потока убираются.
/// 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());
@ -108,10 +119,10 @@ fn split_marks(insns: &[Insn]) -> Result<(BTreeMap<Label, u32>, Vec<&Insn>), Cla
Ok((labels, bare))
}
/// Номер инструкции → байтовое смещение (замер с заглушками целей).
/// Instruction number → byte offset (measured with placeholder targets).
///
/// В карту входит и конец кода (`len` → длина): концы диапазонов указывают
/// за последнюю инструкцию.
/// The map also includes the code end (`len` → length): range ends point past
/// the last instruction.
pub(crate) fn measure(insns: &[RtInsn]) -> Result<BTreeMap<u32, u16>, ClassfileError> {
let mut map = BTreeMap::new();
let mut cursor = Cursor::new(Vec::new());
@ -132,7 +143,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)
@ -178,7 +189,7 @@ fn entry(
})
}
/// Условный переход IR → `if*` backend'а.
/// An IR conditional branch → the backend's `if*`.
fn branch(cond: BranchCond, target: u32) -> Result<RtInsn, ClassfileError> {
let target = fit_index(target)?;
Ok(match cond {
@ -211,13 +222,13 @@ fn ret_op(prim: Option<Prim>) -> RtInsn {
}
}
/// Номер инструкции обязан влезать в `u16` (метод < 64 КБ кода).
/// The instruction number must fit in `u16` (method < 64 KB of code).
fn fit_index(index: u32) -> Result<u16, ClassfileError> {
u16::try_from(index)
.map_err(|_| ClassfileError::Write(format!("номер инструкции {index} вне u16")))
}
/// Дельта `switch`: цель минус позиция самого `switch`.
/// A `switch` delta: the target minus the `switch` instruction's own position.
fn delta(index: u32, target: u32) -> Result<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};
/// Константа: короткие формы (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` через пул.
/// A constant: short forms (`iconst`, `bipush`) + `ldc_w`/`ldc2_w` through the pool.
pub(super) fn int_const(value: &Const, pool: &mut Pool) -> Result<RtInsn, ClassfileError> {
Ok(match value {
Const::Int(v) => match *v {
@ -166,29 +166,34 @@ pub(super) fn convert_op(op: Convert) -> RtInsn {
}
}
/// `invoke*` family: the `itf` flag is authoritative (a Static/Special
/// call may still target an interface method - `List.of`), so the pool
/// entry kind follows it, not the opcode alone.
pub(super) fn invoke(
kind: InvokeKind,
owner: &str,
name: &str,
descriptor: &str,
itf: bool,
pool: &mut Pool,
) -> Result<RtInsn, ClassfileError> {
let itf = itf || matches!(kind, InvokeKind::Interface);
Ok(match kind {
InvokeKind::Virtual => {
RtInsn::Invokevirtual(pool.method_ref(owner, name, descriptor, kind)?)
RtInsn::Invokevirtual(pool.method_ref(owner, name, descriptor, itf)?)
}
InvokeKind::Special => {
RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, kind)?)
RtInsn::Invokespecial(pool.method_ref(owner, name, descriptor, itf)?)
}
InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, kind)?),
InvokeKind::Static => RtInsn::Invokestatic(pool.method_ref(owner, name, descriptor, itf)?),
InvokeKind::Interface => {
let index = pool.method_ref(owner, name, descriptor, kind)?;
let index = pool.method_ref(owner, name, descriptor, itf)?;
RtInsn::Invokeinterface(index, arg_count(descriptor)?)
}
})
}
/// Байт `count` для `invokeinterface`: слоты аргументов + `objectref`.
/// The `count` byte for `invokeinterface`: argument slots + `objectref`.
fn arg_count(descriptor: &str) -> Result<u8, ClassfileError> {
let params = descriptor
.split_once('(')
@ -229,7 +234,7 @@ fn arg_count(descriptor: &str) -> Result<u8, ClassfileError> {
.map_err(|_| ClassfileError::Write(format!("слишком много аргументов в {descriptor}")))
}
/// Пропустить символы до разделителя (включительно); `false` — строка кончилась.
/// Skip characters up to the separator (inclusive); `false` - the string ended.
fn skip_to(chars: &mut std::str::Chars<'_>, end: char) -> bool {
for char in chars {
if char == end {

View file

@ -1,8 +1,9 @@
//! Хелперы сборки `InnerClasses`/`BootstrapMethods`/`MethodParameters`.
//! Helpers building `InnerClasses`/`BootstrapMethods`/`MethodParameters`.
//!
//! Вынесены из `attrs`, чтобы тот держался в лимите 250 строк; логика не
//! изменилась — только место. Каждый строит запись backend'а из элемента IR,
//! интернируя имена/дескрипторы и резолвя индексы `CONSTANT_Class` через пул.
//! Moved out of `attrs` so it stays within the 250-line limit; the logic is
//! unchanged - only the location. Each builds a backend entry from an IR
//! element, interning names/descriptors and resolving `CONSTANT_Class` indices
//! through the pool.
use ristretto_classfile::MethodAccessFlags;
use ristretto_classfile::attributes::{
@ -50,7 +51,7 @@ pub(super) fn bootstrap(
})
}
/// Аргумент bootstrap-метода: те же константы, что в `ldc`, плюс `Dynamic`.
/// A bootstrap-method argument: the same constants as in `ldc`, plus `Dynamic`.
fn bootstrap_arg(arg: &Const, pool: &mut Pool) -> Result<u16, ClassfileError> {
match arg {
Const::Dynamic {

View file

@ -1,8 +1,9 @@
//! Наш IR → байты `.class` через backend `ristretto_classfile`.
//! Our IR → `.class` bytes through the `ristretto_classfile` backend.
//!
//! Пул собирается с нуля детерминированным обходом; backend сам пересчитывает
//! номера инструкций в байтовые смещения и проверяет результат (`verify`).
//! The pool is built from scratch by a deterministic walk; the backend recomputes
//! instruction numbers into byte offsets and verifies the result (`verify`).
mod annotations;
mod attrs;
pub(crate) mod code;
mod helpers;
@ -16,11 +17,16 @@ use ristretto_classfile::{
use crate::error::ClassfileError;
use crate::model::{ClassFile, Field, Method};
/// Класс нашего IR → байты `.class`.
/// Our IR class → `.class` bytes.
pub(crate) fn write_class(class: &ClassFile) -> Result<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,
@ -36,7 +42,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)?);
methods.push(convert_method(method, &mut pool, emit_frames)?);
}
let mut attributes = Vec::with_capacity(class.attributes.len());
for attr in &class.attributes {
@ -77,13 +83,17 @@ fn convert_field(field: &Field, pool: &mut pool::Pool) -> Result<RtField, Classf
})
}
fn convert_method(method: &Method, pool: &mut pool::Pool) -> Result<RtMethod, ClassfileError> {
fn convert_method(
method: &Method,
pool: &mut pool::Pool,
emit_frames: bool,
) -> 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)?);
attributes.push(code::convert_code(code, pool, emit_frames)?);
}
Ok(RtMethod {
access_flags: MethodAccessFlags::from_bits_truncate(method.access_flags),

View file

@ -1,15 +1,15 @@
//! Сборка constant pool при записи: строки нашего IR → индексы backend'а.
//! Building the constant pool on write: our IR strings → backend indices.
//!
//! Пул строится с нуля детерминированным обходом (классы, поля, методы,
//! атрибуты, код), поэтому одинаковый IR даёт одинаковые байты. Индексы
//! `Raw`-атрибутов при этом не переносятся — см. `super::attrs`.
//! The pool is built from scratch by a deterministic walk (classes, fields,
//! methods, attributes, code), so identical IR yields identical bytes. `Raw`
//! attribute indices are not carried over - see `super::attrs`.
//!
//! Backend не дедуплицирует: `add_*` всегда толкает новый элемент. Кэшируем
//! семантические ключи сами — иначе `LocalVariableTable` и
//! `LocalVariableTypeTable` получат разные `name_index` для одного имени, и
//! HotSpot отвергнет класс (`LVTT entry ... does not match any LVT entry`).
//! Порядок обхода детерминирован, поэтому кэш меняет только компактность пула.
//! Референсы (поле/метод/хендл/динамик) — в [`refs`].
//! The backend does not deduplicate: `add_*` always pushes a new entry. We cache
//! semantic keys ourselves - otherwise `LocalVariableTable` and
//! `LocalVariableTypeTable` would get different `name_index` values for the same
//! name, and HotSpot would reject the class (`LVTT entry ... does not match any
//! LVT entry`). The walk order is deterministic, so the cache only changes pool
//! compactness. References (field/method/handle/dynamic) live in [`refs`].
use std::collections::HashMap;
@ -20,7 +20,7 @@ use crate::insn::Const;
mod refs;
/// Строитель пула; живёт только внутри одного `write`.
/// The pool builder; lives only within a single `write`.
pub(crate) struct Pool {
pub(super) pool: ConstantPool<'static>,
pub(super) utf8s: HashMap<String, u16>,
@ -68,8 +68,8 @@ impl Pool {
if let Some(&index) = self.name_types.get(&key) {
return Ok(index);
}
// Собираем из примитивов, а не `add_name_and_type`: последний толкает
// собственные `Utf8`-строки мимо нашего кэша (дубли в пуле).
// Build from primitives, not `add_name_and_type`: the latter pushes its
// own `Utf8` strings past our cache (pool duplicates).
let name_index = self.utf8(name)?;
let descriptor_index = self.utf8(descriptor)?;
let index = self
@ -96,7 +96,7 @@ impl Pool {
Ok(index)
}
/// Константа для `ldc`/`ldc2_w`; `dynamic` запрещён (только через bootstrap).
/// A constant for `ldc`/`ldc2_w`; `dynamic` is forbidden (bootstrap only).
pub(super) fn constant(&mut self, value: &Const) -> Result<u16, ClassfileError> {
match value {
Const::Int(v) => self.pool.add_integer(*v).map_err(write_err),

View file

@ -1,15 +1,14 @@
//! Референсы constant pool: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`.
//! Constant-pool references: `Fieldref`/`Methodref`/`MethodHandle`/`Dynamic`.
//!
//! Это `impl Pool` из [`super`]; вынесено отдельно, чтобы материнский файл
//! держался в лимите структуры. Каждый билдер мемоизирован по семантическому
//! ключу (owner/name/descriptor/…) — одинаковая ссылка всегда получает один
//! индекс, а пул не раздувается дублями (раздувание иначе расширяет `ldc`
//! в `ldc_w` и меняет длину кода при переносе).
//! This is an `impl Pool` from [`super`], split out so the parent file stays
//! within the structure limit. Each builder is memoized by a semantic key
//! (owner/name/descriptor/…) - an identical reference always gets the same index,
//! and the pool doesn't bloat with duplicates (bloat would otherwise widen `ldc`
//! into `ldc_w` and change code length on relocation).
use ristretto_classfile::{Constant, ReferenceKind};
use crate::error::ClassfileError;
use crate::insn::InvokeKind;
use super::{Pool, write_err};
@ -42,9 +41,8 @@ impl Pool {
owner: &str,
name: &str,
descriptor: &str,
kind: InvokeKind,
itf: bool,
) -> Result<u16, ClassfileError> {
let itf = matches!(kind, InvokeKind::Interface);
let key = (
owner.to_string(),
name.to_string(),
@ -94,7 +92,7 @@ impl Pool {
ClassfileError::Write(format!("некорректный reference_kind {kind}: {e}"))
})?;
let reference = if itf {
self.method_ref(owner, name, descriptor, InvokeKind::Interface)?
self.method_ref(owner, name, descriptor, true)?
} else if matches!(
reference_kind,
ReferenceKind::GetField
@ -104,7 +102,7 @@ impl Pool {
) {
self.field_ref(owner, name, descriptor)?
} else {
self.method_ref(owner, name, descriptor, InvokeKind::Static)?
self.method_ref(owner, name, descriptor, false)?
};
let index = self
.pool

View file

@ -1,9 +1,9 @@
//! Типы операндов инструкций: константы, примитивы, условия, вызовы.
//! Instruction operand types: constants, primitives, conditions, calls.
/// Идентификатор метки внутри одного метода.
/// A label identifier within a single method.
pub type Label = u32;
/// Константа для `ldc`/`ldc_w`/`ldc2_w`.
/// A constant for `ldc`/`ldc_w`/`ldc2_w`.
#[derive(Debug, Clone, PartialEq)]
pub enum Const {
Int(i32),
@ -11,7 +11,7 @@ pub enum Const {
Float(f32),
Double(f64),
String(String),
/// Внутреннее имя класса (`java/lang/String`).
/// The class's internal name (`java/lang/String`).
Class(String),
MethodType(String),
MethodHandle {
@ -21,7 +21,7 @@ pub enum Const {
descriptor: String,
itf: bool,
},
/// `CONSTANT_Dynamic`: имя, дескриптор, индекс bootstrap-метода.
/// `CONSTANT_Dynamic`: name, descriptor, bootstrap-method index.
Dynamic {
name: String,
descriptor: String,
@ -29,7 +29,7 @@ pub enum Const {
},
}
/// Размер операнда/результата арифметики.
/// Operand/result size of an arithmetic operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Prim {
Int,
@ -38,7 +38,7 @@ pub enum Prim {
Double,
}
/// Арифметическая/битовая операция; тип берётся из [`Prim`].
/// An arithmetic/bitwise operation; the type comes from [`Prim`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Arith {
Add,
@ -55,7 +55,7 @@ pub enum Arith {
Ushr,
}
/// Условие перехода.
/// A branch condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cond {
Eq,
@ -66,10 +66,10 @@ pub enum Cond {
Ge,
}
/// Вид условного перехода (соответствует семействам `if*`).
/// Kind of conditional branch (matches the `if*` families).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BranchCond {
/// `if<cond>` относительно нуля.
/// `if<cond>` against zero.
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,
}
/// Конверсия типов (`i2l`, `f2b`, ... — JVMS §6.5.i2<b|c|s|l|f|d>).
/// Type conversion (`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,
}
/// Тип элемента массива для `newarray`/`*aload`/`*astore`.
/// Array element type for `newarray`/`*aload`/`*astore`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayKind {
Boolean,
@ -122,10 +122,10 @@ pub enum ArrayKind {
Reference,
}
/// Тип слота локальной переменной для `*load*`/`*store*`.
/// Local-variable slot type for `*load*`/`*store*`.
///
/// Хранится явно: выбор опкода (`iload` vs `aload`) — подсказка верификатору,
/// потерять её при round-trip нельзя.
/// Stored explicitly: the opcode choice (`iload` vs `aload`) is a hint to the
/// verifier, and losing it on a round-trip is not acceptable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotKind {
Int,

View file

@ -1,7 +1,7 @@
//! Инструкции IR: смещения отсутствуют, ветвления адресуют [`Label`].
//! IR instructions: no offsets, branches address a [`Label`].
//!
//! Это принципиально: любой пасс, меняющий порядок/длину инструкций, не обязан
//! пересчитывать jump-офсеты — это делает writer один раз в конце пайплайна.
//! This is fundamental: any pass that changes instruction order/length need not
//! recompute jump offsets - the writer does that once at the end of the pipeline.
mod kinds;
@ -9,32 +9,32 @@ pub use kinds::{
Arith, ArrayKind, BranchCond, Cond, Const, Convert, InvokeKind, Label, Prim, SlotKind,
};
/// Мнемоника одной инструкции.
/// Mnemonic of a single instruction.
#[derive(Debug, Clone, PartialEq)]
pub enum Insn {
/// Маркер метки. Ветвления указывают на [`Label`], writer вычисляет смещения.
/// Label marker. Branches point at a [`Label`]; the writer computes offsets.
Mark(Label),
Nop,
AconstNull,
Const(Const),
/// Загрузка локальной переменной (`iload`, `aload`, ...).
/// Load a local variable (`iload`, `aload`, ...).
Load {
slot: u16,
kind: SlotKind,
},
/// Сохранение локальной переменной.
/// Store a local variable.
Store {
slot: u16,
kind: SlotKind,
},
/// `iinc` — увеличение локальной переменной на константу.
/// `iinc` - increase a local variable by a constant.
Iinc {
index: u16,
delta: i32,
},
/// Загрузка элемента массива.
/// Load an array element.
ArrayLoad(ArrayKind),
/// Сохранение элемента массива.
/// Store an array element.
ArrayStore(ArrayKind),
Pop,
Pop2,
@ -45,23 +45,23 @@ pub enum Insn {
Dup2X1,
Dup2X2,
Swap,
/// `iadd`, `lmul`, `lneg`, ... — тип + операция.
/// `iadd`, `lmul`, `lneg`, ... - type + operation.
Binary {
prim: Prim,
op: Arith,
},
/// Сравнение длин (`lcmp`) и плавающих (`fcmpl`/`fcmpg`).
/// Comparison of longs (`lcmp`) and floats (`fcmpl`/`fcmpg`).
Cmp {
prim: Prim,
nan_great: bool,
},
/// Конверсия типов (`i2l`, `d2f`, ...).
/// Type conversion (`i2l`, `d2f`, ...).
Convert(Convert),
Branch(BranchCond, Label),
Goto(Label),
/// `jsr` — вызов подпрограммы (только классы версии ≤ 50).
/// `jsr` - subroutine call (only version ≤ 50 classes).
Jsr(Label),
/// `ret` — возврат из подпрограммы (`jsr`/`ret` парны).
/// `ret` - return from a subroutine (`jsr`/`ret` come in pairs).
Ret(u16),
TableSwitch {
default: Label,
@ -73,9 +73,9 @@ pub enum Insn {
default: Label,
pairs: Vec<(i32, Label)>,
},
/// `return`/`ireturn`/...; `None` — пустой возврат.
/// `return`/`ireturn`/...; `None` - void return.
Return(Option<Prim>),
/// `areturn` — возврат ссылки (у [`Prim`] нет ссылочного типа).
/// `areturn` - return a reference ([`Prim`] has no reference type).
AReturn,
GetStatic {
owner: String,
@ -112,7 +112,7 @@ pub enum Insn {
New(String),
NewArray(ArrayKind),
ANewArray(String),
/// `multianewarray` — массив любого измерения; `dims` — сколько измерений со стека.
/// `multianewarray` - array of any dimension; `dims` - how many dimensions from the stack.
MultiANewArray {
descriptor: String,
dims: u8,
@ -126,7 +126,7 @@ pub enum Insn {
}
impl Insn {
/// Метки, на которые ссылается инструкция (для построения CFG).
/// Labels the instruction references (for building the CFG).
pub fn targets(&self) -> Vec<Label> {
match self {
Insn::Branch(_, label) | Insn::Goto(label) | Insn::Jsr(label) => vec![*label],
@ -154,7 +154,7 @@ impl Insn {
}
}
/// Незакодированный переход (для вставки opaque-предикатов и перестройки CFG).
/// An encoded jump target (for inserting opaque predicates and rebuilding the 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
//!
//! Собственный IR для классовых файлов JVM: разбор, представление, запись.
//! Own IR for JVM class files: parsing, representation, writing.
//!
//! Почему свой IR, а не работа напрямую с крейтом-парсером: пассам нужна
//! стабильная модель (метки вместо смещений, осознанный набор атрибутов),
//! а не API третьей стороны, который меняется между версиями.
//! 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.
//!
//! Статус: модель и билдер готовы, бинарный parse/write — этап P1
//! (см. `docs/stack.md`).
//! Status: model and builder are ready; binary parse/write is stage P1
//! (see `docs/stack.md`).
pub mod error;
pub mod format;
@ -23,7 +23,15 @@ pub use insn::{
};
pub use model::builder::{ClassBuilder, empty_code};
pub use model::{
Attribute, BootstrapMethod, ClassFile, Code, ExceptionHandler, Field, InnerClass, LineNumber,
LocalVariable, LocalVariableType, Method, MethodParameter, Program, RecordComponent, Resource,
Version,
Annotation, AnnotationValue, Attribute, BootstrapMethod, ClassFile, Code, ExceptionHandler,
Field, InnerClass, LineNumber, LocalVariable, LocalVariableType, Method, MethodParameter,
Program, RecordComponent, Resource, TypeAnnotation, 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

@ -0,0 +1,55 @@
//! 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 @@
//! Сборка классов «с нуля»: junk-классы, рантайм-декодеры, аннотации-шум.
//! Building classes "from scratch": junk classes, runtime decoders, noise annotations.
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 {
/// Новый класс `public` с указанным суперклассом (`None` = `java/lang/Object`,
/// кроме самого `java/lang/Object` — у него суперкласса нет).
/// A new `public` class with the given superclass (`None` = `java/lang/Object`,
/// except for `java/lang/Object` itself - it has no superclass).
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
}
/// Задать флаги доступа (перезаписывает `ACC_PUBLIC|ACC_SUPER`).
/// Set access flags (overwrites `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
}
/// Добавить метод без тела (`abstract`/`native` должны выставить флаги сами).
/// Add a method without a body (`abstract`/`native` must set their own flags).
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 {
}
}
/// Пустое тело метода (`return`), для junk-методов.
/// An empty method body (`return`), for junk methods.
pub fn empty_code(max_locals: u16) -> Code {
Code {
max_stack: 0,

View file

@ -1,14 +1,16 @@
//! Структура «программы» — единица работы пайплайна.
//! 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};
/// Неизвестные/специфичные атрибуты хранятся байтами — round-trip без потерь.
/// Unknown/specific attributes are stored as bytes - lossless round-trip.
#[derive(Debug, Clone, PartialEq)]
pub enum Attribute {
SourceFile(String),
@ -19,26 +21,49 @@ pub enum Attribute {
Deprecated,
Synthetic,
InnerClasses(Vec<InnerClass>),
/// `NestHost`: класс, служащий nest-хостом (JVMS §4.7.28).
/// `NestHost`: the class acting as nest host (JVMS §4.7.28).
NestHost(String),
/// `NestMembers`: классы-члены этого nest-хоста (JVMS §4.7.29).
/// `NestMembers`: the member classes of this nest host (JVMS §4.7.29).
NestMembers(Vec<String>),
/// `ConstantValue` поля (`static final`): значение из пула.
/// `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(Const),
/// `BootstrapMethods` для `invokedynamic` (лямбды): метод + аргументы.
/// `BootstrapMethods` for `invokedynamic` (lambdas): method + arguments.
BootstrapMethods(Vec<BootstrapMethod>),
/// `EnclosingMethod`: класс и опциональный метод, содержащие локальный класс.
/// `EnclosingMethod`: the class and optional method enclosing a local class.
EnclosingMethod {
class: String,
method: Option<(String, String)>,
},
/// `MethodParameters`: имена формальных параметров (`None` — безымянный).
/// `MethodParameters`: formal parameter names (`None` - unnamed).
MethodParameters(Vec<MethodParameter>),
/// `Record`: компоненты record-класса.
/// `Record`: the record class's components.
Record(Vec<RecordComponent>),
/// `LocalVariableTypeTable`: сигнатуры generic-локальных (как LVT).
/// `LocalVariableTypeTable`: generic local signatures (like LVT).
LocalVariableTypeTable(Vec<LocalVariableType>),
/// Всё остальное: имя + сырые байты `info` (осторожно с индексами пула).
/// `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).
Raw {
name: String,
data: Vec<u8>,
@ -47,14 +72,14 @@ pub enum Attribute {
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineNumber {
/// Метка начала (байты вычисляет writer — переживает вставки пассов).
/// Start label (the writer computes bytes - survives pass insertions).
pub start: Label,
pub line: u16,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LocalVariable {
/// Метки диапазона видимости (writer пересчитает в байты).
/// Visibility-range labels (the writer recomputes them into bytes).
pub start: Label,
pub end: Label,
pub name: String,
@ -70,10 +95,10 @@ pub struct InnerClass {
pub access_flags: u16,
}
/// Один `bootstrap`-метод: ссылка вида `MethodHandle` + аргументы-константы.
/// One `bootstrap` method: a `MethodHandle`-style reference + const arguments.
#[derive(Debug, Clone, PartialEq)]
pub struct BootstrapMethod {
/// Номер `reference_kind` (JVMS §5.4.3.5).
/// The `reference_kind` number (JVMS §5.4.3.5).
pub kind: u8,
pub owner: String,
pub name: String,
@ -82,14 +107,14 @@ pub struct BootstrapMethod {
pub args: Vec<Const>,
}
/// Формальный параметр метода (`MethodParameters`).
/// A method's formal parameter (`MethodParameters`).
#[derive(Debug, Clone, PartialEq)]
pub struct MethodParameter {
pub name: Option<String>,
pub access_flags: u16,
}
/// Компонент `Record`: поле record-класса с атрибутами.
/// A `Record` component: a record class field with attributes.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordComponent {
pub name: String,
@ -97,10 +122,10 @@ pub struct RecordComponent {
pub attributes: Vec<Attribute>,
}
/// Строка `LocalVariableTypeTable` (как `LocalVariable`, но с сигнатурой).
/// A `LocalVariableTypeTable` entry (like `LocalVariable`, but with a signature).
#[derive(Debug, Clone, PartialEq)]
pub struct LocalVariableType {
/// Метки диапазона видимости (writer пересчитает в байты).
/// Visibility-range labels (the writer recomputes them into bytes).
pub start: Label,
pub end: Label,
pub name: String,
@ -126,18 +151,18 @@ pub struct Method {
}
impl Method {
/// `native`/`abstract` тела не имеют.
/// `native`/`abstract` methods have no body.
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`].
/// Label markers + instructions; branches point at a [`Label`].
pub insns: Vec<Insn>,
pub exception_table: Vec<ExceptionHandler>,
pub frames: Vec<StackMapFrame>,
@ -145,7 +170,7 @@ pub struct Code {
}
impl Code {
/// Все метки, объявленные в теле метода.
/// All labels declared in the method body.
pub fn labels(&self) -> Vec<Label> {
self.insns
.iter()
@ -159,15 +184,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,
/// Внутреннее имя класса или `None` для `any`.
/// The class's internal name, or `None` for `any`.
pub catch_type: Option<String>,
}
/// Один `.class` в нормализованном виде.
/// One `.class` in normalized form.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassFile {
pub version: Version,
@ -181,34 +206,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)
}
/// Признак `ACC_INTERFACE`.
/// The `ACC_INTERFACE` flag.
pub fn is_interface(&self) -> bool {
self.access_flags & 0x0200 != 0
}
}
/// Ресурс внутри архива (JSON, properties, картинки, ...).
/// A resource inside the archive (JSON, properties, images, ...).
#[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>,
@ -216,24 +241,24 @@ pub struct Program {
}
impl Program {
/// Класс по внутреннему имени (`pkg/Class`).
/// A class by internal name (`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 @@
//! Версия классового файла (major/minor).
//! Class-file version (major/minor).
/// Версия классового файла.
/// The class-file version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
pub minor: u16,

View file

@ -1,9 +1,9 @@
//! Приёмка `compute_frames` на фикстурах (`tests/data`).
//! Acceptance for `compute_frames`: fixtures plus emitter edge cases.
//!
//! Кадры сносятся и считаются заново. Судьи: детерминизм + round-trip IR +
//! настоящий `java -Xverify:all` для классов без внешних зависимостей.
//! (`verify_class` backend'а для приёмки не годится: он ждёт кадры в байтах,
//! а `from_bytes` отдаёт в индексах — см. `todo.md`.)
//! 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`.)
#![allow(clippy::expect_used, clippy::unwrap_used)]
@ -11,9 +11,12 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use noxis_classfile::{Hierarchy, compute_frames, format};
use noxis_classfile::{
Arith, BranchCond, ClassBuilder, Code, Cond, Const, Insn, Prim, SlotKind, Version,
{Hierarchy, compute_frames, format},
};
/// Карта `класс → суперкласс` для LUB.
/// A `class → superclass` map for LUB.
#[derive(Default)]
struct MapHierarchy {
supers: BTreeMap<String, String>,
@ -25,13 +28,13 @@ impl Hierarchy for MapHierarchy {
}
}
/// Классы только на JDK — их `java` проверит полностью.
/// JDK-only classes - `java` checks them fully.
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");
@ -41,7 +44,7 @@ fn fixtures_recompute_and_verify() {
.filter(|path| path.extension().is_some_and(|ext| ext == "class"))
.collect();
names.sort();
assert!(!names.is_empty(), "нет фикстур в tests/data");
assert!(!names.is_empty(), "no fixtures in tests/data");
let mut supers = BTreeMap::new();
let mut parsed = Vec::new();
@ -50,7 +53,7 @@ fn fixtures_recompute_and_verify() {
supers.insert(class.this_class.clone(), class.super_class.clone());
parsed.push(class);
}
// Без суперкласса — только `java/lang/Object`.
// Only `java/lang/Object` has no superclass.
supers.entry("java/lang/Object".to_string()).or_insert(None);
let hierarchy = MapHierarchy {
supers: supers
@ -71,11 +74,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, "недетерминированные кадры");
assert_eq!(first, second, "nondeterministic frames");
}
// Round-trip: записанное читается в тот же IR (включая кадры).
// Round-trip: written bytes read back into the same IR (frames included).
let written = format::write(class).expect("write");
assert_eq!(
format::parse(&written).expect("re-parse"),
@ -89,7 +92,85 @@ fn fixtures_recompute_and_verify() {
let _ = std::fs::remove_dir_all(&scratch);
}
/// Есть ли `java` для проверки настоящим верификатором.
/// 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.
fn java_available() -> bool {
Command::new("java")
.arg("-version")
@ -97,8 +178,60 @@ fn java_available() -> bool {
.is_ok_and(|out| out.status.success())
}
/// Записать класс в дерево пакетов и прогнать `java -Xverify:all`.
/// Успех — загрузка без ошибок верификации (`main` при этом отсутствует).
/// 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).
fn java_verify(
scratch: &Path,
class: &noxis_classfile::ClassFile,
@ -118,7 +251,7 @@ fn java_verify(
.arg(scratch)
.arg(&dotted)
.output()
.map_err(|e| format!("запуск java: {e}"))?;
.map_err(|e| format!("running 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

@ -0,0 +1,267 @@
//! 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

@ -0,0 +1,108 @@
//! 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

@ -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, BootstrapMethod as RtBsm, ExceptionTableEntry as RtEntry,
Instruction as Rt, LineNumber as RtLine, StackFrame as RtFrame,
Attribute as RtAttr, 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, ReferenceKind,
FieldType, JAVA_21, Method as RtMethod, MethodAccessFlags,
};
/// Минимальный класс: версия, флаги, поле с `ConstantValue`, `SourceFile`.
@ -151,85 +151,6 @@ 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");
@ -243,3 +164,10 @@ 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

@ -0,0 +1,259 @@
//! 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,49 +1,50 @@
//! Секции конфигурации: стили имён и настройки отдельных пассов.
//! 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` — короткие латинские.
/// `a`, `b`, ... `aa` - short Latin.
ShortLatin,
/// `I`, `l`, `O`, `0` — визуально одинаковые.
/// `I`, `l`, `O`, `0` - visually identical.
IlO0,
/// Случайные unicode-имена (суррогаты допустимы в modified UTF-8).
/// Random Unicode names (surrogates are valid in modified UTF-8).
Unicode,
/// Смешанная латиница средней длины.
/// Medium-length mixed-case Latin.
#[default]
MixedLatin,
/// Псевдосмысленные слова из другого проекта (дезориентация).
/// Pseudo-meaningful words from another project (misdirection).
DecoyWords,
/// Правдоподобные имена: `TextureCache`, `resolveToken` — вместо
/// явного мусора маскируется под обычный прикладной код.
/// Plausible names: `TextureCache`, `resolveToken` - blends in as
/// ordinary application code instead of obvious noise.
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,
/// Делать члены `public` (чтобы не ломать inheritance между пакетами).
/// Widen members to `public` (so moving to a new package doesn't break
/// inheritance).
pub widen_access: bool,
/// Переименовывать enum-константы.
/// Rename enum constants.
pub rename_enum_constants: bool,
/// Переименовывать локальные переменные и параметры.
/// Rename local variables and parameters.
pub rename_locals: bool,
/// Переименовывать и не-private члены (агрессивно: безопасно для приложений,
/// опасно для библиотек и кода с рефлексией).
/// Also rename non-private members (aggressive: safe for applications,
/// dangerous for libraries and reflection-heavy code).
pub rename_public_members: bool,
}
@ -63,19 +64,20 @@ 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>,
/// Вычислять ключ из KDF(class, method, index), а не класть рядом с текстом.
/// Derive the key from KDF(class, method, index) instead of placing it
/// next to the ciphertext.
pub derive_key: bool,
}
@ -91,15 +93,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,
/// Вплетать opaque-предикаты в тела блоков.
/// Weave opaque predicates into block bodies.
pub encrypt_block_bodies: bool,
}
@ -118,15 +120,15 @@ impl Default for FlowConfig {
}
}
/// Настройки шифрования констант.
/// Constant encryption settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConstantsConfig {
/// Схемы разбиения (`xor`, `add`, `shift`), выбор по RNG на константу.
/// Splitting schemes (`xor`, `add`, `shift`), picked by RNG per constant.
pub schemes: Vec<String>,
/// Вставлять opaque-предикаты (не больше этого на метод).
/// Insert opaque predicates (at most this many per method).
pub max_predicates: usize,
/// Не трогать константы в этих классах (префиксы внутренних имён).
/// Don't touch constants in these classes (internal-name prefixes).
pub skip: Vec<String>,
}
@ -140,15 +142,19 @@ impl Default for ConstantsConfig {
}
}
/// Настройки шума.
/// Noise pass settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NoiseConfig {
/// Сколько junk-классов на каждый настоящий (0 = выключено).
/// How many junk classes per real one (0 = disabled).
pub junk_ratio: usize,
/// Число junk-аннотаций на класс.
/// 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.
pub junk_annotations: usize,
/// Вплетать junk-классы в граф достижимости (обязательно для осмысленности).
/// Weave junk classes into the reachability graph (required for them to
/// make sense).
pub weave_reachable: bool,
}
@ -156,23 +162,29 @@ 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 {
/// Удалять `LineNumberTable`.
/// Strip `LineNumberTable`.
pub strip_line_numbers: bool,
/// Удалять `LocalVariableTable`.
/// 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`.
pub strip_local_variables: bool,
/// Подменять `SourceFile` на ложное имя.
/// Replace `SourceFile` with a fake name.
pub spoof_source_file: bool,
/// Удалять `Signature`/`InnerClasses`/`EnclosingMethod`.
/// Remove `SourceFile` entirely instead of spoofing it.
pub strip_source_file: bool,
/// Strip `Signature`/`InnerClasses`/`EnclosingMethod`.
pub strip_signatures: bool,
}
@ -180,8 +192,10 @@ 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,9 +1,11 @@
//! Перевод архива в [`Program`] и обратно.
//! Archive to [`Program`] and back.
//!
//! Правило простое: `*.class` уходит в парсер, всё остальное — в ресурсы.
//! Обратно классы сериализуются первыми, затем ресурсы: порядок внутри
//! архива на поведение не влияет, а фиксированный порядок даёт
//! воспроизводимую запись.
//! 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;
use noxis_classfile::Program;
use noxis_classfile::format;
@ -11,13 +13,22 @@ 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) {
program.classes.push(format::parse(&entry.data)?);
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);
}
} else {
program.resources.push(Resource {
path: entry.name,
@ -29,13 +40,19 @@ pub fn load(entries: Vec<Entry>) -> Result<Program, JarError> {
Ok(program)
}
/// Собирает записи архива из [`Program`]: сначала классы, потом ресурсы.
/// Assembles archive entries from [`Program`]: classes first, then resources.
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);
entries.push(Entry::new(name, format::write(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));
}
for resource in &program.resources {
entries.push(Entry::new(resource.path.clone(), resource.data.clone()));
@ -44,11 +61,19 @@ pub fn save(program: &Program) -> Result<Vec<Entry>, JarError> {
Ok(entries)
}
/// Классовый файл внутри архива: путь оканчивается на `.class`.
/// A class file inside the archive: the path ends in `.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)]
@ -78,7 +103,7 @@ mod tests {
assert_eq!(save(&program).expect("save"), source);
}
/// До P1 `format::parse` — заглушка; после P1 ожидается успешный разбор.
/// Class entries go through the parser (round-trip keeps them intact).
#[test]
fn class_entries_go_through_the_parser() {
let entries = vec![
@ -97,4 +122,41 @@ 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,6 +11,7 @@ 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,14 +1,13 @@
//! Схемы разбиения констант и opaque-предикаты.
//! Constant-splitting schemes and opaque predicates.
//!
//! Целые константы вне `iconst`-диапазона заменяются тройками (`x^k`,
//! `a+b`, сдвиг); opaque-предикат — всегда истинное условие с мёртвой
//! ветвью из одного `nop` (валидно, не исполняется, ломает линейный
//! дисассемблирование).
//! 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).
use noxis_classfile::{Arith, BranchCond, Cond, Const, Insn, Prim};
use noxis_core::Rng;
/// Схема разбиения (имена из `ConstantsConfig::schemes`).
/// Splitting scheme (names from `ConstantsConfig::schemes`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Scheme {
Xor,
@ -27,7 +26,7 @@ impl Scheme {
}
}
/// Разбить `int`-константу на вычисляющую её тройку.
/// Split an `int` constant into a triple that computes it.
pub(super) fn encrypt_int(value: i32, scheme: Scheme, rng: &mut Rng) -> Vec<Insn> {
let (first, second) = match scheme {
Scheme::Xor => {
@ -50,7 +49,7 @@ pub(super) fn encrypt_int(value: i32, scheme: Scheme, rng: &mut Rng) -> Vec<Insn
}
}
/// Разбить `long`-константу (те же три схемы на `l*`-опкодах).
/// Split a `long` constant (the same three schemes on `l*` opcodes).
pub(super) fn encrypt_long(value: i64, scheme: Scheme, rng: &mut Rng) -> Vec<Insn> {
let (first, second) = match scheme {
Scheme::Xor => {
@ -73,7 +72,7 @@ pub(super) fn encrypt_long(value: i64, scheme: Scheme, rng: &mut Rng) -> Vec<Ins
}
}
/// `(a, b, op)` как три инструкции.
/// `(a, b, op)` as three instructions.
fn binary(first: i32, second: i32, op: Arith, prim: Prim) -> Vec<Insn> {
vec![
Insn::Const(Const::Int(first)),
@ -93,7 +92,7 @@ fn binary_long(first: i64, second: i64, op: Arith) -> Vec<Insn> {
]
}
/// `v = ((v >> 1) << 1) | (v & 1)` — работает для любых, включая отрицательные.
/// `v = ((v >> 1) << 1) | (v & 1)` - works for any value, including negatives.
fn shift_form(value: i32) -> Vec<Insn> {
vec![
Insn::Const(Const::Int(value >> 1)),
@ -110,7 +109,7 @@ fn shift_form(value: i32) -> Vec<Insn> {
]
}
/// То же для `long` (величина сдвига — всегда `int`!).
/// The same for `long` (the shift amount is always an `int`!).
fn shift_form_long(value: i64) -> Vec<Insn> {
vec![
Insn::Const(Const::Long(value >> 1)),
@ -127,13 +126,18 @@ fn shift_form_long(value: i64) -> Vec<Insn> {
]
}
/// Opaque-предикат `(C*C + C) & 1 == 0` (истина для любого `C`):
/// `[pred, ifne DEAD, goto MERGE, DEAD: nop, MERGE:]`, дальше — оригинал.
/// Opaque predicate `(C*C + C) & 1 == 0` (true for any `C`).
///
/// Метки выдаёт вызывающий код (свободные номера метода).
/// 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 {
@ -150,6 +154,7 @@ 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 @@
//! Пасс шифрования констант: числа → арифметика, плюс opaque-предикаты.
//! The constants pass: numbers become arithmetic, plus opaque predicates.
//!
//! `float`/`double` не трогаются (битовая точность через целые — отдельно).
//! Мелочь из `iconst`-диапазона (`-1..=5`, `0L/1L`) остаётся как есть:
//! её шифрование только раздувает горячий код.
//! `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.
mod forms;
#[cfg(test)]
mod tests;
use noxis_analysis::ClassHierarchy;
use noxis_classfile::{Const, Insn, Program, compute_frames};
use noxis_analysis::{ClassHierarchy, JdkHierarchy};
use noxis_classfile::{Const, Insn, MAX_METHOD_INSNS, 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,17 +30,18 @@ impl Pass for ConstantsPass {
for name in &cfg.schemes {
schemes.push(
Scheme::parse(name)
.ok_or_else(|| pass_error(format!("неизвестная схема `{name}`")))?,
.ok_or_else(|| pass_error(format!("unknown scheme `{name}`")))?,
);
}
if schemes.is_empty() {
return Err(pass_error("нет схем шифрования"));
return Err(pass_error("no encryption schemes"));
}
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
@ -55,25 +56,34 @@ impl Pass for ConstantsPass {
let Some(code) = method.code.as_mut() else {
continue;
};
let mut fresh = Vec::with_capacity(code.insns.len());
let original = std::mem::take(&mut code.insns);
let mut fresh = Vec::with_capacity(original.len());
let mut touched = false;
for insn in code.insns.drain(..) {
for insn in &original {
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),
other => fresh.push(other.clone()),
}
}
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);
@ -84,27 +94,31 @@ 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, &hierarchy)?;
refresh_frames(program, *ci, *mi, &frames)?;
}
Ok(report(replaced, predicates, skipped))
}
}
/// Мелочь, которую шифровать невыгодно (уже `iconst`).
/// Trivia that is not worth encrypting (already `iconst`).
fn is_tiny_int(value: i32) -> bool {
(-1..=5).contains(&value)
}
/// Opaque-предикаты в начало методов с кодом (не больше лимита на метод).
/// Opaque predicates at the top of methods with code (at most the limit).
/// Oversized methods stay fully untouched, predicates included.
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,
@ -116,6 +130,9 @@ 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()
@ -123,7 +140,7 @@ fn insert_predicates(
if empty_or_missing {
continue;
}
let missing = || pass_error("метод пропал при вставке предиката");
let missing = || pass_error("method vanished while inserting a predicate");
let mut top = program.classes[ci]
.methods
.get(mi)
@ -166,25 +183,25 @@ fn insert_predicates(
Ok(())
}
/// Пересчитать фреймы затронутого метода.
/// Recompute the frames of a touched method.
fn refresh_frames(
program: &mut Program,
ci: usize,
mi: usize,
hierarchy: &ClassHierarchy,
hierarchy: &JdkHierarchy<'_>,
) -> Result<(), CoreError> {
let (name, snapshot) = {
let class = program
.classes
.get(ci)
.ok_or_else(|| pass_error("класс пропал"))?;
.ok_or_else(|| pass_error("class vanished"))?;
(
class.this_class.clone(),
class
.methods
.get(mi)
.cloned()
.ok_or_else(|| pass_error("метод пропал"))?,
.ok_or_else(|| pass_error("method vanished"))?,
)
};
let frames =
@ -194,7 +211,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("метод пропал"))?
.ok_or_else(|| pass_error("method vanished"))?
.frames = frames;
Ok(())
}
@ -205,7 +222,7 @@ fn report(replaced: usize, predicates: usize, skipped: usize) -> PassReport {
transformed: replaced + predicates,
skipped,
notes: vec![format!(
"констант разбито: {replaced}, предикатов: {predicates}"
"constants split: {replaced}, predicates: {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, Prim, Program, Version};
use noxis_classfile::{ClassBuilder, Code, Const, Insn, MAX_METHOD_INSNS, 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!("не та тройка: {insns:?}"),
_ => panic!("not a triple: {insns:?}"),
}
}
[
@ -30,7 +30,7 @@ fn eval_int(insns: &[Insn]) -> i32 {
Insn::Const(Const::Int(b)),
Insn::Binary { .. },
] => (a << 1) | (b & 1),
_ => panic!("не форма: {insns:?}"),
_ => panic!("not a form: {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,16 +96,54 @@ fn constants_split_and_predicated() {
.apply(&mut ctx, &mut program)
.expect("constants");
let code = program.classes[0].methods[0].code.as_ref().expect("код");
let code = program.classes[0].methods[0].code.as_ref().expect("code");
let has = |v: i32| code.insns.contains(&Insn::Const(Const::Int(v)));
assert!(!has(100), "исходная константа уцелела");
assert!(has(3), "мелочь тронута");
assert!(!has(100), "source constant survived");
assert!(has(3), "trivia touched");
assert!(
!code.insns.contains(&Insn::Const(Const::Long(10))),
"long уцелел"
"long survived"
);
// Opaque-предикат: мёртвая ветвь из `nop`.
assert!(code.insns.contains(&Insn::Nop), "нет предиката");
assert!(report.transformed >= 3, "мало трансформаций: {report:?}");
// Opaque predicate: a dead branch made of `nop`.
assert!(code.insns.contains(&Insn::Nop), "no predicate");
assert!(report.transformed >= 3, "few transforms: {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,26 +1,28 @@
//! Пасс отладочной информации: удаление и ложная подмена.
//! The debug-info pass: removal and false replacement.
//!
//! Источник требований — `info/evo-weaknesses.md` §3: у разобранного
//! образца оригинальные `SourceFile` у 160 классов, 10 218 `LineNumberTable`
//! и имена локальных переменных. Это дешевле всего чинить и дороже всего
//! отдавать.
//! 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.
//!
//! Важно: удалять недостаточно. Инструменты (JADX/CFR) верят отладке сильнее,
//! чем байткоду, поэтому `spoof_source_file` подставляет **ложное** имя —
//! консистентное, но не связанное с реальным исходником.
//! 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.
use noxis_classfile::{Attribute, ClassFile, Code, Method, Program};
use noxis_core::{Context, CoreError, DebugConfig, Pass, PassId, PassReport};
use noxis_core::{Context, CoreError, DebugConfig, Pass, PassId, PassReport, Rng};
use crate::namegen::NameGenerator;
/// Атрибут уровня класса/метода, который мы выкидываем как «сырой».
/// A class/method-level attribute dropped as "raw".
const ENCLOSING_METHOD: &str = "EnclosingMethod";
/// Атрибут уровня метода с именами параметров (`-parameters`).
/// A method-level attribute holding parameter names (`-parameters`).
const METHOD_PARAMETERS: &str = "MethodParameters";
/// Пасс отладочной информации.
/// The debug-info pass.
#[derive(Debug, Default, Clone, Copy)]
pub struct DebugInfoPass;
@ -34,11 +36,14 @@ 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);
@ -47,6 +52,7 @@ 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);
}
}
@ -57,29 +63,32 @@ impl Pass for DebugInfoPass {
let mut notes = Vec::new();
if stripped > 0 {
notes.push(format!("удалено атрибутов: {stripped}"));
notes.push(format!("attributes removed: {stripped}"));
}
if spoofed > 0 {
notes.push(format!("подменено SourceFile: {spoofed}"));
notes.push(format!("SourceFile spoofed: {spoofed}"));
}
if faked > 0 {
notes.push(format!("line numbers faked: {faked}"));
}
Ok(PassReport {
pass: PassId::DebugInfo,
transformed: stripped + spoofed,
transformed: stripped + spoofed + faked,
skipped: 0,
notes,
})
}
}
/// Оставляет только атрибуты, для которых `keep` вернул `true`.
/// Keep only the attributes for which `keep` returns true.
fn retain(attrs: &mut Vec<Attribute>, keep: impl FnMut(&Attribute) -> bool) -> usize {
let before = attrs.len();
attrs.retain(keep);
before - attrs.len()
}
/// Тела методов: `LineNumberTable`, `LocalVariableTable`.
/// Method bodies: `LineNumberTable`, `LocalVariableTable`.
fn strip_code(code: &mut Code, cfg: &DebugConfig) -> usize {
retain(&mut code.attributes, |attr| match attr {
Attribute::LineNumberTable(_) => !cfg.strip_line_numbers,
@ -90,7 +99,7 @@ fn strip_code(code: &mut Code, cfg: &DebugConfig) -> usize {
})
}
/// Уровень класса/метода/поля: `Signature`, `InnerClasses`, `EnclosingMethod`.
/// Class/method/field level: `Signature`, `InnerClasses`, `EnclosingMethod`.
fn strip_signatures(attrs: &mut Vec<Attribute>, cfg: &DebugConfig) -> usize {
if !cfg.strip_signatures {
return 0;
@ -103,7 +112,7 @@ fn strip_signatures(attrs: &mut Vec<Attribute>, cfg: &DebugConfig) -> usize {
})
}
/// Имена параметров метода (`MethodParameters`).
/// Method parameter names (`MethodParameters`).
fn strip_parameters(method: &mut Method, cfg: &DebugConfig) -> usize {
if !cfg.strip_local_variables {
return 0;
@ -115,7 +124,40 @@ fn strip_parameters(method: &mut Method, cfg: &DebugConfig) -> usize {
})
}
/// Подменяет `SourceFile` ложным, но правдоподобным именем.
/// 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.
fn spoof_source_file(class: &mut ClassFile, names: &mut NameGenerator, cfg: &DebugConfig) -> usize {
if !cfg.spoof_source_file {
return 0;
@ -129,118 +171,3 @@ 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

@ -0,0 +1,96 @@
//! 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

@ -0,0 +1,271 @@
//! 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

@ -0,0 +1,230 @@
//! 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

@ -0,0 +1,264 @@
//! 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,10 +1,11 @@
//! # noxis-passes
//!
//! Трансформации байткода. Сборка конвейера из пассов (`standard_pipeline`)
//! живёт здесь же: ядро (`noxis-core`) знает только контракт [`Pass`].
//! Bytecode transformations. The pipeline assembly (`standard_pipeline`)
//! lives here as well: the core (`noxis-core`) only knows the [`Pass`] contract.
pub mod constants;
pub mod debug;
pub mod flow;
pub mod namegen;
pub mod noise;
pub mod rename;
@ -15,24 +16,22 @@ 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;
/// Стандартный конвейер в порядке [`docs/architecture.md`](../../docs/architecture.md):
/// Standard pipeline in [`docs/architecture.md`](../../docs/architecture.md) order:
/// `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>)
}
@ -70,6 +69,7 @@ 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,6 +86,7 @@ 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.
//!
//! Списки вынесены отдельно: к ним обращаются и генератор, и пасс
//! переименования (резервирование keep-имён).
//! Kept in their own file because both the generator and the rename pass
//! reach into them (reserving keep-listed names before generation starts).
/// Жёсткие ключевые слова Java: имя класса/метода не может им совпадать.
/// Hard Java keywords: a class/method name can never collide with these.
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";
/// Визуально неразличимые символы — ядро стиля `IlO0`.
/// Visually indistinguishable characters: the core of the `IlO0` style.
pub(super) const CONFUSABLE: &[u8] = b"IlO01";
/// Unicode-буквы, валидные как Java-идентификаторы (Cyrillic/Greek/CJK).
/// Unicode letters valid in a Java identifier (Cyrillic/Greek/CJK).
pub(super) const UNICODE_LETTERS: &[char] = &[
'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'у', 'ф',
'х', 'ц', 'ч', 'ш', 'щ', 'э', 'ю', 'я', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'λ', 'μ', 'π',
@ -118,15 +118,58 @@ pub(super) const DECOY_RIGHT: &[&str] = &[
"ripple",
];
/// Стиль `Plausible`: домен-нейтральные существительные для классов/полей —
/// похожи на обычный прикладной код, не привязаны к конкретному проекту.
/// `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.
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",
"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",
];
/// Суффиксы ролей для классов (`NounSuffix`, напр. `TextureCache`).
/// Role suffixes for classes (`NounSuffix`, e.g. `TextureCache`).
pub(super) const PLAUSIBLE_SUFFIX: &[&str] = &[
"Manager",
"Handler",
@ -148,8 +191,10 @@ pub(super) const PLAUSIBLE_SUFFIX: &[&str] = &[
"Processor",
"Context",
"Listener",
"Mixin",
"Component",
];
/// Глаголы для методов/полей (`verbNoun`, напр. `resolveToken`).
/// Verbs for methods/fields (`verbNoun`, e.g. `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 @@
//! Генерация имён: стили, анти-ключевые слова, уникальность в scope.
//! Name generation: styles, anti-keyword checks, uniqueness within a scope.
pub mod alphabet;
#[cfg(test)]
@ -13,18 +13,18 @@ use self::alphabet::{
LATIN_UPPER, PLAUSIBLE_NOUN, PLAUSIBLE_SUFFIX, PLAUSIBLE_VERB, UNICODE_LETTERS,
};
/// Генератор имён с гарантированной уникальностью в пределах одного scope.
/// Name generator with guaranteed uniqueness within a single 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 {
}
}
/// Режим «имена классов»: дополнительно избегаем имён из JDK/аннотаций.
/// "Class name" mode: additionally avoid names from the JDK/annotations.
pub fn for_classes(mut self) -> Self {
self.avoid_class = true;
self
}
/// Занять конкретное имя (защита от коллизий с keep-именами).
/// Reserve a specific name (protects against collisions with keep-listed names).
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
}
// Маскируется под обычный прикладной код, а не под мусор:
// классы — `NounSuffix` (`TextureCache`), члены — `verbNoun`
// (`resolveToken`) camelCase.
// Blends in as ordinary application code instead of obvious
// noise: classes get `NounSuffix` (`TextureCache`), members get
// camelCase `verbNoun` (`resolveToken`).
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()), "повтор имени {name}");
assert!(seen.insert(name.clone()), "duplicate name {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}");
// Два слова подряд слиплись в CamelCase без разделителей.
// Two words run together in CamelCase with no separator.
assert!(
name.chars().filter(|c| c.is_ascii_uppercase()).count() >= 2,
"{name}"

View file

@ -0,0 +1,259 @@
//! 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,26 +1,38 @@
//! Пасс шума: junk-классы и вплетание их в граф достижимости.
//! Noise pass: junk classes with real bodies, woven into reachability.
//!
//! Мёртвый код выкидывается shrink-анализом, поэтому каждый junk-класс
//! получает ребро из живого метода (`invokestatic shadow/decoyN.run()V`).
//! 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.
mod body;
mod weave;
use noxis_classfile::{ClassBuilder, Program, Version, empty_code};
use noxis_core::{Context, CoreError, Pass, PassId, PassReport};
#[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_core::{Context, CoreError, Pass, PassId, PassReport};
use weave::weave_first_reachable;
/// Префикс детерминированных имён junk-классов.
const JUNK_PREFIX: &str = "shadow/decoy";
/// Имя и дескриптор точки входа junk-класса.
const JUNK_ENTRY: (&str, &str) = ("run", "()V");
/// Флаги `public static` для junk-метода.
/// Flags for the junk entry (`public static`, callable from live code).
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;
@ -31,6 +43,7 @@ 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;
@ -39,7 +52,7 @@ impl Pass for NoisePass {
pass: PassId::Noise,
transformed: 0,
skipped: 0,
notes: vec!["шум выключен: junk_ratio=0, junk_annotations=0".to_string()],
notes: vec!["noise off: junk_ratio=0, junk_annotations=0".to_string()],
});
}
@ -50,45 +63,100 @@ impl Pass for NoisePass {
let real_classes = program.classes.len();
let count = ratio.saturating_mul(real_classes);
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 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);
junk_names.push(name);
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 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));
}
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)?;
}
let added = junk_names.len();
let mut woven = 0usize;
if weave && added > 0 {
woven = weave_first_reachable(program, real_classes, &junk_names)?;
woven = weave_first_reachable(program, real_classes, &entries)?;
}
let mut skipped = 0usize;
let mut notes = Vec::new();
if added > 0 {
notes.push(format!("добавлено junk-классов: {added}"));
notes.push(format!("junk classes added: {added}"));
}
if woven > 0 {
notes.push(format!("вплетено вызовов: {woven}"));
notes.push(format!("woven calls: {woven}"));
}
if added == 0 && woven == 0 {
notes.push("нечего шуметь: нет классов или методов с кодом".to_string());
notes.push("nothing to fuzz: no classes or methods with code".to_string());
}
if annotations > 0 {
skipped = annotations.saturating_mul(program.classes.len());
notes.push(format!(
"junk_annotations пропущен: сырые атрибуты не могут нести свежие индексы пула (пропущено: {skipped})"
"junk_annotations skipped: raw attributes cannot carry fresh pool indices (skipped: {skipped})"
));
}
@ -105,85 +173,35 @@ impl Pass for NoisePass {
}
}
#[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);
}
/// 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(())
}

View file

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

View file

@ -1,20 +1,23 @@
//! Назначение новых имён: карты, семейства виртуальных методов,
//! пул пакетов и финальное ширинирование доступа.
//! Assigning new names: maps, virtual method families, the package pool,
//! and final access widening.
use std::collections::{BTreeMap, BTreeSet};
use noxis_analysis::{Analysis, ClassHierarchy};
use noxis_analysis::{Analysis, ClassHierarchy, external_dispatch_families};
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)` — как в JVM-ссылке.
/// `(owner, name, descriptor)` - matches a JVM reference.
pub(super) type MemberKey = (String, String, String);
/// Карты переименований одного прогона: `declared` — где объявлено,
/// `alias` — наследники, которые наследуют это имя без своего объявления.
/// `(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.
#[derive(Debug, Default)]
pub(super) struct RenameMaps {
pub(super) classes: BTreeMap<String, String>,
@ -41,7 +44,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
@ -85,19 +88,19 @@ impl RenameMaps {
}
}
/// Переименование виртуальных методов «семейством»: одно имя на всю иерархию,
/// включая мостовые методы с ковариантным возвратом.
pub(super) fn rename_virtual_families(
/// 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(
program: &Program,
analysis: &Analysis,
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();
hierarchy: &ClassHierarchy,
) -> (BTreeMap<FamilyKey, Vec<MemberKey>>, BTreeSet<FamilyKey>) {
let mut families: BTreeMap<FamilyKey, Vec<MemberKey>> = BTreeMap::new();
let mut locked: BTreeSet<FamilyKey> = BTreeSet::new();
for class in &program.classes {
let locked_class = analysis.is_locked(&class.this_class);
@ -113,7 +116,7 @@ pub(super) fn rename_virtual_families(
};
let family = (method.name.clone(), params);
if locked_class || analysis.keep.keeps_member(&method.name) {
locked_families.insert(family.clone());
locked.insert(family.clone());
}
families.entry(family).or_default().push((
class.this_class.clone(),
@ -123,6 +126,22 @@ pub(super) fn rename_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 {
@ -149,8 +168,8 @@ pub(super) fn rename_virtual_families(
renamed
}
/// `(<params>)<ret>` → `(<params>)`, либо `None`, если дескриптор кривой.
fn params_of(descriptor: &str) -> Option<String> {
/// `(<params>)<ret>` → `(<params>)`, or `None` if the descriptor is malformed.
pub(super) fn params_of(descriptor: &str) -> Option<String> {
let close = descriptor.find(')')?;
if !descriptor.starts_with('(') {
return None;
@ -158,7 +177,7 @@ fn params_of(descriptor: &str) -> Option<String> {
Some(descriptor[..=close].to_string())
}
pub(super) fn parent_package(internal: &str) -> String {
pub(crate) fn parent_package(internal: &str) -> String {
match internal.rfind('/') {
Some(i) => internal[..i].to_string(),
None => String::new(),
@ -172,7 +191,8 @@ pub(super) fn simple_name(internal: &str) -> String {
}
}
/// Пул случайных пакетов (2–3 сегмента); при выключенном разбросе — один пустой.
/// Pool of random packages (2-3 segments); a single empty one when spreading
/// is turned off.
pub(super) fn generate_packages(cfg: &Config, rng: &mut Rng) -> Vec<String> {
if !cfg.rename.spread_packages {
return vec![String::new()];
@ -194,7 +214,12 @@ pub(super) fn generate_packages(cfg: &Config, rng: &mut Rng) -> Vec<String> {
.collect()
}
/// Переписать дескриптор/сигнатуру: `Lpkg/Class;` → новое имя класса.
/// 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).
pub(super) fn rewrite_descriptor(desc: &str, classes: &BTreeMap<String, String>) -> String {
if !desc.contains('L') {
return desc.to_string();
@ -207,20 +232,22 @@ 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 == ';' {
if c == ';' || c == '<' {
term = c;
break;
}
name.push(c);
}
out.push('L');
out.push_str(classes.get(&name).map_or(name.as_str(), String::as_str));
out.push(';');
out.push(term);
}
out
}
/// Расширить доступ до `public`, чтобы переезд в другой пакет не ломал вызовы.
/// Widen access to `public` so moving to a different package doesn't break calls.
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.
//!
//! Это самая дешёвая и самая отдающая техника (см. `info/evo-weaknesses.md`:
//! у EvoVis члены не переименовывались вообще, и класс читался по `javap -p`).
//! 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`).
//!
//! Тонкости, которые здесь учитываются:
//! - вызов `Sub.staticMethod()` может указывать владельцем подкласс — нужны
//! псевдонимы (`alias`) для всей иерархии;
//! - мостовые методы (`ACC_BRIDGE`) и ковариантные возвраты живут в одном
//! «семействе» метода — переименовывать их нужно разом;
//! - `serialVersionUID`, JNI, рефлексия, сериализация — не трогаем.
//! 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.
/// Карты и стратегия назначения имён.
mod assign;
/// Переписывание тел методов и атрибутов.
/// Name maps and the assignment strategy.
pub(crate) mod assign;
/// Rewriting method bodies and attributes.
mod rewrite;
/// Интеграционные тесты пасса.
/// Pass integration tests.
#[cfg(test)]
mod tests;
@ -23,7 +23,8 @@ use noxis_classfile::Program;
use noxis_core::{Context, CoreError, Pass, PassId, PassReport, field_key, method_key};
use self::assign::{
RenameMaps, generate_packages, parent_package, rename_virtual_families, simple_name, widen_all,
RenameMaps, build_virtual_families, generate_packages, params_of, parent_package,
rename_virtual_families, simple_name, widen_all,
};
use self::rewrite::rewrite_class;
use crate::namegen::NameGenerator;
@ -35,7 +36,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;
@ -58,7 +59,14 @@ impl Pass for RenamePass {
let mut maps = RenameMaps::default();
let mut renamed_classes = 0usize;
// 1. Имена классов.
// 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.
{
let packages = generate_packages(&cfg, &mut ctx.rng("rename/packages"));
let mut names =
@ -91,7 +99,7 @@ impl Pass for RenamePass {
}
}
// 2. Простые (не-виртуальные) члены: private/static/final.
// 2. Simple (non-virtual) members: private/static/final.
let mut renamed_methods = 0usize;
let mut renamed_fields = 0usize;
@ -117,6 +125,35 @@ 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,
@ -138,8 +175,8 @@ impl Pass for RenamePass {
);
renamed_methods += 1;
}
// Виртуальный не-final: переименовывается только вместе
// со всем семейством (см. rename_virtual_families).
// Non-final virtual: renamed only together with the whole
// family (see rename_virtual_families).
_ => method_names.reserve(method.name.clone()),
}
}
@ -179,28 +216,29 @@ impl Pass for RenamePass {
}
}
// 3. Виртуальные семейства — только в агрессивном режиме.
// 3. Virtual families - aggressive mode only.
if cfg.rename.rename_public_members {
renamed_methods += rename_virtual_families(program, &analysis, &mut maps, &cfg, ctx);
renamed_methods +=
rename_virtual_families(families, locked_families, &mut maps, &cfg, ctx);
}
// 4. Псевдоними для наследников.
// 4. Aliases for subclasses.
maps.expand(&hierarchy, &owners);
// 5. Переписать определения и все ссылки.
// 5. Rewrite definitions and all references.
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. Ширинирование доступа: после переезда в другие пакеты иначе
// возможен IllegalAccessError.
// 6. Access widening: moving across packages could otherwise
// cause IllegalAccessError.
if cfg.rename.widen_access {
widen_all(program);
}
// 7. Маппинги в отчёт (обратная деобфускация stack trace'ей).
// 7. Mappings for the report (stack-trace deobfuscation).
for ((owner, name, desc), new_name) in maps.methods.iter() {
ctx.mapping
.methods
@ -217,7 +255,7 @@ impl Pass for RenamePass {
let locked = analysis.locked_classes.len();
if locked > 0 {
ctx.note(format!("rename: {locked} классов в keep (не тронуты)"));
ctx.note(format!("rename: {locked} keep-listed classes (untouched)"));
}
Ok(PassReport {
@ -225,7 +263,7 @@ impl Pass for RenamePass {
transformed: renamed_classes + renamed_methods + renamed_fields,
skipped: locked,
notes: vec![format!(
"классов: {renamed_classes}, методов: {renamed_methods}, полей: {renamed_fields}"
"classes: {renamed_classes}, methods: {renamed_methods}, fields: {renamed_fields}"
)],
})
}

View file

@ -0,0 +1,60 @@
//! 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,11 +1,12 @@
//! Переписывание тела метода: инструкции, кадры, handler'ы, атрибуты кода.
use noxis_classfile::{Code, Const, Insn};
use noxis_classfile::{Code, 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,
@ -22,10 +23,8 @@ pub(super) fn rewrite_code(
}
for insn in code.insns.iter_mut() {
match insn {
Insn::Const(Const::Class(name)) => {
if let Some(mapped) = maps.classes.get(name.as_str()) {
*name = mapped.clone();
}
Insn::Const(value) => {
super::rewrite_const(value, maps);
}
Insn::GetStatic {
owner,
@ -61,22 +60,33 @@ pub(super) fn rewrite_code(
descriptor,
..
} => {
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();
}
rewrite_method_ref(owner, name, descriptor, maps);
}
// 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::CheckCast(name)
| Insn::InstanceOf(name)
| Insn::ANewArray(name) => {
Insn::New(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

@ -0,0 +1,58 @@
//! 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,7 +1,13 @@
//! Переписывание одного класса: имена, дескрипторы, код, атрибуты.
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};
@ -134,6 +140,42 @@ 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