# 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/ ├── Makefile # builds everything (see below) ├── tools/gen_class.py # bytecode stub generator (self-contained) ├── tools/gen_jar_lists.py # regenerates the jars/*.txt lists from the Gradle cache ├── docs/opcodes.html # JVM bytecode opcode reference (for gen_class.py work) ├── stubs/ │ ├── src/kotlin/proxy/KotlinProxyLog.java # the logger the stubs call │ ├── src/kotlin/proxy/KotlinProxyOverrides.java # per-method custom return values │ ├── src/kotlin/proxy/ProxyPerformanceManager.java # override support class │ └── classes_min/ # generated .class files (build output) ├── jars/ │ ├── defs.txt # all kotlin- jars, sorted (definition lookup) │ ├── scan.txt # AGP core jars (which kotlin classes AGP touches) │ ├── fallback.txt # other cached KGP versions (definition lookup only) │ └── .stamp # versions the lists were generated for (drift detection) ├── dist/kotlin-proxy-compiler-stubs.jar # the artifact └── test_project/ # AGP test app that consumes the jar ``` ## Building `dist/kotlin-proxy-compiler-stubs.jar` ```bash make ``` from the repo root (requires JDK 11+ and Python 3). The Makefile regenerates `jars/*.txt` via `tools/gen_jar_lists.py` whenever the pinned versions (its `KOTLIN_VERSION` / `AGP_VERSION` vars — keep in sync with `test_project/gradle/libs.versions.toml`) drift from `jars/.stamp`, then runs the three steps below. The Gradle cache must already hold the pinned versions — run `test_project` once first (even a red build resolves everything). The three steps, manually: ### 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 real classes into the same tree ```bash javac -nowarn -proc:none -d stubs/classes_min \ -cp "$(grep -v '^[[:space:]]*#' jars/defs.txt | tr '\n' ':')" \ stubs/src/kotlin/proxy/KotlinProxyLog.java \ stubs/src/kotlin/proxy/KotlinProxyOverrides.java \ stubs/src/kotlin/proxy/ProxyPerformanceManager.java ``` `KotlinProxyLog` (the logger every stub calls), `KotlinProxyOverrides` (the per-method return-value hook you implement against), and `ProxyPerformanceManager` (an override support class the hook returns) are the only real classes in the jar. The `-cp` puts the real compiler jars on javac's classpath so your overrides may import compiler types (`CommonCompilerArguments`, `Services`, …). (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: 7 class files + manifest ``` $ jar tf dist/kotlin-proxy-compiler-stubs.jar | grep -v '/$' META-INF/MANIFEST.MF kotlin/proxy/KotlinProxyLog.class kotlin/proxy/KotlinProxyOverrides.class kotlin/proxy/KotlinProxyOverrides$Compiler.class kotlin/proxy/ProxyPerformanceManager.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). Both files are auto-generated by `tools/gen_jar_lists.py`: `defs.txt` holds every `org.jetbrains.kotlin` jar at the pinned Kotlin version, sorted by jar name — the sort keeps `kotlin-compiler-*` ahead of `kotlin-gradle-plugin`, which bundles its own byte-different copies of some compiler classes (the compiler jar must win, it's what the daemon loads); `fallback.txt` adds other cached KGP versions, newest first, for definitions missing from the pinned set. - `--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 - **``** (classes only): calls `KotlinProxyLog.loaded(dotname)` — proves the stub shadowed the real class — and, when the class has a Kotlin companion object, mirrors the real ``'s companion init (`new Companion; dup; aconst_null; invokespecial; putstatic` — Kotlin builds the companion in the enclosing class's static initializer; leaving the static null makes real code touching `.Companion` NPE before any stub method is ever called). - **Constructors:** `super()` (or `Enum.("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`): build an `Object[]` of the call's arguments (references as-is, primitives boxed — so position `i` is parameter `i`; `null` for a param-less method), then ask `KotlinProxyLog.returnValue(member, owner, retType, args, instance)` + `checkcast`, where `instance` is the receiver — the stub instance the method was called on (`this`), or `null` for statics. That first dispatches to `KotlinProxyOverrides.invoke` — your per-method custom implementation, see below — and falls back to `KotlinProxyLog.newInstance(retType)`, which 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. ## Implementing a stub method (custom return values) `KotlinProxyOverrides` (a real class in the jar, `stubs/src/kotlin/proxy/`) is the extension point: every stub method with a reference-class return type (other than `String`) asks it for its return value **before** falling back to the default. Implement exactly the methods you want the stub to actually do something for; return `NO_VALUE` for everything else. ```java public static Object invoke(String member, String ownerDotName, String returnDotName, Object[] args, Object instance) { if ("createPerformanceManager".equals(member) && "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler".equals(ownerDotName)) { CommonCompilerArguments a = (CommonCompilerArguments) args[0]; Services services = (Services) args[1]; // build/return whatever this method should return, using the real args // (and `instance`, to keep per-compiler-instance state) return new MyPerformanceManager(); } return NO_VALUE; } ``` - `member` / `ownerDotName` identify the method; `returnDotName` is its **declared** return type (what the generated body `checkcast`s the result to — your value must be assignable to it, or `ClassCastException`). - `args[i]` is the `i`-th parameter of the call, so your implementation works on the **real** arguments the daemon handed the compiler: reference types as-is, primitives boxed (`Integer`, `Long`, `Boolean`, …). A param-less method gets `args == null`. - `instance` is the receiver — the stub instance the method was called on (the daemon's `K2JVMCompiler` object) — so you can keep per-compiler state across calls (identity-keyed, e.g. in an `IdentityHashMap`). It is `null` for static methods (e.g. everything on the `K2JVMCompilerKt` file facade). - Returning `NO_VALUE` keeps the default (real no-arg instance, or null). An override is logged as `OVERRIDE . [inst=0x…] -> ` — the `inst` tag (the receiver's `identityHashCode`, omitted for statics) lets you correlate which compiler instance a method ran on. Rebuild with steps **2–3** after editing (no need to re-run the generator). Your overrides may reference the real compiler types — they resolve from the real jars on the daemon classpath; compile `KotlinProxyOverrides.java` with the jars from `jars/defs.txt` on `javac`'s classpath if you import them. ## Using the jar in a build The daemon is a separate JVM. Since **KGP ≥ 2.3.20** it runs JVM compilation through the **Build Tools API (BTA) by default**, and the daemon's JVM classpath is the resolved **`kotlinBuildToolsApiClasspath`** configuration (default deps: `kotlin-build-tools-compat` + `kotlin-build-tools-impl`, whose transitive closure *is* the compiler — 15 jars at 2.4.21). Like any `defaultDependencies`-seeded configuration, adding **any** regular dependency suppresses the defaults, so re-declare the same 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 kotlinVersion = "2.4.21" // from libs.versions.toml in the test project afterEvaluate { // BTA path (the default since KGP 2.3.20): the daemon classpath val bta = configurations.getByName("kotlinBuildToolsApiClasspath") bta.dependencies.add(dependencies.create(files(proxyStub))) bta.dependencies.add(dependencies.create( "org.jetbrains.kotlin:kotlin-build-tools-compat:$kotlinVersion")) bta.dependencies.add(dependencies.create( "org.jetbrains.kotlin:kotlin-build-tools-impl:$kotlinVersion")) // legacy path (kotlin.compiler.runViaBuildToolsApi=false; deprecated, // removed in KGP 2.5.0) — shadow it the same way, with the full // kotlinCompilerClasspath default closure re-declared } ``` The legacy `kotlinCompilerClasspath` (what the daemon used before 2.3.20) still exists; its closure is the classic `kotlin-compiler-embeddable` + transitives set (`kotlin-stdlib`, `kotlin-script-runtime`, `kotlin-reflect:1.6.10`, `kotlin-daemon-embeddable`, `kotlinx-coroutines-core-jvm:1.8.0`, `org.jetbrains:annotations:13.0`) and the test project shadows it too. Two more pins, both in the root `build.gradle.kts` buildscript: the stub jar is declared **before** AGP/KGP on the buildscript classpath, and KGP is declared explicitly (`org.jetbrains.kotlin:kotlin-gradle-plugin:`) because **AGP 9.x's built-in Kotlin** applies its own pinned KGP version — an explicit buildscript classpath dep upgrades it (AGP 9.0 release notes, "Runtime dependency on Kotlin Gradle plugin"). 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** (under BTA: "Internal compiler error" — the stub returns defaults/null, so the real compiler machinery fails 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. (A *green* build means the stub is not being loaded — that's a failure state, not success.) The daemon's full argument dump ("Starting compilation with args: …") is in `/tmp/kotlin-daemon.*.log`; stale daemons hold stale classpaths, so kill them (`pkill -f 'KotlinCompile[D]aemon'`) and `rm /tmp/kotlin-proxy-marker.txt` when re-verifying. ## 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` | `/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 | LOAD org.jetbrains.kotlin.cli.jvm.K2JVMCompiler$Companion <- file:…/dist/kotlin-proxy-compiler-stubs.jar RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler$Companion. RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler. ``` (Under the BTA flow the daemon drives compilation through its own `CompileServiceImpl` with arguments it builds itself, so the stub's `createArguments`/`execute` may never be *called* — the crash happens in the real incremental machinery after construction. Under the legacy `runViaBuildToolsApi=false` path you additionally see `CALL …createArguments` and friends, with the boundary args dumped.) - `LOAD <- ` — the stub class was initialized, from our jar. - `CALL .` — the stub member was invoked. - `CALL . arg=` — boundary argument: compiler-argument objects are dumped via `toCommonList()`; other objects via their non-null fields across the hierarchy. - `OVERRIDE . [inst=0x…] -> ` — a `KotlinProxyOverrides.invoke` implementation supplied the return value (logged once, in `KotlinProxyLog.returnValue`); `inst` is the receiver instance's `identityHashCode` (omitted for static calls), so you can see which compiler instance the method ran on. A `newInstance FAIL : ` 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 → `make` (steps 1–3). - Changed `KotlinProxyLog.java` → steps 2–3 (or all three; step 1 is idempotent). - Bumped the Kotlin/AGP version → update `test_project/gradle/libs.versions.toml` (what the build uses) and the Makefile's `KOTLIN_VERSION` / `AGP_VERSION` (what the jar lists are generated for), run the test_project once so Gradle primes the cache with the new jars (even a red build), then `make` — it detects the drift against `jars/.stamp` and regenerates `jars/*.txt` via `tools/gen_jar_lists.py` before regenerating the stubs.