1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
# 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-<version> 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
- **`<clinit>`** (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 `<clinit>`'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 `<This>.Companion` NPE before any stub method is ever called).
- **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`): 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 <owner>.<member> [inst=0x…] -> <dump>` — 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:<version>`)
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` | `<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 | 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.<init>
RMI TCP Connection(2)-127.0.0.1 | CALL org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.<init>
```
(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 <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.
- `OVERRIDE <name>.<member> [inst=0x…] -> <dump>` — 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 <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 → `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.
|