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
|
# 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
│ ├── src/kotlin/proxy/KotlinProxyOverrides.java # per-method custom return values
│ └── 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 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
```
`KotlinProxyLog` (the logger every stub calls) and `KotlinProxyOverrides`
(the per-method return-value hook you implement against) 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: 5 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
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`): 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)` + `checkcast`.
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) {
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
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`.
- Returning `NO_VALUE` keeps the default (real no-arg instance, or null).
An override is logged as `OVERRIDE <owner>.<member> -> <dump>`.
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. 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.
- `OVERRIDE <name>.<member> -> <dump>` — a `KotlinProxyOverrides.invoke`
implementation supplied the return value (logged once, in
`KotlinProxyLog.returnValue`).
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).
|