Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / build-logic / src / main / kotlin / RustNative.kt

RustNative.kt902 lines · 45.2 KiBRaw
1import org.gradle.api.DefaultTask
2import org.gradle.api.GradleException
3import org.gradle.api.Project
4import org.gradle.api.artifacts.ProjectDependency
5import org.gradle.api.file.ConfigurableFileCollection
6import org.gradle.api.file.DirectoryProperty
7import org.gradle.api.provider.ListProperty
8import org.gradle.api.provider.Property
9import org.gradle.api.services.BuildService
10import org.gradle.api.services.BuildServiceParameters
11import org.gradle.api.tasks.Exec
12import org.gradle.api.tasks.Input
13import org.gradle.api.tasks.InputDirectory
14import org.gradle.api.tasks.InputFiles
15import org.gradle.api.tasks.OutputDirectory
16import org.gradle.api.tasks.PathSensitive
17import org.gradle.api.tasks.PathSensitivity
18import org.gradle.api.tasks.TaskAction
19import org.gradle.api.tasks.testing.Test
20import org.gradle.internal.os.OperatingSystem
21import org.gradle.kotlin.dsl.register
22import org.gradle.kotlin.dsl.withType
23import org.gradle.process.ExecOperations
24import java.io.File
25import java.util.Properties
26import javax.inject.Inject
27
28/**
29 * Shared build service that caps concurrent cargoBuild executions to 1.
30 * This prevents parallel invocations of `rustup toolchain install` triggered
31 * implicitly by cargo when rust-toolchain.toml pins 1.97.0, which is not
32 * concurrency-safe and produces "Directory not empty (os error 39)",
33 * "cargo not applicable", "failed to install component bin/rust-gdb" errors.
34 */
35abstract class RustToolchainLock : BuildService<BuildServiceParameters.None>
36
37/**
38 * Maximum lines per Rust source file, mirroring the Kotlin `FileLength`
39 * rule (which cannot see Rust — Android lint only visits Kotlin/Java).
40 * Long files hide the same brace-imbalance breakage and grab-bag rot;
41 * splitting along module lines keeps each file reviewable.
42 *
43 * Enforced as a build failure, like `ToastUsage`: files already over the
44 * limit must be split before the owning module builds.
45 */
46const val RUST_FILE_LENGTH_LIMIT = 500
47
48/**
49 * Exemptions by filename: long by design, not by accretion — same rationale
50 * as `LENGTH_EXEMPT_FILES` in the Kotlin rule. Test fixtures and examples
51 * are long by nature; generated files are not hand-written.
52 */
53private val RUST_LENGTH_EXEMPT_FILES = setOf(
54 "route_diff.rs", // maps example harness with inline fixtures
55)
56
57private fun isRustLengthExempt(path: String): Boolean =
58 path.contains("/tests/") || path.contains("/test_fixtures/") ||
59 path.contains("/examples/") || path.contains("/generated/") ||
60 path.contains("/third_party/")
61
62/**
63 * An Android ABI paired with the Rust target triple and the NDK clang-wrapper prefix
64 * used to cross-compile for it.
65 *
66 * @param clangPrefix deliberately separate from [triple]: for armeabi-v7a the NDK ships
67 * `armv7a-linux-androideabi<api>-clang` (note the `a`) while the Rust triple is
68 * `armv7-linux-androideabi`, so deriving one from the other silently misses the wrapper.
69 */
70data class RustAbi(val abiDir: String, val triple: String, val clangPrefix: String)
71
72/**
73 * Compiles GLSL entry points to `<name>.spv` with the NDK's glslc. Crates load the output with
74 * `include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/<name>.spv"))`,
75 * so standalone cargo (./check, ./test) needs this task to have run first.
76 */
77abstract class GlslcCompile @Inject constructor(
78 private val execOps: ExecOperations,
79) : DefaultTask() {
80 /** Whole shader dir, so `#include`d files invalidate the task too. */
81 @get:InputDirectory
82 @get:PathSensitive(PathSensitivity.RELATIVE)
83 abstract val shaderDir: DirectoryProperty
84
85 @get:InputFiles
86 @get:PathSensitive(PathSensitivity.RELATIVE)
87 abstract val sources: ConfigurableFileCollection
88
89 @get:Input
90 abstract val glslc: Property<String>
91
92 @get:Input
93 abstract val glslcArgs: ListProperty<String>
94
95 @get:OutputDirectory
96 abstract val outputDir: DirectoryProperty
97
98 @TaskAction
99 fun compile() {
100 val compiler = File(glslc.get())
101 if (!compiler.isFile) {
102 throw GradleException("glslc not found at $compiler. Install NDK $NDK_VERSION.")
103 }
104 val shaders = sources.files.sortedBy { it.name }
105 if (shaders.isEmpty()) throw GradleException("No shaders matched in ${shaderDir.get()}")
106 val out = outputDir.get().asFile
107 // Wipe first so a deleted shader can't leave a stale .spv behind for include_bytes!.
108 out.deleteRecursively()
109 out.mkdirs()
110 for (src in shaders) {
111 val spv = File(out, "${src.name}.spv")
112 execOps.exec {
113 commandLine(compiler.path, *glslcArgs.get().toTypedArray(), "-o", spv.path, src.path)
114 }
115 }
116 }
117}
118
119private val KNOWN_RUST_ABIS = listOf(
120 RustAbi(ABI_ARM64, "aarch64-linux-android", "aarch64-linux-android"),
121 RustAbi(ABI_ARMV7, "armv7-linux-androideabi", "armv7a-linux-androideabi"),
122 // Emulator-only; see [ABI_X86_64]. Never packaged by default.
123 RustAbi(ABI_X86_64, "x86_64-linux-android", "x86_64-linux-android"),
124)
125
126/**
127 * Host target triple for JVM unit tests that load Rust cdylibs via
128 * `System.loadLibrary`. Mirrors the pattern in
129 * `:library:everysync-core` (which predates this helper): GNU triple on
130 * Windows (MinGW — matches the installed toolchain; MSVC would need VS Build
131 * Tools), Apple triples on macOS, GNU triples on Linux. Resolved with plain
132 * JVM system properties at configuration time so the configuration cache is
133 * unaffected (a String, never a task or Project, crosses into task actions).
134 */
135fun hostRustTriple(): String {
136 val os = System.getProperty("os.name").lowercase()
137 val arch = System.getProperty("os.arch").lowercase()
138 val isArm = arch.contains("aarch64") || arch.startsWith("arm")
139 return when {
140 os.contains("win") -> if (isArm) "aarch64-pc-windows-gnullvm" else "x86_64-pc-windows-gnu"
141 os.contains("mac") -> if (isArm) "aarch64-apple-darwin" else "x86_64-apple-darwin"
142 else -> if (isArm) "aarch64-unknown-linux-gnu" else "x86_64-unknown-linux-gnu"
143 }
144}
145
146/** `lib<crate>.dylib` / `.so` / `<crate>.dll` for [hostRustTriple]. */
147fun hostRustLibFileName(crate: String): String = when {
148 System.getProperty("os.name").lowercase().contains("win") -> "$crate.dll"
149 System.getProperty("os.name").lowercase().contains("mac") -> "lib$crate.dylib"
150 else -> "lib$crate.so"
151}
152
153/**
154 * A `path = "..."` or workspace-inherited reference found in one manifest's
155 * dependency tables.
156 */
157private data class CargoDepRefs(val paths: List<String>, val workspaceNames: List<String>)
158
159private val cargoPathValue = Regex("""\bpath\s*=\s*("([^"]*)"|'([^']*)')""")
160private val cargoDottedWorkspace = Regex("""^([A-Za-z0-9_-]+)\.workspace\s*=\s*true\b""")
161private val cargoInlineWorkspace =
162 Regex("""^[A-Za-z0-9_-]+\s*=\s*\{[^}]*?\bworkspace\s*=\s*true\b""")
163private val cargoInlineWorkspaceName = Regex("""^([A-Za-z0-9_-]+)\s*=""")
164
165private fun stripTomlComment(line: String): String {
166 var inDouble = false
167 var inSingle = false
168 var i = 0
169 while (i < line.length) {
170 val c = line[i]
171 when {
172 c == '"' && !inSingle && (i == 0 || line[i - 1] != '\\') -> inDouble = !inDouble
173 c == '\'' && !inDouble -> inSingle = !inSingle
174 c == '#' && !inDouble && !inSingle -> return line.substring(0, i)
175 }
176 i++
177 }
178 return line
179}
180
181/**
182 * Dependency refs in a crate manifest: inline `path = "..."` entries plus
183 * `<name>.workspace = true` / `<name> = { workspace = true ... }` entries.
184 * Only dependency tables are scanned (`[dependencies]`,
185 * `[dev-dependencies]`, `[build-dependencies]`, `[target.*.dependencies]`,
186 * `[workspace.dependencies]`), so `[[bin]]`/`[lib]`/`[[example]]`
187 * `path = "src/..."` file entries never surface here — and the directory
188 * check in [findRustPathDepDirs] rejects them anyway.
189 */
190private fun parseCargoDepRefs(manifestText: String): CargoDepRefs {
191 val paths = mutableListOf<String>()
192 val workspaceNames = mutableListOf<String>()
193 var inDeps = false
194 for (rawLine in manifestText.lines()) {
195 val line = stripTomlComment(rawLine).trim()
196 if (line.startsWith("[")) {
197 inDeps = line.startsWith("[dependencies") ||
198 line.startsWith("[dev-dependencies") ||
199 line.startsWith("[build-dependencies") ||
200 line.startsWith("[target.") ||
201 line.replace(" ", "") == "[workspace.dependencies]"
202 continue
203 }
204 if (!inDeps || line.isEmpty()) continue
205 cargoPathValue.find(line)?.let {
206 paths += it.groupValues[2].ifEmpty { it.groupValues[3] }
207 }
208 cargoDottedWorkspace.find(line)?.let {
209 workspaceNames += it.groupValues[1]
210 }
211 if (cargoInlineWorkspace.containsMatchIn(line)) {
212 cargoInlineWorkspaceName.find(line)?.let {
213 workspaceNames += it.groupValues[1]
214 }
215 }
216 }
217 return CargoDepRefs(paths, workspaceNames)
218}
219
220/** `name = { path = "...", ... }` entries of root `[workspace.dependencies]`. */
221private fun parseWorkspacePathDeps(rootManifestText: String): Map<String, String> {
222 val out = LinkedHashMap<String, String>()
223 var inSection = false
224 for (rawLine in rootManifestText.lines()) {
225 val line = stripTomlComment(rawLine).trim()
226 if (line.startsWith("[")) {
227 inSection = line.replace(" ", "") == "[workspace.dependencies]"
228 continue
229 }
230 if (!inSection || line.isEmpty()) continue
231 if (cargoDottedWorkspace.containsMatchIn(line) ||
232 cargoInlineWorkspace.containsMatchIn(line)
233 ) {
234 // `name.workspace = true` re-export: no path of its own.
235 continue
236 }
237 val name = line.substringBefore("=").trim()
238 if (!name.matches(Regex("[A-Za-z0-9_-]+"))) continue
239 cargoPathValue.find(line)?.let {
240 out[name] = it.groupValues[2].ifEmpty { it.groupValues[3] }
241 }
242 }
243 return out
244}
245
246/**
247 * Reads a Cargo.toml through the file-contents provider so the configuration
248 * cache tracks it: editing any visited manifest invalidates configuration.
249 * Manifests outside the repo (defensive fallback) are read untracked.
250 */
251private fun Project.readCargoManifest(manifestFile: File): String {
252 val canonical = manifestFile.canonicalFile
253 fun relativeToBase(base: File): String? {
254 val prefix = base.canonicalPath.trimEnd(File.separatorChar) + File.separatorChar
255 return if (canonical.path.startsWith(prefix)) canonical.path.removePrefix(prefix) else null
256 }
257 relativeToBase(projectDir)?.let {
258 return providers.fileContents(layout.projectDirectory.file(it)).asText.get()
259 }
260 relativeToBase(rootProject.projectDir)?.let {
261 return providers.fileContents(rootProject.layout.projectDirectory.file(it)).asText.get()
262 }
263 return canonical.readText()
264}
265
266/** Stable per-crate input property name from the root-relative crate path. */
267private fun pathDepPropertyName(rootDir: File, depDir: File): String {
268 val rel = try {
269 depDir.relativeTo(rootDir).invariantSeparatorsPath
270 } catch (_: IllegalArgumentException) {
271 depDir.canonicalPath
272 }
273 return "pathDep_" + rel.replace(Regex("[^A-Za-z0-9]+"), "_")
274}
275
276/**
277 * Cross-crate path dependencies of the crate in [crateDir], e.g. euicc ->
278 * library/jni-http, camera/measure -> library/vision, maps/library:map ->
279 * library/tilecodec. Parsed generically from `path = "..."` entries (resolved
280 * relative to the crate dir) plus `<name>.workspace = true` entries (resolved
281 * against root `[workspace.dependencies]` paths), recursed with dedupe and a
282 * cycle guard. Only paths resolving to a directory containing Cargo.toml are
283 * accepted. Returns plain Files; callers build FileCollections from them so
284 * only those (never the Project) cross into task actions.
285 */
286private fun Project.findRustPathDepDirs(crateDir: File): List<File> {
287 val rootDir = rootProject.projectDir.canonicalFile
288 val workspacePaths =
289 parseWorkspacePathDeps(readCargoManifest(rootDir.resolve("Cargo.toml")))
290 val canonicalCrate = crateDir.canonicalFile
291 val visited = HashSet<File>()
292 visited += canonicalCrate
293 val found = mutableListOf<File>()
294 val queue = ArrayDeque<File>()
295 fun enqueue(base: File, rawPath: String) {
296 val resolved = File(base, rawPath).canonicalFile
297 if (!resolved.isDirectory || !resolved.resolve("Cargo.toml").isFile) return
298 if (visited.add(resolved)) {
299 found += resolved
300 queue += resolved
301 }
302 }
303 fun enqueueWorkspaceDep(name: String) {
304 workspacePaths[name]?.let { enqueue(rootDir, it) }
305 }
306 val seed = parseCargoDepRefs(readCargoManifest(canonicalCrate.resolve("Cargo.toml")))
307 seed.paths.forEach { enqueue(canonicalCrate, it) }
308 seed.workspaceNames.forEach(::enqueueWorkspaceDep)
309 while (queue.isNotEmpty()) {
310 val dir = queue.removeFirst()
311 val refs = parseCargoDepRefs(readCargoManifest(dir.resolve("Cargo.toml")))
312 refs.paths.forEach { enqueue(dir, it) }
313 refs.workspaceNames.forEach(::enqueueWorkspaceDep)
314 }
315 return found
316}
317
318/**
319 * Registers the per-ABI cargo cross-compile of a Rust cdylib into `build/rustJniLibs`,
320 * wired ahead of `preBuild`. This consolidates the ~80 lines of NDK-toolchain + cargo +
321 * reproducible-build boilerplate that used to be copy-pasted across every native module
322 * (pdf, camera, weather, passwords, e2ee-p2p). The caller still registers
323 * `build/rustJniLibs` as a jniLibs source dir in its own `android { }` block.
324 *
325 * Prereq: `rustup target add` for every triple built (see `rust-toolchain.toml`).
326 *
327 * @param crate cargo package lib name → produces `lib<crate>.so`
328 * @param remapLabel `--remap-path-prefix` label baked in for reproducible builds
329 * (defaults to [crate]).
330 * @param srcDir crate directory relative to the module (defaults to
331 * `src/main/rust`). Namespaces the per-ABI task names by
332 * [crate] so a module can build several crates.
333 * @param extraAbis ABIs to build in addition to [ABI_ARM64]. Opt-in per module so only
334 * the modules that need a second ABI pay for the extra cargo build;
335 * pass [ABI_ARMV7] for libraries consumed by an app that sets
336 * `nativeAbis { armv7 = true }`.
337 * @param features Cargo features to enable via `--features`. Resolved to a plain
338 * String list at configuration time so the build stays
339 * configuration-cache compatible (only the strings cross into
340 * the task action, never the Project).
341 * @param shaders Glob patterns under `$srcDir/shaders` to compile to SPIR-V into
342 * `build/spirv` ahead of the cargo build (see [GlslcCompile]). Empty
343 * means the crate has no Vulkan shaders. Only supported with the
344 * default [srcDir], since crates locate `build/spirv` relative to it.
345 * @param glslcArgs Extra glslc flags, e.g. `--target-env=vulkan1.1`, `-O`.
346 * @param hostTests Also build this crate for the host (`cargoBuildHost_<crate>`,
347 * see below) so JVM unit tests can `System.loadLibrary` it.
348 * Set to false for crates that cannot compile for host
349 * (Android-only deps like `ndk`/`oboe`, Vulkan/GLES paths
350 * with no host fallback): no host task is registered and
351 * [wireRustHostLibsForUnitTests] skips the crate cleanly
352 * instead of breaking unit tests that never load it.
353 */
354fun Project.rustNativeLib(
355 crate: String,
356 remapLabel: String = crate,
357 extraAbis: List<String> = emptyList(),
358 features: List<String> = emptyList(),
359 srcDir: String = "src/main/rust",
360 shaders: List<String> = emptyList(),
361 glslcArgs: List<String> = emptyList(),
362 hostTests: Boolean = true,
363) {
364 // Serialize cargoBuild across all Rust modules to avoid concurrent rustup installs.
365 val rustLock = gradle.sharedServices.registerIfAbsent(
366 "rustToolchainLock",
367 RustToolchainLock::class.java
368 ) {
369 maxParallelUsages.set(1)
370 }
371
372 val androidApiLevel = 31
373
374 // Resolved once per build, not once per native module: every
375 // rustNativeLib caller shares the stashed value via the Gradle extra
376 // cache. Plain String keeps the configuration cache happy.
377 fun resolveSdkDirOnce(): String {
378 val extra = gradle.extensions.extraProperties
379 if (extra.has("modernAppsSdkDir")) return extra.get("modernAppsSdkDir") as String
380 val dir = System.getenv("ANDROID_HOME")
381 ?: System.getenv("ANDROID_SDK_ROOT")
382 ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->
383 Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")
384 }
385 ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")
386 extra.set("modernAppsSdkDir", dir)
387 return dir
388 }
389
390 fun resolveSdkDir(): String = resolveSdkDirOnce()
391
392 val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"
393 val ndkRoot = "${resolveSdkDir()}/ndk/$NDK_VERSION"
394 val hostTag = when {
395 OperatingSystem.current().isMacOsX -> "darwin-x86_64"
396 OperatingSystem.current().isLinux -> "linux-x86_64"
397 OperatingSystem.current().isWindows -> "windows-x86_64"
398 else -> error("Unsupported host OS for NDK toolchain")
399 }
400 val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"
401 val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"
402
403 // arm64-v8a always; anything else is opt-in via extraAbis.
404 val rustAbis = (listOf(ABI_ARM64) + extraAbis).distinct().map { abiDir ->
405 KNOWN_RUST_ABIS.firstOrNull { it.abiDir == abiDir }
406 ?: error(
407 "rustNativeLib($crate): unknown ABI '$abiDir'. " +
408 "Known: ${KNOWN_RUST_ABIS.joinToString { it.abiDir }}"
409 )
410 }
411
412 // Config-cache compatible: snapshot to plain Strings at configuration time so
413 // only the strings (never the Project) cross into the task actions below.
414 val cargoFeatureArgs: List<String> =
415 if (features.isNotEmpty()) listOf("--features", features.joinToString(",")) else emptyList()
416
417 // Cargo profile chosen once at configuration time (plain String, config-cache
418 // safe). Explicit `-Pmodernapps.rustProfile=fast|release` wins; otherwise fail
419 // safe: `fast` only when every requested task is a dev/cargo task, else
420 // `release` so an ambiguous build never ships a fast-profile .so.
421 val devTaskPattern = Regex("(Dev|Debug)(?=[A-Z]|$)")
422 val profile: String = providers.gradleProperty("modernapps.rustProfile").orNull?.let { requested ->
423 if (requested != "fast" && requested != "release") {
424 throw GradleException(
425 "Invalid -Pmodernapps.rustProfile=$requested: expected 'fast' or 'release'."
426 )
427 }
428 requested
429 } ?: run {
430 val taskNames = gradle.startParameter.taskNames
431 if (taskNames.isNotEmpty() && taskNames.all { name ->
432 val lastSegment = name.substringAfterLast(':')
433 lastSegment.startsWith("cargo") || devTaskPattern.containsMatchIn(lastSegment)
434 }
435 ) "fast" else "release"
436 }
437
438 // Cross-crate path deps (euicc -> library/jni-http, camera -> library/vision,
439 // maps/library:map -> library/tilecodec, ...), parsed generically from
440 // Cargo.toml below. Computed once per crate — identical for every ABI — as
441 // plain Files; only the FileCollections built from them cross into tasks.
442 val pathDepDirs: List<File> = findRustPathDepDirs(file(srcDir))
443
444 val compileShaders = if (shaders.isEmpty()) null else {
445 require(srcDir == "src/main/rust") { "rustNativeLib($crate): shaders need the default srcDir" }
446 val glslcExe = if (OperatingSystem.current().isWindows) "glslc.exe" else "glslc"
447 tasks.register<GlslcCompile>("compileShaders") {
448 description = "Compiles $crate's GLSL to SPIR-V."
449 shaderDir.set(file("$srcDir/shaders"))
450 sources.from(fileTree("$srcDir/shaders") { include(shaders) })
451 glslc.set("$ndkRoot/shader-tools/$hostTag/$glslcExe")
452 this.glslcArgs.set(glslcArgs)
453 outputDir.set(layout.buildDirectory.dir("spirv"))
454 }
455 }
456
457 val perAbi = rustAbis.map { abi ->
458 val (abiDir, triple) = abi
459 tasks.register<Exec>("cargoBuild_${crate}_${abiDir.replace('-', '_')}") {
460 usesService(rustLock)
461 description = "Cross-compiles lib$crate for $abiDir."
462 workingDir = file(srcDir)
463
464 // Windows hosts use the .cmd clang wrappers and .exe tool suffixes; Unix hosts none.
465 val isWindows = OperatingSystem.current().isWindows
466 val exeExt = if (isWindows) ".exe" else ""
467 val clangExt = if (isWindows) ".cmd" else ""
468 val clang = "$ndkBin/${abi.clangPrefix}$androidApiLevel-clang$clangExt"
469 val clangpp = "$ndkBin/${abi.clangPrefix}$androidApiLevel-clang++$clangExt"
470 val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"
471 // Per-crate target (may exist from older isolated builds) and workspace root target
472 // (current scheme since Cargo.toml workspace unified to root).
473 val perCrateSoOut = file("$srcDir/target/$triple/$profile/lib$crate.so")
474 val workspaceSoOut = rootProject.file("target/$triple/$profile/lib$crate.so")
475 val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/lib$crate.so").get().asFile
476 val targetRustflags = "-C link-arg=-Wl,-z,max-page-size=16384"
477
478 // Cacheable + relocatable: every input is RELATIVE-sensitive with a
479 // distinct property name, and toolchain facts the env doesn't cover
480 // (Exec treats environment/workingDir as @Internal, so env vars are
481 // NOT in the cache key) are explicit input properties. A fresh
482 // worktree at a different absolute path then restores FROM-CACHE.
483 outputs.cacheIf("Rust cdylib build is hermetic given the declared inputs") { true }
484
485 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
486 .withPropertyName("crateSrc")
487 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
488 .withPropertyName("crateManifest")
489 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
490 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
491 .withPropertyName("buildRs")
492 }
493 // The crate include_bytes!s build/spirv, so a shader edit must re-run cargo;
494 // otherwise the task stays up to date and the old SPIR-V silently ships.
495 compileShaders?.let {
496 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
497 .withPropertyName("spirv")
498 }
499 // `:library:ml`'s build.rs also compiles `schema/maml2.fbs` to Rust via
500 // flatc and `include!`s the result, so a schema edit changes the .so too.
501 // Same staleness hazard as shaders above: without this the task stays up
502 // to date and the old bindings ship.
503 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
504 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
505 .withPropertyName("schema")
506 }
507 // Whole-crate safety net: track every source under src/main/rust so ANY
508 // rust change invalidates cargoBuild - crucially vendored dependency
509 // crates under vendor/, which
510 // the path-specific inputs above do NOT cover. Before this, editing a
511 // vendored crate left the task UP-TO-DATE and shipped a stale .so. Exclude
512 // target/ because cargo writes this task's own .so there; folding build
513 // output back in as an input means the task can never be up to date. The
514 // FileTree is a FileCollection resolved at configuration time, so only the
515 // file set (never the Project) crosses into the task action.
516 inputs.files(fileTree(srcDir) { exclude("target/**") })
517 .withPathSensitivity(PathSensitivity.RELATIVE)
518 .withPropertyName("rustCrateTree")
519 // Cross-crate path deps (euicc -> jni-http, camera -> vision,
520 // maps -> tilecodec, ...): an edit there must rebuild this .so.
521 // Parsed generically from Cargo.toml `path =` + `workspace = true`
522 // entries (see findRustPathDepDirs), one input tree per dep crate.
523 for (depDir in pathDepDirs) {
524 val relDep = depDir.relativeTo(rootProject.projectDir)
525 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
526 .withPathSensitivity(PathSensitivity.RELATIVE)
527 .withPropertyName(pathDepPropertyName(rootProject.projectDir, depDir))
528 }
529 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
530 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
531 .withPropertyName("workspaceManifest")
532 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
533 .withPropertyName("workspaceLock")
534 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
535 .withPropertyName("rustToolchain")
536 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
537 // jni is a crates.io dependency now, so Cargo.lock above covers it.
538 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
539 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiSrc")
540 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
541 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiManifest")
542 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
543 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiBuildRs")
544 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
545 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiC")
546 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
547 inputs.dir(rootProject.file("third_party/betocore"))
548 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("betocore")
549 // Toolchain facts that shape the .so bytes but live in env/workingDir
550 // (both @Internal on Exec), so they need explicit input properties.
551 inputs.property("ndkVersion", NDK_VERSION)
552 inputs.property("hostTag", hostTag)
553 inputs.property("androidApiLevel", androidApiLevel)
554 inputs.property("targetRustflags", targetRustflags)
555 outputs.file(destSo)
556
557 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
558 val rustSrc = file(srcDir).absolutePath
559
560 val pathSep = if (isWindows) ";" else ":"
561 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
562 // A non-rustup rustc earlier on PATH (e.g. Homebrew's) has no
563 // aarch64-linux-android std, so cargo fails with "can't find crate for core".
564 // Pin the rustup shim explicitly.
565 environment("RUSTC", "$cargoBin/rustc$exeExt")
566 // The per-API NDK clang wrapper bakes in --target and the sysroot.
567 environment("CC", clang)
568 environment("CXX", clangpp)
569 environment("AR", "$ndkBin/llvm-ar$exeExt")
570 environment("SYSROOT", ndkSysroot)
571 environment(linkerVar, clang)
572 // Android 15 requires 16 KB page alignment on arm64 (Play blocks
573 // 4 KB .so files). Target-scoped so host build-script links on
574 // MSVC are unaffected. See analysis/plan-16kb-page-size.md.
575 val rustflagsVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_RUSTFLAGS"
576 environment(rustflagsVar, targetRustflags)
577 // Force the system clang for host-side C on Unix; on Windows let cc locate MinGW gcc.
578 if (!isWindows) environment("HOST_CC", "/usr/bin/clang")
579 // Pre-generated bindings (armv8-only): weather's om-file-format-sys no longer uses bindgen
580 // (bindings_android.rs/host checked in), so BINDGEN_EXTRA_CLANG_ARGS is no longer needed for build.
581 // Kept as comment for documentation if future C sys crates added.
582 // environment("BINDGEN_EXTRA_CLANG_ARGS", "--target=$triple$androidApiLevel --sysroot=$ndkSysroot")
583 // Reproducible builds: remap $HOME-specific paths (cargo registry + crate
584 // dir) to fixed constants so different machines produce identical .so bytes.
585 environment(
586 "RUSTFLAGS",
587 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",
588 )
589 environment("CFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
590 environment("CXXFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
591 environment("CPPFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
592 environment("ZERO_AR_DATE", "1")
593 // Reproducible builds: respect SOURCE_DATE_EPOCH if set (exported by the release build)
594 // https://reproducible-builds.org/docs/source-date-epoch/
595 System.getenv("SOURCE_DATE_EPOCH")?.takeIf { it.isNotBlank() }?.let {
596 environment("SOURCE_DATE_EPOCH", it)
597 }
598 environment("CARGO_INCREMENTAL", "0")
599
600 commandLine(
601 "$cargoBin/cargo$exeExt",
602 "build",
603 "--locked",
604 "--profile",
605 profile,
606 "--target",
607 triple,
608 *cargoFeatureArgs.toTypedArray(),
609 )
610
611 doLast {
612 destSo.parentFile.mkdirs()
613 val src = when {
614 perCrateSoOut.exists() -> perCrateSoOut
615 workspaceSoOut.exists() -> workspaceSoOut
616 else -> error("Neither per-crate ${perCrateSoOut.path} nor workspace ${workspaceSoOut.path} exists for $crate")
617 }
618 src.copyTo(destSo, overwrite = true)
619 }
620 }
621 }
622
623 val cargoNdkBuild = tasks.register("cargoNdkBuild_$crate") {
624 description = "Builds lib$crate.so for all Android ABIs."
625 dependsOn(perAbi)
626 }
627 // Keep the historic aggregate name for the default crate dir so existing
628 // invocations (`./gradlew :mod:cargoNdkBuild`) keep working.
629 if (srcDir == "src/main/rust") {
630 tasks.register("cargoNdkBuild") {
631 description = "Builds lib$crate.so for all Android ABIs."
632 dependsOn(cargoNdkBuild)
633 }
634 }
635 // Host cdylib for JVM unit tests (testDevUnitTest / testDevUnitTest):
636 // `cargo build --locked --target <hostTriple>` with the same profile,
637 // features, env (RUSTC pin, PATH, RUSTFLAGS remap, CARGO_INCREMENTAL=0),
638 // toolchain lock, inputs/outputs, and caching as the per-ABI tasks above —
639 // but WITHOUT any Android linker/NDK env (no CC/CXX/AR/SYSROOT, no
640 // per-target LINKER/RUSTFLAGS, no 16 KB page-size link arg: that flag
641 // would break the host link). The output (`lib<crate>.dylib/.so/.dll`)
642 // is installed into `build/rustHostLibs`, which nothing packages — APK/AAB
643 // assembly reads only `build/rustJniLibs`, so Android outputs are
644 // unchanged. Lazy by construction: nothing depends on this task except
645 // unit Test tasks (see wireRustHostLibsForUnitTests), so assemble/install
646 // never build it. With hostTests = false nothing is registered and
647 // dependents' tests never notice the crate.
648 val hostTriple: String = hostRustTriple()
649 val hostTaskName = "cargoBuildHost_$crate"
650 if (hostTests) {
651 val cargoBuildHost = tasks.register<Exec>(hostTaskName) {
652 usesService(rustLock)
653 description = "Builds lib$crate for the host (JVM unit tests)."
654 workingDir = file(srcDir)
655
656 val isWindowsHost = OperatingSystem.current().isWindows
657 val exeExt = if (isWindowsHost) ".exe" else ""
658 val hostLibName = hostRustLibFileName(crate)
659 // Per-crate target (may exist from older isolated builds) and workspace root target
660 // (current scheme since Cargo.toml workspace unified to root).
661 val perCrateHostOut = file("$srcDir/target/$hostTriple/$profile/$hostLibName")
662 val workspaceHostOut = rootProject.file("target/$hostTriple/$profile/$hostLibName")
663 val destHostLib = layout.buildDirectory.file("rustHostLibs/$hostLibName").get().asFile
664
665 // Same cacheable + relocatable shape as the per-ABI tasks: every
666 // input is RELATIVE-sensitive with a distinct (host-prefixed)
667 // property name, and host-toolchain facts the env doesn't cover
668 // are explicit input properties.
669 outputs.cacheIf("Rust cdylib host build is hermetic given the declared inputs") { true }
670
671 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
672 .withPropertyName("hostCrateSrc")
673 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
674 .withPropertyName("hostCrateManifest")
675 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
676 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
677 .withPropertyName("hostBuildRs")
678 }
679 // Same SPIR-V staleness hazard as the ABI tasks: the crate
680 // include_bytes!s build/spirv, so a shader edit must re-run cargo.
681 compileShaders?.let {
682 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
683 .withPropertyName("hostSpirv")
684 }
685 // Same flatc-bindings staleness hazard as the ABI tasks (see above).
686 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
687 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
688 .withPropertyName("hostSchema")
689 }
690 inputs.files(fileTree(srcDir) { exclude("target/**") })
691 .withPathSensitivity(PathSensitivity.RELATIVE)
692 .withPropertyName("hostRustCrateTree")
693 for (depDir in pathDepDirs) {
694 val relDep = depDir.relativeTo(rootProject.projectDir)
695 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
696 .withPathSensitivity(PathSensitivity.RELATIVE)
697 .withPropertyName("host_" + pathDepPropertyName(rootProject.projectDir, depDir))
698 }
699 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
700 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
701 .withPropertyName("hostWorkspaceManifest")
702 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
703 .withPropertyName("hostWorkspaceLock")
704 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
705 .withPropertyName("hostRustToolchain")
706 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
707 // jni is a crates.io dependency now, so Cargo.lock above covers it.
708 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
709 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiSrc")
710 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
711 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiManifest")
712 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
713 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiBuildRs")
714 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
715 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiC")
716 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
717 inputs.dir(rootProject.file("third_party/betocore"))
718 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostBetocore")
719 // Host-toolchain facts that shape the lib bytes but live in env/workingDir
720 // (both @Internal on Exec), so they need an explicit input property.
721 // Deliberately NOT the NDK props: the host link must not see them.
722 inputs.property("hostTriple", hostTriple)
723 outputs.file(destHostLib)
724
725 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
726 val rustSrc = file(srcDir).absolutePath
727
728 val pathSep = if (isWindowsHost) ";" else ":"
729 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
730 // Same non-rustup-rustc hazard as the ABI tasks: pin the shim.
731 environment("RUSTC", "$cargoBin/rustc$exeExt")
732 // Reproducible builds: same $HOME remap as the ABI tasks.
733 environment(
734 "RUSTFLAGS",
735 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",
736 )
737 environment("CARGO_INCREMENTAL", "0")
738
739 commandLine(
740 "$cargoBin/cargo$exeExt",
741 "build",
742 "--locked",
743 "--profile",
744 profile,
745 "--target",
746 hostTriple,
747 *cargoFeatureArgs.toTypedArray(),
748 )
749
750 doLast {
751 destHostLib.parentFile.mkdirs()
752 val src = when {
753 perCrateHostOut.exists() -> perCrateHostOut
754 workspaceHostOut.exists() -> workspaceHostOut
755 else -> error("Neither per-crate ${perCrateHostOut.path} nor workspace ${workspaceHostOut.path} exists for $crate")
756 }
757 src.copyTo(destHostLib, overwrite = true)
758 }
759 }
760 // Same historic-aggregate convenience as cargoNdkBuild for the default
761 // crate dir (`./gradlew :mod:cargoBuildHost`); per-crate task names stay
762 // unique for multi-crate modules (communicate's rust-mls second crate).
763 if (srcDir == "src/main/rust") {
764 tasks.register("cargoBuildHost") {
765 description = "Builds lib$crate for the host (JVM unit tests)."
766 dependsOn(cargoBuildHost)
767 }
768 }
769 // Recorded for wireRustHostLibsForUnitTests: plain strings only, so the
770 // configuration cache never sees a Project.
771 rustHostLibRefs().getOrPut(path) { mutableListOf() } += RustHostLibRef(
772 projectPath = path,
773 taskName = hostTaskName,
774 libDir = layout.buildDirectory.dir("rustHostLibs").get().asFile.absolutePath,
775 )
776 } else {
777 logger.warn("rustNativeLib($crate): hostTests = false — JVM unit tests cannot load this crate.")
778 }
779 // Rust file-length gate: fails the build on any *.rs over
780 // RUST_FILE_LENGTH_LIMIT lines, like the Kotlin FileLength rule (which
781 // cannot see Rust). Configuration-cache compatible: plain path strings
782 // cross the configuration boundary, never the Project object.
783 val rustSrcPath: String = file("$srcDir/src").absolutePath
784 val rustProjPath: String = projectDir.absolutePath
785 val lengthTaskName = if (srcDir == "src/main/rust") "rustFileLength" else "rustFileLength_$crate"
786 val rustFileLength = tasks.register(lengthTaskName) {
787 description = "Fails on Rust files over $RUST_FILE_LENGTH_LIMIT lines."
788 inputs.dir(rustSrcPath)
789 doLast {
790 val srcDir = java.io.File(rustSrcPath)
791 val projDir = java.io.File(rustProjPath)
792 val over = srcDir.walkTopDown()
793 .filter { it.isFile && it.extension == "rs" }
794 .map { it to it.readLines().size }
795 .filter { (f, n) ->
796 n > RUST_FILE_LENGTH_LIMIT &&
797 f.name !in RUST_LENGTH_EXEMPT_FILES &&
798 !isRustLengthExempt(f.path)
799 }
800 .toList()
801 if (over.isNotEmpty()) {
802 val detail = over.joinToString("\n") { (f, n) ->
803 " $n ${f.relativeTo(projDir)}"
804 }
805 throw org.gradle.api.GradleException(
806 "Rust files exceed $RUST_FILE_LENGTH_LIMIT lines (split along module lines):\n$detail"
807 )
808 }
809 }
810 }
811 tasks.matching { it.name == "preBuild" }.configureEach {
812 dependsOn(cargoNdkBuild)
813 dependsOn(rustFileLength)
814 }
815}
816
817/**
818 * One host-testable crate registered by [rustNativeLib]: the owning project's
819 * path, the host build task name, and the `build/rustHostLibs` dir. Plain
820 * strings only, so the configuration cache never sees a Project.
821 */
822data class RustHostLibRef(
823 val projectPath: String,
824 val taskName: String,
825 val libDir: String,
826)
827
828/** Shared `projectPath -> host crates` registry (see [RustHostLibRef]). */
829private fun Project.rustHostLibRefs(): MutableMap<String, MutableList<RustHostLibRef>> {
830 val extra = rootProject.extensions.extraProperties
831 @Suppress("UNCHECKED_CAST")
832 return if (extra.has("rustHostLibRefs")) {
833 extra.get("rustHostLibRefs") as MutableMap<String, MutableList<RustHostLibRef>>
834 } else {
835 mutableMapOf<String, MutableList<RustHostLibRef>>().also { extra.set("rustHostLibRefs", it) }
836 }
837}
838
839/**
840 * Wires every unit [Test] task (testDevUnitTest, testDebugUnitTest, ...) so
841 * `System.loadLibrary` finds Rust cdylibs on the host JVM: each Test task
842 * depends on the host build tasks of this module and of every project it
843 * transitively depends on that registered one via [rustNativeLib]
844 * (e.g. `:office` also picks up `:library:e2ee-p2p`'s `e2ee_pqc`), and
845 * `java.library.path` gains each of their `build/rustHostLibs` dirs.
846 *
847 * The existing value is appended to, never clobbered: AGP's own
848 * `src/test/jniLibs` dirs (which AGP merges into the same property) survive
849 * regardless of ordering, because both sides merge. Crates opted out with
850 * `hostTests = false` register no task and are skipped cleanly.
851 *
852 * Laziness: the host tasks are reachable only through these `dependsOn`
853 * edges, so assemble/install never build them. Configuration-cache safe:
854 * `evaluationDependsOn` pulls transitive deps through evaluation before any
855 * state is read, and only plain strings (task paths, dir paths) cross into
856 * task configuration — never a Project.
857 */
858fun Project.wireRustHostLibsForUnitTests() {
859 // Deferred to afterEvaluate: the module's own `dependencies {}` block runs
860 // after the convention plugin, so the project-dep graph is only complete
861 // then. Task wiring uses configureEach, which covers Test tasks whether
862 // AGP already created them or creates them later.
863 afterEvaluate {
864 val self = this@wireRustHostLibsForUnitTests
865 val ordered = mutableListOf<String>()
866 val seen = HashSet<String>()
867 seen += self.path
868 val queue = ArrayDeque<String>()
869 fun enqueueDepsOf(p: Project) {
870 p.configurations.forEach { cfg ->
871 cfg.dependencies.filterIsInstance<ProjectDependency>().forEach { dep ->
872 val depPath = dep.path
873 if (seen.add(depPath)) {
874 queue += depPath
875 ordered += depPath
876 }
877 }
878 }
879 }
880 enqueueDepsOf(self)
881 while (queue.isNotEmpty()) {
882 val depPath = queue.removeFirst()
883 self.evaluationDependsOn(depPath)
884 enqueueDepsOf(self.project(depPath))
885 }
886 val refs = (listOf(self.path) + ordered).flatMap { rustHostLibRefs()[it].orEmpty() }
887 if (refs.isEmpty()) return@afterEvaluate
888 self.tasks.withType<Test>().configureEach {
889 refs.forEach { ref -> dependsOn("${ref.projectPath}:${ref.taskName}") }
890 val sep = File.pathSeparator
891 val existing = (systemProperties["java.library.path"] as? String)
892 ?.split(sep).orEmpty()
893 val merged = (existing + refs.map { it.libDir }).distinct()
894 systemProperty("java.library.path", merged.joinToString(sep))
895 // A JNI library can be bound to only one classloader per JVM. Plain JVM tests
896 // load it via the app classloader and Robolectric tests via its sandbox loader,
897 // so mixing both in one JVM fails with "already loaded in another classloader".
898 // One JVM per test class keeps each loader's System.loadLibrary isolated.
899 forkEvery = 1
900 }
901 }
902}