summaryrefslogtreecommitdiff
path: root/README.md
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-02 22:55:23 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-02 22:55:52 +0100
commit2a4f2fb7e985a3a733ac5d7a1d107e68538c8e18 (patch)
treedc0d0cf8188b69354bdbcd22f9d298702939d067 /README.md
Initial commit
Diffstat (limited to 'README.md')
-rw-r--r--README.md237
1 files changed, 237 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ff88a88
--- /dev/null
+++ b/README.md
@@ -0,0 +1,237 @@
+# kotlin-proxy
+
+Replace the Kotlin compiler inside an AGP/Gradle build with a stub that
+shadows `org.jetbrains.kotlin.cli.jvm.K2JVMCompiler` on the **Kotlin daemon's**
+classpath. The stub is ABI-identical to the real compiler entry point, logs
+every call (and the compiler arguments it receives) to a file, and returns
+defaults — so the build stays red until you implement your own alternative
+compile inside the stub. **Pure replacement: no passthrough, no fallback.**
+
+```
+kotlin-proxy/
+├── tools/gen_class.py # bytecode stub generator (self-contained)
+├── stubs/
+│ ├── src/kotlin/proxy/KotlinProxyLog.java # the logger the stubs call
+│ └── classes_min/ # generated .class files (build output)
+├── jars/
+│ ├── defs.txt # 28 kotlin-2.2.10 jars (definition lookup)
+│ ├── scan.txt # 6 AGP-9.4.1 jars (which kotlin classes AGP touches)
+│ └── fallback.txt # newer KGP variants (definition lookup only)
+├── dist/kotlin-proxy-compiler-stubs.jar # the artifact
+└── test_project/ # AGP test app that consumes the jar
+```
+
+## Building `dist/kotlin-proxy-compiler-stubs.jar`
+
+Three steps, from the repo root. Requires JDK 11+ and Python 3.
+
+### 1. Generate the stub classes with `gen_class.py`
+
+```bash
+python3 tools/gen_class.py \
+ --scan-jars jars/scan.txt \
+ --def-jars jars/defs.txt \
+ --fallback-jars jars/fallback.txt \
+ --seed-only --no-closure \
+ --seed 'org/jetbrains/kotlin/cli/jvm/K2JVMCompiler,org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$Companion,org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt' \
+ --out stubs/classes_min
+```
+
+This emits exactly the three seeded classes into `stubs/classes_min/`:
+
+| class | role |
+|---|---|
+| `K2JVMCompiler` | the compiler entry point the daemon instantiates |
+| `K2JVMCompiler$Companion` | its Kotlin companion object |
+| `K2JVMCompilerKt` | the file facade (holds `main`) |
+
+`gen_class.py` **wipes `--out` first** and regenerates everything, so the
+output directory must not contain anything you need.
+
+### 2. Compile the logger into the same tree
+
+```bash
+javac -nowarn -proc:none -d stubs/classes_min stubs/src/kotlin/proxy/KotlinProxyLog.java
+```
+
+`KotlinProxyLog` is the one real class in the jar; every generated stub calls
+into it. (Step 1 wiped the directory, so `javac` must run **after** it.)
+
+### 3. Package the jar
+
+```bash
+jar cf dist/kotlin-proxy-compiler-stubs.jar -C stubs/classes_min .
+```
+
+Result: 4 class files + manifest
+
+```
+$ jar tf dist/kotlin-proxy-compiler-stubs.jar | grep -v '/$'
+META-INF/MANIFEST.MF
+kotlin/proxy/KotlinProxyLog.class
+org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$Companion.class
+org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class
+org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt.class
+```
+
+Sanity-check the generated bytecode:
+
+```bash
+javap -c stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class
+```
+
+## How `gen_class.py` works
+
+Instead of emitting Java source (and fighting `javac`'s generics checker over
+erasure bridges it forbids), it emits `.class` files directly, copying the real
+class's **erased structure verbatim**: exact superclass/interfaces, every
+field, every method (including synthetic `$default` helpers and erasure
+bridges) with its exact name + descriptor + access flags. The `Signature`
+attribute is omitted entirely, so there are no generics and no generics
+clashes. The JVM links by name + erased descriptor, both copied verbatim, so
+the stub is ABI-identical to the real class.
+
+Bodies are straight-line (no branches), so no `StackMapTable` frames are needed.
+
+### Inputs
+
+The list files contain one jar path per line; `#` starts a comment.
+
+- `--def-jars` / `--fallback-jars` — the definition source. Every `.class` in
+ these jars is parsed into a `name → info` map (first jar wins). `defs.txt`
+ holds the full 2.2.10 set (KGP first for priority); `fallback.txt` adds newer
+ KGP variants for definitions not present in 2.2.10.
+- `--scan-jars` — AGP jars. Only used when **not** in `--seed-only` mode: their
+ Kotlin class references form the seed set S0.
+
+### Options
+
+| flag | meaning |
+|---|---|
+| `--scan-jars L` | list file of jars to scan for S0 (AGP jars) |
+| `--def-jars L` | list file of jars for definition lookup (required) |
+| `--fallback-jars L` | extra definition-lookup list (optional) |
+| `--out DIR` | output directory, wiped and recreated (required) |
+| `--report FILE` | write the generation report to FILE |
+| `--seed a,b,c` | add classes (dotted or internal names) to S0 |
+| `--seed-only` | use only `--seed` as S0; ignore `--scan-jars` and the KGP plugin entry points |
+| `--no-closure` | emit exactly the seed set; don't expand the transitive closure |
+| `--exclude prefix[,prefix]` | skip internal-name prefixes (leave that subtree real) |
+
+### Generation modes
+
+- **Trio (used for the daemon jar):** `--seed-only --no-closure --seed ...`
+ emits exactly the seeded classes. Their superclasses/interfaces (e.g.
+ `CLICompiler`, `K2JVMCompilerArguments`) are **not** stubbed — they resolve
+ from the real jars later on the daemon classpath.
+- **Full closure (default):** S0 = Kotlin classes referenced by the `--scan-jars`
+ AGP jars + KGP plugin entry points from `META-INF/gradle-plugins/*.properties`,
+ then expanded transitively through each class's constant-pool references.
+ Classes without a definition in the def jars get a *minimal* stub (bare
+ structure + no-arg ctor + `loaded()` clinit); classes with a definition get a
+ full structural copy.
+
+### What each generated member does
+
+- **`<clinit>`** (classes only): calls `KotlinProxyLog.loaded(dotname)` — proves
+ the stub shadowed the real class.
+- **Constructors:** `super()` (or `Enum.<init>("stub", 0)` for enums), then log.
+ A public no-arg ctor is synthesized if the real class lacks one, so child
+ stubs can `invokespecial super()`.
+- **Concrete methods:** call
+ `KotlinProxyLog.call(member, dotName)` — or the 3-arg overload passing the
+ **first reference parameter**, so the log shows the boundary argument
+ (typically `K2JVMCompilerArguments`), then produce the return value:
+ - reference-class returns (except `String`): `KotlinProxyLog.newInstance(retType)`
+ + `checkcast` — reflectively instantiates the real (un-stubbed) return
+ class so the daemon can proceed (e.g. `createArguments()` yields a real
+ `K2JVMCompilerArguments`). Types without a usable no-arg ctor (interfaces,
+ enums, abstract) yield `null`, as before.
+ - everything else: the JVM default (`0`, `null`, …).
+- **Param-less erasure bridges:** forward to their concrete sibling (same name,
+ narrower return type) instead of logging + null — the daemon dispatches
+ through bridges (e.g. `createArguments()CommonCompilerArguments`, whose
+ abstract return can't be instantiated), so the bridge must behave like the
+ real one: call the concrete method.
+- **Abstract methods / interface methods:** no body.
+
+## Using the jar in a build
+
+The daemon is a separate JVM. Its compiler classpath comes from the Gradle
+configuration `kotlinCompilerClasspath`, which KGP seeds via hidden
+`defaultDependencies` (0 declared deps → 7 resolved jars). Adding **any**
+regular dependency suppresses those defaults, so re-declare the real compiler
+modules as regular dependencies **with the stub jar first** — the daemon then
+loads `K2JVMCompiler` from the stub:
+
+```kotlin
+// app/build.gradle.kts
+val proxyStub = file("/home/the_jk/source/kotlin_proxy/dist/kotlin-proxy-compiler-stubs.jar")
+val realCompilerJars = listOf(
+ "org.jetbrains.kotlin:kotlin-compiler-embeddable:2.2.10",
+ "org.jetbrains.kotlin:kotlin-stdlib:2.2.10",
+ "org.jetbrains.kotlin:kotlin-script-runtime:2.2.10",
+ "org.jetbrains.kotlin:kotlin-reflect:1.6.10",
+ "org.jetbrains.kotlin:kotlin-daemon-embeddable:2.2.10",
+ "org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.8.0",
+ "org.jetbrains:annotations:13.0",
+)
+afterEvaluate {
+ val cfg = configurations.getByName("kotlinCompilerClasspath")
+ cfg.dependencies.add(dependencies.create(files(proxyStub)))
+ realCompilerJars.forEach { cfg.dependencies.add(dependencies.create(it)) }
+}
+```
+
+and in `gradle.properties`:
+
+```properties
+kotlin.compiler.execution.strategy=daemon
+# PURE REPLACEMENT: don't fall back to in-process when the stub "fails"
+kotlin.daemon.useFallbackStrategy=false
+```
+
+Expected outcome: `:app:compileDebugKotlin` **fails** (the stub returns
+defaults/null, so the real `CLICompiler` machinery NPEs after calling into the
+stub) — that's the point. The stub is the only compiler; the build goes green
+only once the stub implements its own compile.
+
+## Reading the log
+
+`KotlinProxyLog` honors three system properties (pass them to the daemon JVM
+via `org.gradle.jvmargs` or the daemon's own args):
+
+| property | default | meaning |
+|---|---|---|
+| `kotlin.proxy.log` | `<user.dir>/build/kotlin-proxy.log` | main log file |
+| `kotlin.proxy.log.mode` | `all` | `all` \| `classes` (loads only) \| `off` |
+| `kotlin.proxy.marker` | `/tmp/kotlin-proxy-marker.txt` | fixed-path copy of every line |
+
+The marker file is what proves the stub ran **inside the out-of-process
+daemon** (its thread name is `RMI TCP Connection(N)`), regardless of the
+daemon's working directory or missing `-Dkotlin.proxy.log`:
+
+```
+RMI TCP Connection(2)-127.0.0.1 | LOAD org.jetbrains.kotlin.cli.jvm.K2JVMCompiler <- file:…/dist/kotlin-proxy-compiler-stubs.jar
+RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.<init>
+RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.createArguments
+RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.createPerformanceManager arg=K2JVMCompilerArguments{destination=… classpath=… freeArgs=[…/Hello.kt] …}
+```
+
+- `LOAD <name> <- <codesource>` — the stub class was initialized, from our jar.
+- `CALL <name>.<member>` — the stub member was invoked.
+- `CALL <name>.<member> arg=<dump>` — boundary argument: compiler-argument
+ objects are dumped via `toCommonList()`; other objects via their
+ non-null fields across the hierarchy.
+
+A `newInstance FAIL <type> : <exception>` line means a stub method's declared
+return type has no usable no-arg constructor (e.g. `PerformanceManager`), so
+that method returned `null` — expected diagnostic noise, not an error.
+
+## Regenerating after changes
+
+- Changed the seeded class set or a stub's behavior → re-run steps 1–3.
+- Changed `KotlinProxyLog.java` → re-run steps 2–3 (or all three; step 1 is
+ idempotent).
+- Changed a kotlin version → update the jars in `jars/defs.txt` (and the
+ `realCompilerJars` versions in the build script).