diff --git a/Cargo.lock b/Cargo.lock
index 364e024..a1ac432 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -310,6 +310,7 @@ dependencies = [
"noxis-core",
"noxis-structure-check",
"regex",
+ "serde_json",
"thiserror",
"tracing",
]
@@ -355,6 +356,7 @@ dependencies = [
"noxis-core",
"noxis-runtime",
"noxis-structure-check",
+ "serde_json",
"thiserror",
"tracing",
]
diff --git a/NOTICE.md b/NOTICE.md
index b059baf..7451839 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -1,8 +1,8 @@
-# NOTICE — сторонние компоненты
+# NOTICE - сторонние компоненты
Проект `noxis` распространяется по лицензии AGPL-3.0-only
(см. [`LICENSE`](LICENSE)).
-Ниже — компоненты third-party, которые используются напрямую и чьи
+Ниже - компоненты third-party, которые используются напрямую и чьи
лицензионные условия обязательны к сохранению.
## ristretto_classfile
diff --git a/README.md b/README.md
index 4d592b6..72b20a2 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,7 @@
| пассы: rename, resources, strings, constants, noise, debug | ✅ |
| верификация: red-паттерны, `java -Xverify:all`, метрики | ✅ |
| CLI (`obfuscate` / `analyze` / `patterns`) | ✅ |
-| пасс flow (кадры готовы, схем флаттенинга пока нет) | 🚧 |
+| пасс flow (кадры готовы, 4 схемы: state-spread, computed-switch, butterfly, exception-goto) | ✅ |
Подробности в [`docs/architecture.md`](docs/architecture.md), план в [`todo.md`](todo.md).
@@ -50,12 +50,8 @@ cargo run -p noxis -- patterns --input output.jar
```
`obfuscate` по умолчанию включает все готовые пассы. Флаги `--no-rename`,
-`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`
-выключают их по отдельности. `--no-flow` честно падает с ошибкой: пасса пока нет.
-
-Одно `cargo build` уже гоняет проверку структуры кода: `.rs`-файл длиннее
-250 строк или директория с больше чем 4 `.rs`-файлами ломают сборку.
-Документация (`docs/**`) под это правило не попадает. Правила в [`docs/README.md`](docs/README.md).
+`--no-strings`, `--no-constants`, `--no-noise`, `--no-resources`, `--no-debug-info`,
+`--no-flow` выключают их по отдельности.
## Структура
diff --git a/crates/noxis-analysis/Cargo.toml b/crates/noxis-analysis/Cargo.toml
index 40224a6..4a65dac 100644
--- a/crates/noxis-analysis/Cargo.toml
+++ b/crates/noxis-analysis/Cargo.toml
@@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
regex = { workspace = true }
+serde_json = { workspace = true }
noxis-classfile = { workspace = true }
noxis-core = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/noxis-analysis/src/JdkHierarchy.java b/crates/noxis-analysis/src/JdkHierarchy.java
new file mode 100644
index 0000000..65f9707
--- /dev/null
+++ b/crates/noxis-analysis/src/JdkHierarchy.java
@@ -0,0 +1,34 @@
+import java.util.Scanner;
+
+/**
+ * Answers superclass queries from the obfuscator's frame analysis.
+ *
+ *
Protocol: one internal class name per line on stdin
+ * ({@code java/io/BufferedReader}); one line back on stdout - the direct
+ * superclass as an internal name, or an empty line when unknown
+ * (missing dependency, interface, primitive, array). A single process
+ * serves the whole analysis run; EOF on stdin ends it.
+ */
+public class JdkHierarchy {
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+ while (in.hasNextLine()) {
+ String name = in.nextLine().trim().replace('/', '.');
+ String sup = "";
+ if (!name.isEmpty()) {
+ try {
+ Class> loaded =
+ Class.forName(name, false, JdkHierarchy.class.getClassLoader());
+ Class> parent = loaded.getSuperclass();
+ if (parent != null) {
+ sup = parent.getName().replace('.', '/');
+ }
+ } catch (Throwable ignored) {
+ // Unknown: not on the JDK classpath, an interface with
+ // no superclass, a primitive or an array - empty line.
+ }
+ }
+ System.out.println(sup);
+ }
+ }
+}
diff --git a/crates/noxis-analysis/src/entrypoints.rs b/crates/noxis-analysis/src/entrypoints.rs
index f559d1f..93349c0 100644
--- a/crates/noxis-analysis/src/entrypoints.rs
+++ b/crates/noxis-analysis/src/entrypoints.rs
@@ -24,7 +24,7 @@ pub struct Entrypoints {
}
impl Entrypoints {
- /// Собрать entrypoint'ы по программе (без keep-правил — их добавляет [`Self::merge`]).
+ /// Собрать entrypoint'ы по программе (без keep-правил - их добавляет [`Self::merge`]).
pub fn collect(program: &Program) -> Self {
let mut out = Self::default();
@@ -101,7 +101,7 @@ fn implements_serializable(program: &Program, start: &str) -> bool {
return true;
}
let Some(class) = program.class(&name) else {
- // Внешний предок: считаем, что не знаем — консервативно не keep'им.
+ // Внешний предок: считаем, что не знаем - консервативно не keep'им.
continue;
};
if let Some(sup) = &class.super_class {
@@ -130,15 +130,15 @@ fn collect_service_interfaces(program: &Program) -> BTreeSet {
/// Линейный эвристический поиск имён в рефлексивных API.
///
/// Полноценный dataflow не нужен: если рядом с вызовом `Class.forName(...)` /
-/// `getMethod(...)` лежит строковый литерал — это имя видно статически,
+/// `getMethod(...)` лежит строковый литерал - это имя видно статически,
/// значит, его нельзя переименовывать.
fn collect_reflective_names(out: &mut Entrypoints, code: &noxis_classfile::Code) {
- /// API, чьи аргументы — **имена классов**.
+ /// API, чьи аргументы - **имена классов**.
const CLASS_API: &[(&str, &str)] = &[
("java/lang/Class", "forName"),
("java/lang/ClassLoader", "loadClass"),
];
- /// API, чьи аргументы — **имена членов** (поле/метод).
+ /// API, чьи аргументы - **имена членов** (поле/метод).
const MEMBER_API: &[(&str, &str)] = &[
("java/lang/Class", "getMethod"),
("java/lang/Class", "getDeclaredMethod"),
diff --git a/crates/noxis-analysis/src/hierarchy.rs b/crates/noxis-analysis/src/hierarchy.rs
index 6a57ea1..b982d8f 100644
--- a/crates/noxis-analysis/src/hierarchy.rs
+++ b/crates/noxis-analysis/src/hierarchy.rs
@@ -40,7 +40,7 @@ impl ClassHierarchy {
.and_then(|n| n.super_class.clone())
}
- /// Есть ли класс в иерархии (в том числе из внешнего classpath — нет).
+ /// Есть ли класс в иерархии (в том числе из внешнего classpath - нет).
pub fn contains(&self, internal_name: &str) -> bool {
self.nodes.contains_key(internal_name)
}
@@ -57,7 +57,7 @@ impl ClassHierarchy {
/// Является ли `child` подклассом `parent` (в пределах программы).
///
- /// Неполная иерархия (внешние зависимости не грузим) — это осознанно:
+ /// Неполная иерархия (внешние зависимости не грузим) - это осознанно:
/// обфускатор работает по артефакту, а не по всему classpath.
pub fn is_subclass_of(&self, child: &str, parent: &str) -> bool {
if child == parent {
@@ -137,10 +137,10 @@ pub enum RenameSafety {
/// Оценка безопасности переименования метода.
///
/// Правила (сознательно консервативные, как в `OBF/InheritanceAnalyzer`):
-/// - ``/`` — никогда;
-/// - `private`/`static`/`final`/`` внутри финального класса — можно;
+/// - ``/`` - никогда;
+/// - `private`/`static`/`final`/`` внутри финального класса - можно;
/// - `public`/`protected`/`package-private`, если класс не `final` и есть
-/// наследники (внутри артефакта или нет) — нельзя, пока нет доказательства.
+/// наследники (внутри артефакта или нет) - нельзя, пока нет доказательства.
pub fn method_rename_safety(
program: &Program,
hierarchy: &ClassHierarchy,
diff --git a/crates/noxis-analysis/src/jdk.rs b/crates/noxis-analysis/src/jdk.rs
new file mode 100644
index 0000000..1e10d95
--- /dev/null
+++ b/crates/noxis-analysis/src/jdk.rs
@@ -0,0 +1,195 @@
+//! JDK superclass fallback for frame merging.
+//!
+//! [`ClassHierarchy`] only knows program classes - deliberately so: rename
+//! safety must stay conservative outside the program. Frame merging has the
+//! opposite need: joins over JDK types (`Reader`/`BufferedReader`, a
+//! multi-catch over `NoSuchMethodException`/`SecurityException`) degrade to
+//! `Object` without the true superclass chain, and the verifier rejects the
+//! poisoned frame at the first typed use (`putfield Reader`, a `Throwable`
+//! parameter). This wrapper answers program classes from the built
+//! hierarchy and asks the running JDK about the rest: one `java` process
+//! (single-file launch, no `javac` needed), a line protocol, answers cached.
+//! Without `java` every answer is `None` - exactly the old behaviour.
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::io::{BufRead, BufReader, BufWriter, Write};
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+
+use noxis_classfile::Hierarchy;
+
+use super::hierarchy::ClassHierarchy;
+
+const HELPER: &str = include_str!("JdkHierarchy.java");
+
+/// Frame-time hierarchy: program first, running JDK second.
+pub struct JdkHierarchy<'a> {
+ inner: &'a ClassHierarchy,
+ shared: RefCell,
+}
+
+#[derive(Default)]
+struct Shared {
+ cache: HashMap>,
+ child: Option,
+ dead: bool,
+}
+
+struct Pipes {
+ rx: BufReader,
+ tx: BufWriter,
+ proc: Child,
+}
+
+impl<'a> JdkHierarchy<'a> {
+ /// Wrap a built program hierarchy (spawns nothing yet).
+ pub fn wrap(inner: &'a ClassHierarchy) -> Self {
+ Self {
+ inner,
+ shared: RefCell::new(Shared::default()),
+ }
+ }
+
+ fn jdk_superclass(&self, name: &str) -> Option {
+ let mut shared = self.shared.borrow_mut();
+ if let Some(cached) = shared.cache.get(name) {
+ return cached.clone();
+ }
+ if shared.dead {
+ return None;
+ }
+ if shared.child.is_none() {
+ match spawn_helper() {
+ Some(pipes) => shared.child = Some(pipes),
+ None => {
+ shared.dead = true;
+ return None;
+ }
+ }
+ }
+ let answer = match query(shared.child.as_mut(), name) {
+ // Transport broke: stop spawning, keep the old behaviour.
+ None => {
+ shared.dead = true;
+ return None;
+ }
+ Some(answer) => answer,
+ };
+ shared.cache.insert(name.to_string(), answer.clone());
+ answer
+ }
+}
+
+impl Hierarchy for JdkHierarchy<'_> {
+ fn superclass(&self, class: &str) -> Option {
+ match self.inner.superclass(class) {
+ Some(known) => Some(known),
+ None => self.jdk_superclass(class),
+ }
+ }
+}
+
+impl Drop for JdkHierarchy<'_> {
+ fn drop(&mut self) {
+ if let Ok(mut shared) = self.shared.try_borrow_mut()
+ && let Some(mut pipes) = shared.child.take()
+ {
+ let _ = pipes.proc.kill();
+ let _ = pipes.proc.wait();
+ }
+ }
+}
+
+/// Whether a `java` runtime exists for the helper.
+fn java_available() -> bool {
+ Command::new("java")
+ .arg("-version")
+ .output()
+ .is_ok_and(|out| out.status.success())
+}
+
+/// Write the helper next to itself atomically-ish (every writer emits
+/// identical bytes) and launch it; a handshake query proves it runs.
+fn spawn_helper() -> Option {
+ if !java_available() {
+ return None;
+ }
+ let path = std::env::temp_dir().join("noxis-jdk-hierarchy.java");
+ let staging = path.with_extension(format!("java.{}", std::process::id()));
+ std::fs::write(&staging, HELPER).ok()?;
+ std::fs::rename(&staging, &path).ok()?;
+ let mut proc = Command::new("java")
+ .arg(&path)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+ let rx = BufReader::new(proc.stdout.take()?);
+ let tx = BufWriter::new(proc.stdin.take()?);
+ let mut pipes = Pipes { rx, tx, proc };
+ // Handshake: `Object` has no superclass; any answer at all means a wrong
+ // runtime (or no source-launch support) - stay silent instead.
+ match query(Some(&mut pipes), "java/lang/Object") {
+ // The child must still be alive: EOF also reads as an empty line.
+ Some(None) if pipes.proc.try_wait().is_ok_and(|exit| exit.is_none()) => Some(pipes),
+ _ => None,
+ }
+}
+
+/// One round trip: `None` - dead transport (child reaped);
+/// `Some(answer)` - the reply, empty string for unknown superclasses.
+fn query(pipes: Option<&mut Pipes>, name: &str) -> Option