diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-02 22:55:23 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-02 22:55:52 +0100 |
| commit | 2a4f2fb7e985a3a733ac5d7a1d107e68538c8e18 (patch) | |
| tree | dc0d0cf8188b69354bdbcd22f9d298702939d067 | |
Initial commit
57 files changed, 2363 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7773828 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +dist/
\ No newline at end of file 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). diff --git a/jars/defs.txt b/jars/defs.txt new file mode 100644 index 0000000..26903ec --- /dev/null +++ b/jars/defs.txt @@ -0,0 +1,29 @@ +# auto-generated: all org.jetbrains.kotlin 2.2.10 jars (priority order: KGP first) +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/abi-tools-api/2.2.10/d3d684d1dfec17b0c9f0fda875da938d5f304328/abi-tools-api-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-build-statistics/2.2.10/e826d07e18ad23dc3894d40113fd5e79a94f83b3/kotlin-build-statistics-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-build-tools-api/2.2.10/eac607420801deb9abcf71e250ab1ea11b049c06/kotlin-build-tools-api-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-build-tools-impl/2.2.10/6bf34d03b713e0536300b0d507bdd701ba53318c/kotlin-build-tools-impl-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-compiler-embeddable/2.2.10/6882d39ef03b18879c1a5d2a83c2212361bed5fe/kotlin-compiler-embeddable-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-compiler-runner/2.2.10/aee5165d5829687acee89311747076622a05d664/kotlin-compiler-runner-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-daemon-client/2.2.10/9de9722b2ab63b00fed168c924c41ea3b2f7d9c5/kotlin-daemon-client-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-daemon-embeddable/2.2.10/212fd3c2c6e4e5d0f4db3c4191233e2b622380cc/kotlin-daemon-embeddable-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin/2.2.10/5b7032e3454baa99627177ef48a324dbf33d42a3/kotlin-gradle-plugin-2.2.10-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-annotations/2.2.10/45152dbad91398d945afff472498c8610cef5ae5/kotlin-gradle-plugin-annotations-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-api/2.2.10/8b990c8b8a53b5179f6a7a43718079cabac9d4c9/kotlin-gradle-plugin-api-2.2.10-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-api/2.2.10/8b990c8b8a53b5179f6a7a43718079cabac9d4c9/kotlin-gradle-plugin-api-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-idea/2.2.10/a07b350797aa4fe6d4bc6e1be2feecb638e94b13/kotlin-gradle-plugin-idea-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-idea-proto/2.2.10/2caef57b02e64afbcbb276e4f1edb5d9807d8fa4/kotlin-gradle-plugin-idea-proto-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-model/2.2.10/530a4cac0ce3ac72ad548f9128cbae8b5bb22d3e/kotlin-gradle-plugin-model-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-klib-commonizer-api/2.2.10/e7a9a8f5ca3d6027fb86f1df5bb2ce2812b1486a/kotlin-klib-commonizer-api-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-native-utils/2.2.10/6c6650142c8ddaf921ffc46f9757b39681c0c02e/kotlin-native-utils-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-reflect/2.2.10/98d0ca9819d98cb3aa5c0a25793830b6659feee2/kotlin-reflect-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-scripting-common/2.2.10/87769c03c5456d7c827fc950063664907b192c1c/kotlin-scripting-common-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-scripting-compiler-embeddable/2.2.10/25d0e9a886551d4a46ae85d4d5d0088829ef9/kotlin-scripting-compiler-embeddable-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-scripting-compiler-impl-embeddable/2.2.10/3f1bcab651be1ab86e8d240b797b1a05dd8b0027/kotlin-scripting-compiler-impl-embeddable-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-scripting-jvm/2.2.10/beecd90e2b145845581e953ba8420f1b30cac848/kotlin-scripting-jvm-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-script-runtime/2.2.10/712f9bc08f378c13a4a00f0bbb28c76e59183e83/kotlin-script-runtime-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/2.2.10/30de6faa127a4a012db8e71bf1b9c0a99b1402b2/kotlin-stdlib-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-tooling-core/2.2.10/685151c03e638207a3b5045002411fbef78fdeb/kotlin-tooling-core-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-util-io/2.2.10/aa4dc86feb1b0d99f14f0510892ddecf6f6139fd/kotlin-util-io-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-util-klib/2.2.10/82e5679f8609ebd439f96fd708cc8644b5f06f0/kotlin-util-klib-2.2.10.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-util-klib-metadata/2.2.10/aae4449834d66cddf14f0fb5b8867eb422bb52f0/kotlin-util-klib-metadata-2.2.10.jar diff --git a/jars/fallback.txt b/jars/fallback.txt new file mode 100644 index 0000000..915693a --- /dev/null +++ b/jars/fallback.txt @@ -0,0 +1,7 @@ +# fallback: newer variants for definition lookup only +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin/2.4.0/18bfb59ea7d01e0ae925f5a5535e61a98624ed3f/kotlin-gradle-plugin-2.4.0-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin/2.4.10/54e85b6639aa6819abc9985612e470576540e8ec/kotlin-gradle-plugin-2.4.10-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-api/2.4.0/75cef3ce6f6086fd3943cc614158c889b84ce5d1/kotlin-gradle-plugin-api-2.4.0-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-gradle-plugin-api/2.4.10/57abfa0230a1ffc31556110bff4b946b55967ba3/kotlin-gradle-plugin-api-2.4.10-gradle813.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-tooling-core/2.4.0/75970f5a2a9cb4d25557965bbec0a7ccd55bfbcf/kotlin-tooling-core-2.4.0.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-tooling-core/2.4.10/75970f5a2a9cb4d25557965bbec0a7ccd55bfbcf/kotlin-tooling-core-2.4.10.jar diff --git a/jars/scan.txt b/jars/scan.txt new file mode 100644 index 0000000..ed6fc9a --- /dev/null +++ b/jars/scan.txt @@ -0,0 +1,7 @@ +# AGP 9.4.1 jars on the buildscript classpath (the classes "AGP uses") +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/gradle/9.4.1/41c81edd76f786e79cb4807c3435aba3857eca18/gradle-9.4.1.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/gradle-api/9.4.1/ce1f7c278ac4af318446d43fcec073752a84a00a/gradle-api-9.4.1.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/gradle-common-api/9.4.1/188fc42710d4072ae7f02415b497fe311041b555/gradle-common-api-9.4.1.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/gradle-settings-api/9.4.1/fcfedf9a56578511894c869f71eaecafbf5e49e6/gradle-settings-api-9.4.1.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/builder/9.4.1/af1135b3a2fd9c7606e2f0e301348147953e49ef/builder-9.4.1.jar +/home/the_jk/.gradle/caches/modules-2/files-2.1/com.android.tools.build/builder-model/9.4.1/9dd0f1cd71305a2ea484adfc223535ab88aeb72e/builder-model-9.4.1.jar diff --git a/stubs/classes_min/kotlin/proxy/KotlinProxyLog.class b/stubs/classes_min/kotlin/proxy/KotlinProxyLog.class Binary files differnew file mode 100644 index 0000000..398517e --- /dev/null +++ b/stubs/classes_min/kotlin/proxy/KotlinProxyLog.class diff --git a/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$Companion.class b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$Companion.class Binary files differnew file mode 100644 index 0000000..a7ceaea --- /dev/null +++ b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$Companion.class diff --git a/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class Binary files differnew file mode 100644 index 0000000..d8c4787 --- /dev/null +++ b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class diff --git a/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt.class b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt.class Binary files differnew file mode 100644 index 0000000..11e9ddc --- /dev/null +++ b/stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt.class diff --git a/stubs/src/kotlin/proxy/KotlinProxyLog.java b/stubs/src/kotlin/proxy/KotlinProxyLog.java new file mode 100644 index 0000000..49a390e --- /dev/null +++ b/stubs/src/kotlin/proxy/KotlinProxyLog.java @@ -0,0 +1,205 @@ +package kotlin.proxy; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +/** + * Central call log for kotlin-proxy stubs. + * + * Every stub method/constructor and every stub class load is recorded here, + * in order, so you can see exactly which stubs AGP/KGP touch. + * + * System properties: + * kotlin.proxy.log log file path (default: <user.dir>/build/kotlin-proxy.log) + * kotlin.proxy.log.mode "all" (default) | "classes" (class loads only) | "off" + */ +public final class KotlinProxyLog { + + private static BufferedWriter writer; + private static boolean inited = false; + private static final String MODE = System.getProperty("kotlin.proxy.log.mode", "all"); + + private KotlinProxyLog() { + } + + private static synchronized void ensure() { + if (inited) { + return; + } + inited = true; + try { + String path = System.getProperty("kotlin.proxy.log", + System.getProperty("user.dir") + "/build/kotlin-proxy.log"); + File f = new File(path); + if (f.getParentFile() != null) { + f.getParentFile().mkdirs(); + } + writer = new BufferedWriter(new FileWriter(f, true)); + writer.write("# kotlin-proxy log started; mode=" + MODE + "\n"); + } catch (Exception e) { + writer = null; + } + } + + /** Called from a stub class static initializer. Proves the stub shadows the real class. */ + public static void loaded(Class<?> stubClass) { + if ("off".equals(MODE)) { + return; + } + String from = "?"; + try { + if (stubClass.getProtectionDomain().getCodeSource() != null + && stubClass.getProtectionDomain().getCodeSource().getLocation() != null) { + from = stubClass.getProtectionDomain().getCodeSource().getLocation().toString(); + } + } catch (Throwable t) { + // ignore + } + log("LOAD " + stubClass.getName() + " <- " + from); + } + + /** Called from every stub method/constructor body. */ + public static void call(String member, Class<?> stubClass) { + if ("off".equals(MODE) || "classes".equals(MODE)) { + return; + } + log("CALL " + stubClass.getName() + "." + member); + } + + /** + * String-based overload used by the bytecode-generated stubs (they pass + * the dotted class name rather than a Class literal). Resolves the + * already-loaded class to recover its code source location. + */ + public static void loaded(String dotName) { + if ("off".equals(MODE)) { + return; + } + String from = "?"; + try { + Class<?> c = Class.forName(dotName, false, + KotlinProxyLog.class.getClassLoader()); + if (c.getProtectionDomain().getCodeSource() != null + && c.getProtectionDomain().getCodeSource().getLocation() != null) { + from = c.getProtectionDomain().getCodeSource().getLocation().toString(); + } + } catch (Throwable t) { + // ignore + } + log("LOAD " + dotName + " <- " + from); + } + + public static void call(String member, String dotName) { + if ("off".equals(MODE) || "classes".equals(MODE)) { + return; + } + log("CALL " + dotName + "." + member); + } + + /** + * 3-arg overload used by the bytecode stubs to log the boundary: the stub + * passes its first (reference) parameter - typically the compiler + * K2JVMCompilerArguments - so we can see exactly what AGP/KGP handed the + * (replaced) compiler. + */ + public static void call(String member, String dotName, Object arg) { + if ("off".equals(MODE) || "classes".equals(MODE)) { + return; + } + log("CALL " + dotName + "." + member + " arg=" + dump(arg)); + } + + /** + * Called by stub methods that declare a reference return type (other than + * String). Reflectively instantiates the real, un-stubbed class of that + * return type so the caller (the daemon) can keep going: e.g. + * K2JVMCompiler.createArguments() returns a genuine K2JVMCompilerArguments, + * which lets parseCommandLineArguments run and doExecute be reached with the + * fully-populated args (the boundary we want to log). Returns null when the + * type has no usable no-arg constructor (interfaces, enums, abstract, etc.). + */ + public static Object newInstance(String dotName) { + try { + Class<?> c = Class.forName(dotName, false, + KotlinProxyLog.class.getClassLoader()); + return c.getDeclaredConstructor().newInstance(); + } catch (Throwable t) { + log("newInstance FAIL " + dotName + " : " + t + + " | loader=" + KotlinProxyLog.class.getClassLoader()); + return null; + } + } + + /** Reflectively summarize an arbitrary arg object for the log. */ + private static String dump(Object o) { + if (o == null) { + return "null"; + } + try { + // Compiler-argument types expose toCommonList(); show it verbatim. + try { + java.lang.reflect.Method m = o.getClass().getMethod("toCommonList"); + Object list = m.invoke(o); + if (list != null) { + return list.toString(); + } + } catch (Throwable ignore) { + } + // Otherwise dump the non-null declared fields across the hierarchy. + StringBuilder sb = new StringBuilder(o.getClass().getSimpleName()).append('{'); + for (Class<?> c = o.getClass(); c != null && c != Object.class; + c = c.getSuperclass()) { + for (java.lang.reflect.Field f : c.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) { + continue; + } + try { + f.setAccessible(true); + Object v = f.get(o); + if (v == null) { + continue; + } + sb.append(f.getName()).append('=').append(v).append(' '); + } catch (Throwable ignore) { + } + } + } + return sb.append('}').toString(); + } catch (Throwable t) { + try { + return o.toString(); + } catch (Throwable t2) { + return "<unprintable>"; + } + } + } + + private static void log(String line) { + ensure(); + BufferedWriter w = writer; + if (w != null) { + try { + w.write(Thread.currentThread().getName() + " | " + line); + w.newLine(); + w.flush(); // survive JVM exit without a full buffer + } catch (IOException e) { + // logging must never break the build + } + } + // Fixed-path marker: works even when the daemon JVM has no + // -Dkotlin.proxy.log, so we can prove the stub was actually loaded + // in the out-of-process daemon regardless of its working directory. + try { + String marker = System.getProperty("kotlin.proxy.marker", "/tmp/kotlin-proxy-marker.txt"); + synchronized (KotlinProxyLog.class) { + BufferedWriter mw = new BufferedWriter(new java.io.FileWriter(marker, true)); + mw.write(Thread.currentThread().getName() + " | " + line + "\n"); + mw.close(); + } + } catch (Exception e) { + // ignore + } + } +} diff --git a/test_project/.gitignore b/test_project/.gitignore new file mode 100644 index 0000000..261def5 --- /dev/null +++ b/test_project/.gitignore @@ -0,0 +1,16 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +.kotlin +local.properties diff --git a/test_project/.idea/.gitignore b/test_project/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/test_project/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/test_project/.idea/.name b/test_project/.idea/.name new file mode 100644 index 0000000..5e13b80 --- /dev/null +++ b/test_project/.idea/.name @@ -0,0 +1 @@ +TestProject
\ No newline at end of file diff --git a/test_project/.idea/AndroidProjectSystem.xml b/test_project/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/test_project/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="AndroidProjectSystem"> + <option name="providerId" value="com.android.tools.idea.GradleProjectSystem" /> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/codeStyles b/test_project/.idea/codeStyles new file mode 100644 index 0000000..320a4bc --- /dev/null +++ b/test_project/.idea/codeStyles @@ -0,0 +1,137 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ProjectCodeStyleConfiguration"> + <code_scheme name="Project" version="173"> + <JetCodeStyleSettings> + <option name="PACKAGES_TO_USE_STAR_IMPORTS"> + <value> + <package name="java.util" alias="false" withSubpackages="false" /> + <package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" /> + <package name="io.ktor" alias="false" withSubpackages="true" /> + </value> + </option> + <option name="PACKAGES_IMPORT_LAYOUT"> + <value> + <package name="" alias="false" withSubpackages="true" /> + <package name="java" alias="false" withSubpackages="true" /> + <package name="javax" alias="false" withSubpackages="true" /> + <package name="kotlin" alias="false" withSubpackages="true" /> + <package name="" alias="true" withSubpackages="true" /> + </value> + </option> + </JetCodeStyleSettings> + <codeStyleSettings language="XML"> + <indentOptions> + <option name="CONTINUATION_INDENT_SIZE" value="4" /> + </indentOptions> + <arrangement> + <rules> + <section> + <rule> + <match> + <AND> + <NAME>xmlns:android</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>^$</XML_NAMESPACE> + </AND> + </match> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>xmlns:.*</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>^$</XML_NAMESPACE> + </AND> + </match> + <order>BY_NAME</order> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>.*:id</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> + </AND> + </match> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>.*:name</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> + </AND> + </match> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>name</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>^$</XML_NAMESPACE> + </AND> + </match> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>style</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>^$</XML_NAMESPACE> + </AND> + </match> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>.*</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>^$</XML_NAMESPACE> + </AND> + </match> + <order>BY_NAME</order> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>.*</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> + </AND> + </match> + <order>ANDROID_ATTRIBUTE_ORDER</order> + </rule> + </section> + <section> + <rule> + <match> + <AND> + <NAME>.*</NAME> + <XML_ATTRIBUTE /> + <XML_NAMESPACE>.*</XML_NAMESPACE> + </AND> + </match> + <order>BY_NAME</order> + </rule> + </section> + </rules> + </arrangement> + </codeStyleSettings> + </code_scheme> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/compiler.xml b/test_project/.idea/compiler.xml new file mode 100644 index 0000000..bcf4711 --- /dev/null +++ b/test_project/.idea/compiler.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="CompilerConfiguration"> + <bytecodeTargetLevel target="25" /> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/deploymentTargetSelector.xml b/test_project/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..ca16a99 --- /dev/null +++ b/test_project/.idea/deploymentTargetSelector.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="deploymentTargetSelector"> + <selectionStates> + <SelectionState runConfigName="app"> + <option name="selectionMode" value="DROPDOWN" /> + <DialogSelection /> + </SelectionState> + </selectionStates> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/gradle.xml b/test_project/.idea/gradle.xml new file mode 100644 index 0000000..cdbc250 --- /dev/null +++ b/test_project/.idea/gradle.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="GradleSettings"> + <option name="linkedExternalProjectsSettings"> + <GradleProjectSettings> + <option name="testRunner" value="CHOOSE_PER_TEST" /> + <option name="externalProjectPath" value="$PROJECT_DIR$" /> + <option name="modules"> + <set> + <option value="$PROJECT_DIR$" /> + <option value="$PROJECT_DIR$/app" /> + </set> + </option> + </GradleProjectSettings> + </option> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/misc.xml b/test_project/.idea/misc.xml new file mode 100644 index 0000000..29a5cc0 --- /dev/null +++ b/test_project/.idea/misc.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ExternalStorageConfigurationManager" enabled="true" /> + <component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK"> + <output url="file://$PROJECT_DIR$/build/classes" /> + </component> + <component name="ProjectType"> + <option name="id" value="Android" /> + </component> +</project>
\ No newline at end of file diff --git a/test_project/.idea/runConfigurations.xml b/test_project/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/test_project/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="RunConfigurationProducerService"> + <option name="ignoredProducers"> + <set> + <option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" /> + <option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" /> + <option value="com.intellij.execution.junit.PatternConfigurationProducer" /> + <option value="com.intellij.execution.junit.TestInClassConfigurationProducer" /> + <option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" /> + <option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" /> + <option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" /> + <option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" /> + </set> + </option> + </component> +</project>
\ No newline at end of file diff --git a/test_project/app/.gitignore b/test_project/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/test_project/app/.gitignore @@ -0,0 +1 @@ +/build
\ No newline at end of file diff --git a/test_project/app/build.gradle.kts b/test_project/app/build.gradle.kts new file mode 100644 index 0000000..7a9492d --- /dev/null +++ b/test_project/app/build.gradle.kts @@ -0,0 +1,71 @@ +plugins { + id("com.android.application") +} + +android { + namespace = "org.the_jk.testproject" + compileSdk { + version = release(37) + } + + defaultConfig { + applicationId = "org.the_jk.testproject" + minSdk = 26 + targetSdk = 37 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + optimization { + enable = true + packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") + } + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } +} + +dependencies { + implementation(libs.androidx.appcompat) + implementation(libs.androidx.core.ktx) + implementation(libs.material) + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(libs.androidx.junit) +} + +// ---- kotlin-proxy: force our compiler stub to the FRONT of the daemon classpath ---- +// KGP seeds the daemon classpath via `kotlinCompilerClasspath` using +// defaultDependencies (kotlin-compiler-embeddable + transitives). Adding ANY +// regular dependency suppresses those defaults - so we re-declare the real +// compiler modules as regular deps WITH our stub jar FIRST. The daemon then +// loads org.jetbrains.kotlin.cli.jvm.K2JVMCompiler from OUR stub, replacing +// the real compiler with our alternative. +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 { + try { + val cfg = configurations.getByName("kotlinCompilerClasspath") + cfg.dependencies.add(dependencies.create(files(proxyStub))) + realCompilerJars.forEach { cfg.dependencies.add(dependencies.create(it)) } + logger.lifecycle("kotlin-proxy: AGP stub present=" + proxyStub.exists() + + " ORDER=" + cfg.files.joinToString(",") { it.name }) + } catch (t: Throwable) { + logger.lifecycle("kotlin-proxy: AGP injection FAILED: " + t) + } +} diff --git a/test_project/app/src/androidTest/java/org/the_jk/testproject/ExampleInstrumentedTest.kt b/test_project/app/src/androidTest/java/org/the_jk/testproject/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..2ba9101 --- /dev/null +++ b/test_project/app/src/androidTest/java/org/the_jk/testproject/ExampleInstrumentedTest.kt @@ -0,0 +1,25 @@ +package org.the_jk.testproject + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = + InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("org.the_jk.testproject", appContext.packageName) + } +} diff --git a/test_project/app/src/main/AndroidManifest.xml b/test_project/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2d205bf --- /dev/null +++ b/test_project/app/src/main/AndroidManifest.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools"> + + <application + android:allowBackup="true" + android:dataExtractionRules="@xml/data_extraction_rules" + android:fullBackupContent="@xml/backup_rules" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_launcher_round" + android:supportsRtl="true" + android:theme="@style/Theme.TestProject" /> + +</manifest> diff --git a/test_project/app/src/main/java/org/the_jk/testproject/Hello.kt b/test_project/app/src/main/java/org/the_jk/testproject/Hello.kt new file mode 100644 index 0000000..a4fa614 --- /dev/null +++ b/test_project/app/src/main/java/org/the_jk/testproject/Hello.kt @@ -0,0 +1,11 @@ +package org.the_jk.testproject + +/** + * Minimal Kotlin source so that, if the Kotlin compiler runs, it has + * something to compile. With the empty stubs in place the compiler + * entry point is a no-op, so this file is never actually compiled — + * that is expected for the v1 stub jar. + */ +object Hello { + fun message(): String = "hello from kotlin" +} diff --git a/test_project/app/src/main/keepRules/rules.keep b/test_project/app/src/main/keepRules/rules.keep new file mode 100644 index 0000000..d7e081a --- /dev/null +++ b/test_project/app/src/main/keepRules/rules.keep @@ -0,0 +1,12 @@ +# Add project specific R8 rules here. +# AGP will combine all keep rule files in src/main/keepRules to pass to R8 +# +# For more details, see +# https://d.android.com/r/tools/r8/keep-rules + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#}
\ No newline at end of file diff --git a/test_project/app/src/main/res/drawable/ic_launcher_background.xml b/test_project/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..1e4408c --- /dev/null +++ b/test_project/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ +<?xml version="1.0" encoding="utf-8"?> +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:viewportHeight="108" + android:viewportWidth="108"> + <path + android:fillColor="#3DDC84" + android:pathData="M0,0h108v108h-108z" /> + <path + android:fillColor="#00000000" + android:pathData="M9,0L9,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,0L19,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M29,0L29,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M39,0L39,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M49,0L49,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M59,0L59,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M69,0L69,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M79,0L79,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M89,0L89,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M99,0L99,108" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,9L108,9" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,19L108,19" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,29L108,29" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,39L108,39" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,49L108,49" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,59L108,59" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,69L108,69" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,79L108,79" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,89L108,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M0,99L108,99" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,29L89,29" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,39L89,39" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,49L89,49" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,59L89,59" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,69L89,69" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M19,79L89,79" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M29,19L29,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M39,19L39,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M49,19L49,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M59,19L59,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M69,19L69,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> + <path + android:fillColor="#00000000" + android:pathData="M79,19L79,89" + android:strokeColor="#33FFFFFF" + android:strokeWidth="0.8" /> +</vector> diff --git a/test_project/app/src/main/res/drawable/ic_launcher_foreground.xml b/test_project/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..14780bb --- /dev/null +++ b/test_project/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:aapt="http://schemas.android.com/aapt" + android:width="108dp" + android:height="108dp" + android:viewportHeight="108" + android:viewportWidth="108"> + <path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z"> + <aapt:attr name="android:fillColor"> + <gradient + android:endX="85.84757" + android:endY="92.4963" + android:startX="42.9492" + android:startY="49.59793" + android:type="linear"> + <item + android:color="#44000000" + android:offset="0.0" /> + <item + android:color="#00000000" + android:offset="1.0" /> + </gradient> + </aapt:attr> + </path> + <path + android:fillColor="#FFFFFF" + android:fillType="nonZero" + android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z" + android:strokeColor="#00000000" + android:strokeWidth="1" /> +</vector> diff --git a/test_project/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/test_project/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..b3e26b4 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@drawable/ic_launcher_background" /> + <foreground android:drawable="@drawable/ic_launcher_foreground" /> + <monochrome android:drawable="@drawable/ic_launcher_foreground" /> +</adaptive-icon> diff --git a/test_project/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/test_project/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..b3e26b4 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@drawable/ic_launcher_background" /> + <foreground android:drawable="@drawable/ic_launcher_foreground" /> + <monochrome android:drawable="@drawable/ic_launcher_foreground" /> +</adaptive-icon> diff --git a/test_project/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/test_project/app/src/main/res/mipmap-hdpi/ic_launcher.webp Binary files differnew file mode 100644 index 0000000..c209e78 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-hdpi/ic_launcher.webp diff --git a/test_project/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/test_project/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp Binary files differnew file mode 100644 index 0000000..b2dfe3d --- /dev/null +++ b/test_project/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp diff --git a/test_project/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/test_project/app/src/main/res/mipmap-mdpi/ic_launcher.webp Binary files differnew file mode 100644 index 0000000..4f0f1d6 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-mdpi/ic_launcher.webp diff --git a/test_project/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/test_project/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp Binary files differnew file mode 100644 index 0000000..62b611d --- /dev/null +++ b/test_project/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp diff --git a/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher.webp Binary files differnew file mode 100644 index 0000000..948a307 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher.webp diff --git a/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp Binary files differnew file mode 100644 index 0000000..1b9a695 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp diff --git a/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp Binary files differnew file mode 100644 index 0000000..28d4b77 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp diff --git a/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp Binary files differnew file mode 100644 index 0000000..9287f50 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp diff --git a/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp Binary files differnew file mode 100644 index 0000000..aa7d642 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp diff --git a/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp Binary files differnew file mode 100644 index 0000000..9126ae3 --- /dev/null +++ b/test_project/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp diff --git a/test_project/app/src/main/res/values-night/themes.xml b/test_project/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..c67e80a --- /dev/null +++ b/test_project/app/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ +<resources xmlns:tools="http://schemas.android.com/tools"> + <!-- Base application theme. --> + <style name="Theme.TestProject" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> + <!-- Primary brand color. --> + <item name="colorPrimary">@color/purple_200</item> + <item name="colorPrimaryVariant">@color/purple_700</item> + <item name="colorOnPrimary">@color/black</item> + <!-- Secondary brand color. --> + <item name="colorSecondary">@color/teal_200</item> + <item name="colorSecondaryVariant">@color/teal_200</item> + <item name="colorOnSecondary">@color/black</item> + <!-- Status bar color. --> + <item name="android:statusBarColor">?attr/colorPrimaryVariant</item> + <!-- Customize your theme here. --> + </style> +</resources> diff --git a/test_project/app/src/main/res/values/colors.xml b/test_project/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..ca1931b --- /dev/null +++ b/test_project/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="purple_200">#FFBB86FC</color> + <color name="purple_500">#FF6200EE</color> + <color name="purple_700">#FF3700B3</color> + <color name="teal_200">#FF03DAC5</color> + <color name="teal_700">#FF018786</color> + <color name="black">#FF000000</color> + <color name="white">#FFFFFFFF</color> +</resources> diff --git a/test_project/app/src/main/res/values/strings.xml b/test_project/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..f0b25e1 --- /dev/null +++ b/test_project/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ +<resources> + <string name="app_name">TestProject</string> +</resources>
\ No newline at end of file diff --git a/test_project/app/src/main/res/values/themes.xml b/test_project/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..a01d71b --- /dev/null +++ b/test_project/app/src/main/res/values/themes.xml @@ -0,0 +1,16 @@ +<resources xmlns:tools="http://schemas.android.com/tools"> + <!-- Base application theme. --> + <style name="Theme.TestProject" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> + <!-- Primary brand color. --> + <item name="colorPrimary">@color/purple_500</item> + <item name="colorPrimaryVariant">@color/purple_700</item> + <item name="colorOnPrimary">@color/white</item> + <!-- Secondary brand color. --> + <item name="colorSecondary">@color/teal_200</item> + <item name="colorSecondaryVariant">@color/teal_700</item> + <item name="colorOnSecondary">@color/black</item> + <!-- Status bar color. --> + <item name="android:statusBarColor">?attr/colorPrimaryVariant</item> + <!-- Customize your theme here. --> + </style> +</resources> diff --git a/test_project/app/src/main/res/xml/backup_rules.xml b/test_project/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 0000000..90529f8 --- /dev/null +++ b/test_project/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?><!-- + Sample backup rules file; uncomment and customize as necessary. + See https://developer.android.com/guide/topics/data/autobackup + for details. + Note: This file is ignored for devices older than API 31 + See https://developer.android.com/about/versions/12/backup-restore +--> +<full-backup-content> + <!-- + <include domain="sharedpref" path="."/> + <exclude domain="sharedpref" path="device.xml"/> +--> +</full-backup-content> diff --git a/test_project/app/src/main/res/xml/data_extraction_rules.xml b/test_project/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..0c4f95c --- /dev/null +++ b/test_project/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?><!-- + Sample data extraction rules file; uncomment and customize as necessary. + See https://developer.android.com/about/versions/12/backup-restore#xml-changes + for details. +--> +<data-extraction-rules> + <cloud-backup> + <!-- TODO: Use <include> and <exclude> to control what is backed up. + <include .../> + <exclude .../> + --> + </cloud-backup> + <!-- + <device-transfer> + <include .../> + <exclude .../> + </device-transfer> + --> +</data-extraction-rules> diff --git a/test_project/app/src/test/java/org/the_jk/testproject/ExampleUnitTest.kt b/test_project/app/src/test/java/org/the_jk/testproject/ExampleUnitTest.kt new file mode 100644 index 0000000..a77c39c --- /dev/null +++ b/test_project/app/src/test/java/org/the_jk/testproject/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package org.the_jk.testproject + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/test_project/build.gradle.kts b/test_project/build.gradle.kts new file mode 100644 index 0000000..720abe1 --- /dev/null +++ b/test_project/build.gradle.kts @@ -0,0 +1,24 @@ +// kotlin-proxy demo — STANDARD plugins{} syntax. +// +// The narrowed compiler-stub jar is placed FIRST on the buildscript +// classpath so the Kotlin COMPILER path is shadowed, while the real KGP +// plugin (org.jetbrains.kotlin.gradle.*) is left intact so it can apply +// and the project can configure. plugins{} resolves AGP/KGP from the +// buildscript classpath above (stubs first), so the ordering is preserved. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + // 1) kotlin-proxy compiler stubs — must come before AGP/KGP + // (TEMP: disabled for the no-stub baseline run) + classpath(files("../dist/kotlin-proxy-compiler-stubs.jar")) + // 2) AGP (pulls kotlin-gradle-plugin 2.2.10 transitively) + classpath("com.android.tools.build:gradle:9.4.1") + } +} + +plugins { + alias(libs.plugins.android.application) apply false +} diff --git a/test_project/gradle.properties b/test_project/gradle.properties new file mode 100644 index 0000000..d8e0a36 --- /dev/null +++ b/test_project/gradle.properties @@ -0,0 +1,29 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# -Dkotlin.proxy.log -> where the stub jar writes its LOAD/CALL proof log +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 -Dkotlin.proxy.log=/home/the_jk/source/kotlin_proxy/test_project/build/kotlin-proxy.log +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +# When enabled, the Configuration Cache allows Gradle to skip the configuration +# phase entirely if nothing that affects the build configuration (such as build scripts) +# has changed. Additionally, Gradle applies performance optimizations to task execution. +org.gradle.configuration-cache=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Out-of-process Kotlin daemon. KGP assembles the daemon JVM classpath from +# the `kotlinCompilerClasspath` configuration; app/build.gradle.kts re-points +# that configuration so the stub jar is FIRST, letting the stub shadow +# org.jetbrains.kotlin.cli.jvm.K2JVMCompiler inside the daemon. +kotlin.compiler.execution.strategy=daemon +# PURE REPLACEMENT: do NOT fall back to the in-process compiler when the +# (stubbed) daemon fails. Our stub is the ONLY compiler; the build stays +# red until the stub implements its own alternative compile. +kotlin.daemon.useFallbackStrategy=false diff --git a/test_project/gradle/gradle-daemon-jvm.properties b/test_project/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..fa4ed51 --- /dev/null +++ b/test_project/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,12 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c2dd35c9d0aaf0ba6ad0791320f99dfc/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/e5810bd7fd1f8a586644409d395a7e55/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7b3c4877c0749019e6805bb61e421497/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d76df094a9cbbabd3b08251f9e61444a/redirect +toolchainVersion=25 diff --git a/test_project/gradle/libs.versions.toml b/test_project/gradle/libs.versions.toml new file mode 100644 index 0000000..0d165ea --- /dev/null +++ b/test_project/gradle/libs.versions.toml @@ -0,0 +1,20 @@ +[versions] +agp = "9.4.1" +coreKtx = "1.19.1" +junit = "4.13.2" +junitVersion = "1.3.0" +espressoCore = "3.7.0" +appcompat = "1.8.0" +material = "1.14.0" + +[libraries] +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } +androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +material = { group = "com.google.android.material", name = "material", version.ref = "material" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } + diff --git a/test_project/gradle/wrapper/gradle-wrapper.jar b/test_project/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..9fa7f28 --- /dev/null +++ b/test_project/gradle/wrapper/gradle-wrapper.jar diff --git a/test_project/gradle/wrapper/gradle-wrapper.properties b/test_project/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5c385e1 --- /dev/null +++ b/test_project/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/test_project/gradlew b/test_project/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/test_project/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/test_project/gradlew.bat b/test_project/gradlew.bat new file mode 100644 index 0000000..03754c4 --- /dev/null +++ b/test_project/gradlew.bat @@ -0,0 +1,112 @@ +@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem gradlew startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables, and ensure extensions are enabled
+setlocal EnableExtensions
+
+@rem Catch executions from older scripts and ensure they exit cleanly.
+@rem This can be removed once we can be reasonably confident that few people
+@rem will be migrating directly to this new wrapper.
+goto afterSafetyNet
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+goto exitWithErrorLevel
+:afterSafetyNet
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:execute
+@rem Setup the command line
+
+
+
+@rem Execute gradlew
+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
+@rem which allows us to clear the local environment before executing the java command
+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
+
+@rem This label must not be changed. We rely on old scripts being able to jump to this point.
+:exitWithErrorLevel
+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
+"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/test_project/settings.gradle.kts b/test_project/settings.gradle.kts new file mode 100644 index 0000000..31cf208 --- /dev/null +++ b/test_project/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "TestProject" +include(":app") diff --git a/tools/gen_class.py b/tools/gen_class.py new file mode 100755 index 0000000..fb398e9 --- /dev/null +++ b/tools/gen_class.py @@ -0,0 +1,731 @@ +#!/usr/bin/env python3 +""" +kotlin-proxy stub generator — BYTECODE edition. + +Instead of emitting Java source and fighting javac's generics checker +(erasure bridges that the JVM needs for linkage but javac forbids as +"same erasure, yet neither overrides the other"), this emits the .class +files DIRECTLY. It copies the real class file's erased structure +verbatim — exact super/interfaces, every field, every method (including +synthetic $default and erasure bridges) with its exact name + descriptor +and access flags — and gives each concrete method a trivial body that +logs the call via kotlin.proxy.KotlinProxyLog and returns a default value. + +The optional Signature attribute is OMITTED entirely, so there are no +generics in the emitted class files and therefore no generics clashes. +The JVM links by name + erased descriptor, both of which are copied +verbatim, so the stub is ABI-identical to the real class. + +Bodies are straight-line (no branches), so no StackMapTable frames are +needed. + +Usage: + python3 gen_class.py --scan-jars <list> --def-jars <list> --out <dir> + [--fallback-jars <list>] [--report <file>] +""" + +import argparse +import os +import struct +import sys +import zipfile + +MAGIC = 0xCAFEBABE +MAJOR, MINOR = 52, 0 # Java 8 +KPL = "kotlin/proxy/KotlinProxyLog" +OBJ = "java/lang/Object" +CALL_DESC = "(Ljava/lang/String;Ljava/lang/String;)V" +CALL_ARG_DESC = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V" +LOADED_DESC = "(Ljava/lang/String;)V" +NEW_INST_DESC = "(Ljava/lang/String;)Ljava/lang/Object;" + +# access flags +A_PUBLIC, A_PRIVATE, A_PROTECTED = 0x1, 0x2, 0x4 +A_STATIC, A_FINAL, A_SUPER = 0x8, 0x10, 0x20 +A_BRIDGE, A_SYNTHETIC = 0x40, 0x1000 +A_INTERFACE, A_ABSTRACT, A_ANNOTATION, A_ENUM = 0x200, 0x400, 0x2000, 0x4000 + + +# ---------------------------------------------------------------------- +# jar / class-file helpers +# ---------------------------------------------------------------------- +def read_list(path): + """One jar path per line; blank lines and '#' comments ignored.""" + out = [] + with open(path) as fh: + for line in fh: + line = line.strip() + if line and not line.startswith("#"): + out.append(line) + return out + + +def load_jar_classes(jar): + """internal name (slash form) -> .class bytes for every entry.""" + out = {} + with zipfile.ZipFile(jar) as z: + for n in z.namelist(): + if n.endswith(".class"): + out[n[:-len(".class")]] = z.read(n) + return out + + +def parse_class(data): + """Parse a class file into the info dict used by emit_class(): + {access, super, interfaces, fields[{name,desc,access}], + methods[{name,desc,access,has_code}], refs[internal names]}. + Returns None if unparseable.""" + try: + if len(data) < 10 or struct.unpack_from(">I", data, 0)[0] != MAGIC: + return None + o = 8 + cp_count, = struct.unpack_from(">H", data, o) + o += 2 + utf8 = {} # cp idx -> utf8 string + cls_names = {} # cp idx -> internal name (for Class constants) + i = 1 + while i < cp_count: + tag = data[o] + o += 1 + if tag == 1: # Utf8 + ln, = struct.unpack_from(">H", data, o) + o += 2 + utf8[i] = data[o:o + ln].decode("utf-8", "replace") + o += ln + elif tag in (3, 4): # Integer, Float + o += 4 + elif tag in (5, 6): # Long, Double (2 slots) + o += 8 + i += 1 + elif tag == 7: # Class + idx, = struct.unpack_from(">H", data, o) + o += 2 + cls_names[i] = utf8.get(idx, "") + elif tag in (8, 16, 19, 20): # String/MethodType/Module/Package + o += 2 + elif tag == 12: # NameAndType (2 indexes = 4 bytes) + o += 4 + elif tag in (9, 10, 11): # Fieldref/Methodref/... + o += 4 + elif tag == 15: # MethodHandle (u1 kind + u2 idx) + o += 3 + elif tag in (17, 18): # DynamicCallSite/InvokeDynamic + o += 4 # (u2 bootstrap + u2 nametype) + else: + return None + i += 1 + access, this, sup = struct.unpack_from(">HHH", data, o) + o += 6 + # Every class named anywhere in the file (this/super/interfaces and + # every method/field/annotation target) is a Class constant, so the + # set of tag-7 names is the complete reference set for the closure. + refs = {nm for nm in cls_names.values() if nm} + super_name = cls_names.get(sup) if sup else None + interfaces = [] + n, = struct.unpack_from(">H", data, o) + o += 2 + for _ in range(n): + idx, = struct.unpack_from(">H", data, o) + o += 2 + nm = cls_names.get(idx, "") + if nm: + interfaces.append(nm) + fields = [] + n, = struct.unpack_from(">H", data, o) + o += 2 + for _ in range(n): + fa, fn, fd = struct.unpack_from(">HHH", data, o) + o += 6 + fields.append({"name": utf8[fn], "desc": utf8[fd], "access": fa}) + na, = struct.unpack_from(">H", data, o) + o += 2 + for _ in range(na): + ln, = struct.unpack_from(">I", data, o + 2) + o += 6 + ln + methods = [] + n, = struct.unpack_from(">H", data, o) + o += 2 + for _ in range(n): + ma, mn, md = struct.unpack_from(">HHH", data, o) + o += 6 + has_code = False + na, = struct.unpack_from(">H", data, o) + o += 2 + for _ in range(na): + an = utf8[struct.unpack_from(">H", data, o)[0]] + ln, = struct.unpack_from(">I", data, o + 2) + o += 6 + ln + if an == "Code": + has_code = True + methods.append({"name": utf8[mn], "desc": utf8[md], + "access": ma, "has_code": has_code}) + return {"access": access, "super": super_name, + "interfaces": interfaces, "fields": fields, + "methods": methods, "refs": sorted(refs)} + except (struct.error, IndexError, KeyError): + return None + + +def kotlin_ref(name): + """True if the internal name is a Kotlin-owned class we may stub.""" + return name.startswith(("org/jetbrains/kotlin/", "kotlin/", + "kotlinx/", "org/jetbrains/kotlinx/")) + + +# ---------------------------------------------------------------------- +# constant pool +# ---------------------------------------------------------------------- +class CP: + def __init__(self): + self.entries = [] # (tag, payload) + self.u = {} # utf8 str -> idx + self.c = {} # internal name -> class idx + self.s = {} # string str -> idx + self._nt = {} # (name,desc) -> idx + self.mr = {} # (cls,name,desc) -> methodref idx + self.fr = {} # (cls,name,desc) -> fieldref idx + + def _add(self, tag, payload): + self.entries.append((tag, payload)) + return len(self.entries) + + def utf8(self, s): + i = self.u.get(s) + if i is not None: + return i + i = self._add(1, s) + self.u[s] = i + return i + + def cls(self, internal): + i = self.c.get(internal) + if i is not None: + return i + i = self._add(7, self.utf8(internal)) + self.c[internal] = i + return i + + def string(self, s): + i = self.s.get(s) + if i is not None: + return i + i = self._add(8, self.utf8(s)) + self.s[s] = i + return i + + def nt(self, name, desc): + k = (name, desc) + i = self._nt.get(k) + if i is not None: + return i + i = self._add(12, (self.utf8(name), self.utf8(desc))) + self._nt[k] = i + return i + + def methodref(self, internal, name, desc): + k = (internal, name, desc) + i = self.mr.get(k) + if i is not None: + return i + i = self._add(10, (self.cls(internal), self.nt(name, desc))) + self.mr[k] = i + return i + + def fieldref(self, internal, name, desc): + k = (internal, name, desc) + i = self.fr.get(k) + if i is not None: + return i + i = self._add(9, (self.cls(internal), self.nt(name, desc))) + self.fr[k] = i + return i + + def serialize(self): + out = bytearray(struct.pack(">H", len(self.entries) + 1)) + for tag, p in self.entries: + if tag == 1: + b = p.encode("utf-8") + out += bytes([1]) + struct.pack(">H", len(b)) + b + elif tag == 7: # Class + out += bytes([7]) + struct.pack(">H", p) + elif tag == 8: # String + out += bytes([8]) + struct.pack(">H", p) + elif tag == 9: # Fieldref + out += bytes([9]) + struct.pack(">HH", p[0], p[1]) + elif tag == 10: # Methodref + out += bytes([10]) + struct.pack(">HH", p[0], p[1]) + elif tag == 12: # NameAndType + out += bytes([12]) + struct.pack(">HH", p[0], p[1]) + else: + raise ValueError(f"unhandled cp tag {tag}") + return bytes(out) + + +# ---------------------------------------------------------------------- +# bytecode helpers +# ---------------------------------------------------------------------- +def ldc(idx): + if idx <= 0xFF: + return bytes([0x12, idx]) + return bytes([0x13]) + struct.pack(">H", idx) + + +def type_slots(s, i): + """(slot count, next index) for the type starting at s[i].""" + c = s[i] + if c == "L": + return 1, s.index(";", i) + 1 + if c == "[": + _, j = type_slots(s, i + 1) + return 1, j + return (2 if c in "JD" else 1), i + 1 + + +def count_locals(desc, is_static): + params = desc[1:desc.rindex(")")] + n, i = 0, 0 + while i < len(params): + sl, i = type_slots(params, i) + n += sl + if not is_static: + n += 1 + return n + + +def ret_bytes(desc): + """(push-default bytes, return byte) for the return type of desc. + + Opcodes verified byte-for-byte against javac output: + iconst_0=03 aconst_null=01 lconst_0=09 fconst_0=0b dconst_0=0e + ireturn=ac lreturn=ad freturn=ae dreturn=af areturn=b0 return=b1 + """ + r = desc[desc.rindex(")") + 1:] + if r == "V": + return b"", b"\xb1" + if r in ("Z", "B", "S", "C", "I"): + return b"\x03", b"\xac" + if r == "J": + return b"\x09", b"\xad" + if r == "F": + return b"\x0b", b"\xae" + if r == "D": + return b"\x0e", b"\xaf" + return b"\x01", b"\xb0" # reference / array + + +def code_attr(cp, max_stack, max_locals, code): + name = cp.utf8("Code") + body = struct.pack(">HHI", max_stack, max_locals, len(code)) + code \ + + struct.pack(">HH", 0, 0) # no exception table, no sub-attrs + return struct.pack(">HI", name, len(body)) + body + + +def aload(slot): + """aload bytecode for local slot (reference types).""" + if 0 <= slot <= 3: + return bytes([0x2a + slot]) # aload_0..aload_3 + return bytes([0x19, slot]) # aload + + +def first_param_ref_slot(desc, is_static): + """(slot, is_reference) for the first parameter, else (None, False). + + Only reference first-params (L... or [..) are logged - they occupy a + single slot and can be passed straight to an Object-taking helper. + A reference first param is always slot 0 (static) or 1 (instance). + """ + params = desc[1:desc.rindex(")")] + if not params or params[0] not in "L[": + return None, False + return (0 if is_static else 1), True + + +def new_instance_target(desc): + """Internal return type to materialize via KotlinProxyLog.newInstance, or + None to keep the default null return. Only for class (L...;) returns, + excluding String (avoid a ''-for-null behavior change).""" + r = desc[desc.rindex(")") + 1:] + if not (r.startswith("L") and r.endswith(";") and len(r) > 2): + return None + internal = r[1:-1] + if internal == "java/lang/String": + return None + return internal + + +def log_body(cp, member, dotname, desc, is_static, call_ref): + """Straight-line: log the call (with the first reference param, when + there is one), produce the return value, return. + + Reference-class returns materialize a real instance via + KotlinProxyLog.newInstance so the daemon can proceed past e.g. + createArguments() into doExecute() with a populated args object.""" + slot, has_arg = first_param_ref_slot(desc, is_static) + if has_arg: + call_arg_ref = cp.methodref(KPL, "call", CALL_ARG_DESC) + b = ldc(cp.string(member)) + ldc(cp.string(dotname)) + aload(slot) \ + + bytes([0xb8]) + struct.pack(">H", call_arg_ref) + max_stack = 3 + else: + b = ldc(cp.string(member)) + ldc(cp.string(dotname)) \ + + bytes([0xb8]) + struct.pack(">H", call_ref) + max_stack = 2 + ti = new_instance_target(desc) + if ti is not None: + ni = cp.methodref(KPL, "newInstance", NEW_INST_DESC) + # newInstance returns Object; checkcast to the declared return type so + # the verifier is happy (null passes checkcast, so un-instantiable + # types still just return null). + b += ldc(cp.string(ti.replace("/", "."))) \ + + bytes([0xb8]) + struct.pack(">H", ni) \ + + bytes([0xc0]) + struct.pack(">H", cp.cls(ti)) + else: + push, _ = ret_bytes(desc) + b += push + _, ret = ret_bytes(desc) + b += ret + max_locals = count_locals(desc, is_static) + return code_attr(cp, max_stack, max_locals, b) + + +def ctor_body(cp, super_name, member, dotname, desc, call_ref, is_enum): + # Enums: java.lang.Enum has no no-arg ctor, so the super call must be + # Enum.<init>(String name, int ordinal). The enum ctor's own name/ordinal + # params (last two) are ignored — we pass constants; unused params are + # legal in a ctor body. Peak stack is 3 (this, name, ordinal). + b = b"\x2a" # aload_0 + if is_enum: + b += ldc(cp.string("stub")) + b"\x03" # ldc "stub"; iconst_0 + sup = cp.methodref("java/lang/Enum", "<init>", + "(Ljava/lang/String;I)V") + max_stack = 3 + else: + sup = cp.methodref(super_name, "<init>", "()V") + max_stack = 2 + b += bytes([0xb7]) + struct.pack(">H", sup) # invokespecial + b += ldc(cp.string(member)) + ldc(cp.string(dotname)) + b += bytes([0xb8]) + struct.pack(">H", call_ref) + b += b"\xb1" # return + return code_attr(cp, max_stack, count_locals(desc, False), b) + + +def clinit_body(cp, dotname, loaded_ref): + b = ldc(cp.string(dotname)) + b += bytes([0xb8]) + struct.pack(">H", loaded_ref) + b += b"\xb1" # return + return code_attr(cp, 2, 0, b) + + +def bridge_body(cp, dotname, name, target_desc, is_static): + """Body for a param-less erasure bridge: forward to the concrete sibling + (which logs itself) and return its result. Needed because callers + compiled against the supertype (e.g. the daemon calling + CommonCompiler.createArguments()L.../CommonCompilerArguments;) dispatch + to the bridge, whose own return type may be abstract and un-instantiable.""" + this_internal = dotname.replace(".", "/") + b = b"" + if not is_static: + b += b"\x2a" # aload_0 + mi = cp.methodref(this_internal, name, target_desc) + op = 0xb8 if is_static else 0xb6 # invokestatic / invokevirtual + b += bytes([op]) + struct.pack(">H", mi) + _, ret = ret_bytes(target_desc) + b += ret + return code_attr(cp, 1, count_locals(target_desc, is_static), b) + + +def method_bytes(cp, name, desc, access, body_code): + """body_code is bytes or None (abstract).""" + out = struct.pack(">HHH", access, cp.utf8(name), cp.utf8(desc)) + if body_code is None: + out += struct.pack(">H", 0) + else: + out += struct.pack(">H", 1) + body_code + return out + + +def field_bytes(cp, name, desc, access): + return struct.pack(">HHH", access, cp.utf8(name), cp.utf8(desc)) \ + + struct.pack(">H", 0) + + +# ---------------------------------------------------------------------- +# class emission +# ---------------------------------------------------------------------- +def emit_class(cp, name, info, is_iface, dotname): + this_idx = cp.cls(name) + super_name = (info.get("super") or OBJ) if not is_iface else OBJ + super_idx = cp.cls(super_name) + iface_idxs = [cp.cls(x) for x in (info.get("interfaces") or []) if x] + + access = info.get("access", A_PUBLIC) + if is_iface: + access |= A_INTERFACE | A_ABSTRACT + is_enum = bool(access & A_ENUM) + if name == OBJ: + return None + + call_ref = cp.methodref(KPL, "call", CALL_DESC) + loaded_ref = cp.methodref(KPL, "loaded", LOADED_DESC) + + fields = [] + for f in info.get("fields", []): + fields.append(field_bytes(cp, f["name"], f["desc"], f["access"])) + + # param-less concrete (non-bridge) methods, by name. A param-less + # erasure bridge with the same name forwards to its concrete sibling + # (whose own return type is the instantiable subclass). + concrete_noparam = {} + for m in info.get("methods", []): + if m["name"] in ("<init>", "<clinit>"): + continue + if m["access"] & (A_BRIDGE | A_ABSTRACT): + continue + if not m["desc"][1:m["desc"].rindex(")")]: + concrete_noparam[m["name"]] = m["desc"] + + methods = [] + # constructors + concrete methods + has_noarg = False + for m in info.get("methods", []): + mn, md, ma = m["name"], m["desc"], m["access"] + if mn == "<clinit>": + continue # we synthesize our own + abstract = bool(ma & A_ABSTRACT) or (is_iface and not m["has_code"]) + if mn == "<init>": + if md == "()V": + has_noarg = True + body = ctor_body(cp, super_name, mn, dotname, md, call_ref, + is_enum) + methods.append(method_bytes(cp, mn, md, ma, body)) + elif (ma & A_BRIDGE) and not md[1:md.rindex(")")] \ + and mn in concrete_noparam: + # param-less erasure bridge: forward to the concrete sibling + body = bridge_body(cp, dotname, mn, concrete_noparam[mn], + bool(ma & A_STATIC)) + methods.append(method_bytes(cp, mn, md, ma, body)) + else: + if abstract: + methods.append(method_bytes(cp, mn, md, ma, None)) + else: + body = log_body(cp, mn, dotname, md, + bool(ma & A_STATIC), call_ref) + methods.append(method_bytes(cp, mn, md, ma, body)) + if not is_iface: + # guarantee a no-arg ctor so child stubs can invokespecial super() + if not has_noarg: + body = ctor_body(cp, super_name, "<init>", dotname, "()V", + call_ref, is_enum) + methods.append(method_bytes(cp, "<init>", "()V", + A_PUBLIC, body)) + # synthesized static initializer -> KotlinProxyLog.loaded(name) + methods.append(method_bytes(cp, "<clinit>", "()V", + A_STATIC | A_PRIVATE, + clinit_body(cp, dotname, loaded_ref))) + + out = bytearray() + out += struct.pack(">IHH", MAGIC, MINOR, MAJOR) + out += cp.serialize() + out += struct.pack(">H", access) + out += struct.pack(">H", this_idx) + out += struct.pack(">H", super_idx) + out += struct.pack(">H", len(iface_idxs)) + for ix in iface_idxs: + out += struct.pack(">H", ix) + out += struct.pack(">H", len(fields)) + for fb in fields: + out += fb + out += struct.pack(">H", len(methods)) + for mb in methods: + out += mb + out += struct.pack(">H", 0) # no class attributes + return bytes(out) + + +def emit_minimal(cp, name, is_iface): + """A class/interface with no definition found: bare structure + + (for classes) a no-arg ctor and a loaded() clinit.""" + info = {"access": A_PUBLIC, "super": OBJ, "interfaces": [], + "fields": [], "methods": []} + if is_iface: + info["access"] |= A_INTERFACE | A_ABSTRACT + return emit_class(cp, name, info, is_iface, name.replace("/", ".")) + + +# ---------------------------------------------------------------------- +# driver +# ---------------------------------------------------------------------- +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--scan-jars", required=True) + ap.add_argument("--def-jars", required=True) + ap.add_argument("--fallback-jars", default=None) + ap.add_argument("--out", required=True) + ap.add_argument("--report", default=None) + ap.add_argument("--exclude", default=None, + help="comma-separated internal-name prefixes to NOT stub " + "(e.g. org/jetbrains/kotlin/gradle/ to leave the KGP " + "plugin real so the project can still configure)") + ap.add_argument("--seed", default=None, + help="comma-separated internal or dotted class names to add " + "to the seed set (S0) for the closure " + "(e.g. the compiler entry point)") + ap.add_argument("--seed-only", action="store_true", + help="use only --seed as S0 (ignore scan-jars and the KGP " + "plugin entry points) - for a narrow jar such as one " + "holding just the compiler entry point") + ap.add_argument("--no-closure", action="store_true", + help="do not expand the transitive closure - emit exactly " + "the seed set only. Use with --seed to stub just the " + "compiler entry point; its super/interfaces are then " + "resolved from the real jars at load time") + args = ap.parse_args() + + exclude = [p for p in (args.exclude.split(",") if args.exclude else []) + if p] + seeds = [] + if args.seed: + for s in args.seed.split(","): + s = s.strip() + if not s: + continue + seeds.append(s.replace(".", "/") + if ("." in s and "/" not in s) else s) + scan_jars = read_list(args.scan_jars) + def_jars = read_list(args.def_jars) + fb_jars = read_list(args.fallback_jars) if args.fallback_jars else [] + + # defs: internal name -> (jar, info) (first jar wins) + defs = {} + for jar in def_jars + fb_jars: + if not jar or not os.path.exists(jar): + print(f"warn: missing def jar {jar}", file=sys.stderr) + continue + for internal, data in load_jar_classes(jar).items(): + if internal in defs: + continue + info = parse_class(data) + if info is not None: + defs[internal] = (jar, info) + print(f"defs: {len(defs)} classes", file=sys.stderr) + + # S0: kotlin refs from AGP scan jars + KGP plugin entry points + s0 = set() + if not args.seed_only: + for jar in scan_jars: + if not jar or not os.path.exists(jar): + continue + for internal, data in load_jar_classes(jar).items(): + info = parse_class(data) + if info is None: + continue + for r in info["refs"]: + if kotlin_ref(r): + s0.add(r) + for jar in def_jars: + if not jar or not os.path.exists(jar): + continue + try: + with zipfile.ZipFile(jar) as z: + for n in z.namelist(): + if n.startswith("META-INF/gradle-plugins/") \ + and n.endswith(".properties"): + for line in z.read(n).decode( + "utf-8", "replace").splitlines(): + if line.startswith("implementation-class="): + impl = line.split("=", 1)[1].strip() \ + .replace(".", "/") + if kotlin_ref(impl): + s0.add(impl) + except (zipfile.BadZipFile, OSError): + pass + for s in seeds: + s0.add(s) + + # transitive closure (skipped with --no-closure: emit exactly the seed set) + closure = set(s0) + if not args.no_closure: + frontier = sorted(s0) + while frontier: + nxt = [] + for nm in frontier: + e = defs.get(nm) + if e is None: + continue + for r in e[1]["refs"]: + if kotlin_ref(r) and r not in closure: + closure.add(r) + nxt.append(r) + frontier = sorted(nxt) + + # kind hint for names without a definition + kind_hint = {} + for cname, e in defs.items(): + if cname not in closure: + continue + info = e[1] + if info["access"] & A_ANNOTATION: + continue + is_iface = bool(info["access"] & A_INTERFACE) + for x in info["interfaces"]: + kind_hint.setdefault(x, "interface") + sup = info.get("super") + if sup and sup != OBJ: + kind_hint.setdefault(sup, "interface" if is_iface else "class") + + # emit + if os.path.exists(args.out): + import shutil + shutil.rmtree(args.out) + os.makedirs(args.out) + + n_full = n_minimal = n_iface = n_excluded = 0 + minimal = [] + for name in sorted(closure): + if any(name.startswith(p) for p in exclude): + n_excluded += 1 + continue # leave this subtree REAL (not stubbed) + e = defs.get(name) + dot = name.replace("/", ".") + cp = CP() + if e is None: + is_iface = kind_hint.get(name) == "interface" + data = emit_minimal(cp, name, is_iface) + minimal.append(name) + n_minimal += 1 + else: + _, info = e + is_iface = bool(info["access"] & A_INTERFACE) + data = emit_class(cp, name, info, is_iface, dot) + n_full += 1 + if is_iface: + n_iface += 1 + if data is None: + continue + path = os.path.join(args.out, name + ".class") + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as fh: + fh.write(data) + + rep = [ + "kotlin-proxy stub report (bytecode)", + f"scan jars: {len(scan_jars)}; def jars: {len(def_jars)}", + f"S0: {len(s0)}", + f"closure: {len(closure)}", + f"full: {n_full} (interfaces: {n_iface}); minimal: {n_minimal}", + "", + f"=== S0 ({len(s0)}) ===", + *sorted(s0), + "", + f"=== minimal ({n_minimal}) ===", + *sorted(minimal), + ] + txt = "\n".join(rep) + if args.report: + with open(args.report, "w") as fh: + fh.write(txt + "\n") + print(txt[:4000]) + + +if __name__ == "__main__": + main() |
