All checks were successful
android-ci / android (pull_request) Successful in 30m59s
`openWire` segfaults at `dlopen` on every ABI, so the app dies the moment the
passphrase is submitted and the onion never publishes. The tombstone:
signal 11 (SIGSEGV), fault addr 0x0
#00 libonionwire_sdk.so (getauxval+21)
#01 libonionwire_sdk.so (__cxa_atexit+604)
#02 libonionwire_sdk.so (_GLOBAL__sub_I_superscalar.cpp+891)
#06 libjnidispatch.so (Java_com_sun_jna_Native_open+68)
#42 uniffi.onionwire_sdk.Onionwire_sdkKt.openWire+0
`_GLOBAL__sub_I_superscalar.cpp` is RandomX's, and RandomX arrived with the
`cuprate-daemon` feature (#113). It calls `getauxval` from a static
initializer — and `libonionwire_sdk.so` had linked bionic **statically**, so
that `getauxval` read an auxv vector only the dynamic linker ever fills in.
The first SDK call is the first `dlopen`, which is the first time anything
touches the library: the crash lands exactly on "user typed the password".
The static libc came in with the same commit that added the C++ link flags.
`linkFlags()` passes `-L<ndk>/sysroot/usr/lib/<triple>` for the libc++
archives; that directory also holds the static `libc.a`, while the dynamic
`libc.so` stub lives in the per-API subdirectory that cargo-ndk's linker
wrapper normally supplies — and that wrapper is bypassed on purpose here, so
the per-API directory was no longer on the search path at all and `-lc`
resolved to `libc.a`. Both directories are now passed, the per-API one first,
and `verifyDynamicLibc` fails the build if `libc.so` ever leaves DT_NEEDED
again.
before (v0.9.0 arm64): NEEDED liblog.so only, local getauxval/__cxa_atexit
after: NEEDED libstdc++.so, libdl, liblog, libm, libc.so, no local libc
Also: the keep-alive notice is re-announced with the locator once the node
publishes. It is anchored at the Open tap with an empty onion (so the shade
does not claim a reachable node while Tor bootstraps), and only the
POST_NOTIFICATIONS callback ever replaced it — on a device that already
granted notifications there is no callback at all, so the notice claimed
"OnionWire is starting" forever.
356 lines
16 KiB
Kotlin
356 lines
16 KiB
Kotlin
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
|
|
|
plugins {
|
|
alias(libs.plugins.android.library)
|
|
alias(libs.plugins.kotlin.android)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Rust: build crates/onionwire-sdk for the requested Android ABIs and generate
|
|
// the UniFFI Kotlin bindings from the host cdylib.
|
|
//
|
|
// Nothing here touches the Linux TUI crate's feature graph: the SDK crate is
|
|
// its own Cargo workspace that selects Arti's rustls backend.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
val repoRoot: File = rootProject.projectDir.parentFile
|
|
val sdkCrateDir: File = repoRoot.resolve("crates/onionwire-sdk")
|
|
|
|
/** NDK version used for the Rust link step. Must match an installed NDK. */
|
|
val onionwireNdkVersion: String = (findProperty("onionwire.ndk") as String?)
|
|
?: "28.2.13676358"
|
|
|
|
/** Compile against this API level. Keep in sync with `minSdk`. */
|
|
val onionwireApiLevel: Int = ((findProperty("onionwire.api") as String?) ?: "26").toInt()
|
|
|
|
val androidSdkDir: File = sequenceOf(
|
|
System.getenv("ANDROID_HOME"),
|
|
System.getenv("ANDROID_SDK_ROOT"),
|
|
).filterNotNull().map(::File).firstOrNull()
|
|
?: rootProject.file("local.properties")
|
|
.takeIf { it.exists() }
|
|
?.readLines()
|
|
?.firstOrNull { it.startsWith("sdk.dir=") }
|
|
?.substringAfter('=')
|
|
?.trim()
|
|
?.let(::File)
|
|
?: error("ANDROID_HOME / ANDROID_SDK_ROOT unset and no sdk.dir in android/local.properties")
|
|
|
|
val ndkDir: File = androidSdkDir.resolve("ndk/$onionwireNdkVersion")
|
|
require(ndkDir.isDirectory) {
|
|
"NDK $onionwireNdkVersion not found at $ndkDir — run: sdkmanager --install \"ndk;$onionwireNdkVersion\""
|
|
}
|
|
|
|
val cargoExe: String = (findProperty("onionwire.cargo") as String?)
|
|
?: System.getenv("CARGO")
|
|
?: File(System.getProperty("user.home"), ".cargo/bin/cargo").takeIf { it.canExecute() }?.absolutePath
|
|
?: "cargo"
|
|
|
|
/** `-Ponionwire.abis=arm64-v8a,x86_64` to build more than one ABI. */
|
|
val onionwireAbis: List<String> = (findProperty("onionwire.abis") as String?)
|
|
?.split(',')?.map(String::trim)?.filter(String::isNotEmpty)
|
|
?: listOf("arm64-v8a")
|
|
|
|
/**
|
|
* Rust features for the **Android** target build.
|
|
*
|
|
* `cuprate-daemon` is what puts the in-process Monero chain daemon (Cuprate) in
|
|
* the APK — the SDK crate's passthrough to the core
|
|
* (`cuprate-daemon = ["onionwire/cuprate-daemon"]`), so `WalletChildStatus.node_available`
|
|
* is `true` on the device and `ChainChoice.InProcessCuprate` can actually start.
|
|
*
|
|
* Deliberately **not** applied to `cargoHostLib` / `uniffiBindgen`: those build a
|
|
* host cdylib only so `uniffi-bindgen --library` can dlopen it, the cuprated graph
|
|
* (152 crates plus a C++ RandomX build) buys nothing there, and the UniFFI surface
|
|
* does not fork on a cargo feature. The Kotlin bindings are byte-identical either
|
|
* way, which is what `crates/onionwire-sdk`'s own tests cover.
|
|
*/
|
|
val onionwireRustFeatures: List<String> = listOf("cuprate-daemon")
|
|
|
|
/** `arm64-v8a` -> the Rust triple, the sysroot dir name and the builtins archive. */
|
|
data class AndroidTarget(
|
|
val abi: String,
|
|
val triple: String,
|
|
/** Sysroot library dir under `.../sysroot/usr/lib/`. */
|
|
val sysrootLib: String,
|
|
/** `libclang_rt.builtins-<this>.a`, from the NDK clang resource dir. */
|
|
val builtins: String,
|
|
/** NDK clang driver prefix: `<this><api>-clang`. */
|
|
val clangPrefix: String,
|
|
)
|
|
|
|
val androidTargets: Map<String, AndroidTarget> = listOf(
|
|
AndroidTarget("arm64-v8a", "aarch64-linux-android", "aarch64-linux-android", "aarch64-android", "aarch64-linux-android"),
|
|
AndroidTarget("x86_64", "x86_64-linux-android", "x86_64-linux-android", "x86_64-android", "x86_64-linux-android"),
|
|
AndroidTarget("armeabi-v7a", "armv7-linux-androideabi", "arm-linux-androideabi", "arm-android", "armv7a-linux-androideabi"),
|
|
AndroidTarget("x86", "i686-linux-android", "i686-linux-android", "i386-android", "i686-linux-android"),
|
|
).associateBy(AndroidTarget::abi)
|
|
|
|
/** The NDK's host tag (`linux-x86_64`, `darwin-x86_64`, …) — exactly one prebuilt tree. */
|
|
val ndkHostTag: String = ndkDir.resolve("toolchains/llvm/prebuilt").listFiles()
|
|
?.filter(File::isDirectory)?.singleOrNull()?.name
|
|
?: error("expected exactly one NDK prebuilt toolchain under $ndkDir/toolchains/llvm/prebuilt")
|
|
|
|
/** The NDK clang resource dir (`lib/clang/<version>/lib/linux`) — exactly one version. */
|
|
val ndkClangLibDir: File = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
|
|
.listFiles()?.filter(File::isDirectory)?.singleOrNull()
|
|
?.resolve("lib/linux")
|
|
?: error("expected exactly one clang resource dir under $ndkDir/toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
|
|
|
|
/**
|
|
* Per-ABI link flags for the Android build.
|
|
*
|
|
* RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s
|
|
* build script emits `rustc-link-lib=static=stdc++` against the NDK's *stub*
|
|
* `libstdc++.a`. Without libc++ and the compiler-rt builtins on the link line the
|
|
* build dies on `__cxa_allocate_exception` / `std::runtime_error` / `typeinfo`
|
|
* (and `__clear_cache`) undefined. `cargo ndk --link-builtins` covers only the
|
|
* builtins, not libc++ — and `-static-libstdc++` is ignored by NDK clang — so the
|
|
* whole set is spelled out. Recipe and evidence: `docs/cuprate-android-spike.md`.
|
|
*
|
|
* Exported as `CARGO_TARGET_<TRIPLE>_RUSTFLAGS` rather than `RUSTFLAGS`: a global
|
|
* rustflags would also apply to build scripts and proc macros, which are
|
|
* **host**-targeted, and `-lc++_static` there breaks the host link.
|
|
*
|
|
* The same variables also *replace* any `target.<triple>.rustflags` in
|
|
* `~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated here.
|
|
*/
|
|
fun linkFlags(target: AndroidTarget): String {
|
|
val sysrootLib = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/sysroot/usr/lib/${target.sysrootLib}")
|
|
// The *dynamic* libc/libm/libdl stubs live in a per-API subdirectory; the
|
|
// arch directory above holds the static `libc.a` and the libc++ archives.
|
|
// Both must be on the search path, and this one must come first: `-lc`
|
|
// resolves to whichever the linker finds first, and bionic linked
|
|
// statically into a shared object is a landmine — its `getauxval` reads an
|
|
// auxv vector only the dynamic linker fills in, so the first C++ static
|
|
// initializer that asks for it (RandomX's, from `cuprate-daemon`) null-derefs
|
|
// inside `dlopen` and takes the process with it.
|
|
val sysrootStubLib = sysrootLib.resolve(onionwireApiLevel.toString())
|
|
require(sysrootStubLib.resolve("libc.so").isFile) {
|
|
"no dynamic libc stub at $sysrootStubLib/libc.so — NDK $onionwireNdkVersion layout changed? " +
|
|
"Linking the arch dir alone would pull in the static libc.a."
|
|
}
|
|
return listOf(
|
|
// Hygiene on a hand-written link line: lld defaults to --no-as-needed,
|
|
// which records a DT_NEEDED for every `-l` mentioned even when nothing
|
|
// is taken from it. (`libstdc++.so` survives this anyway — randomx-rs's
|
|
// cmake half asks for it and it satisfies symbols the static libc++
|
|
// archives were already scanned for. That shim is present on every
|
|
// Android release to date; the device run in the PR loads it.)
|
|
"-C", "link-arg=-Wl,--as-needed",
|
|
"-C", "link-arg=-L$sysrootStubLib",
|
|
"-C", "link-arg=-L$sysrootLib",
|
|
"-C", "link-arg=-L$ndkClangLibDir",
|
|
"-C", "link-arg=-lclang_rt.builtins-${target.builtins}",
|
|
"-C", "link-arg=-lc++_static",
|
|
"-C", "link-arg=-lc++abi",
|
|
"-C", "link-arg=-Wl,--exclude-libs,libc++_static.a",
|
|
"-C", "link-arg=-Wl,--exclude-libs,libc++abi.a",
|
|
).joinToString(" ")
|
|
}
|
|
|
|
/** The NDK clang driver for one ABI at [onionwireApiLevel]. */
|
|
private fun clangDriver(target: AndroidTarget): File =
|
|
ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/${target.clangPrefix}$onionwireApiLevel-clang")
|
|
|
|
val jniLibsDir = layout.buildDirectory.dir("rustJniLibs")
|
|
val uniffiKotlinDir = layout.buildDirectory.dir("generated/uniffi")
|
|
|
|
// cargo honors CARGO_TARGET_DIR when set (CI sibling container). UniFFI's
|
|
// --library path must match, or bindgen dies with ENOENT after a green compile.
|
|
val cargoTargetDir: File = System.getenv("CARGO_TARGET_DIR")?.let(::File)
|
|
?: sdkCrateDir.resolve("target")
|
|
val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so")
|
|
|
|
/**
|
|
* Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch.
|
|
*
|
|
* Feature-free **on purpose**: this exists only to emit the Kotlin bindings, and
|
|
* `cuprate-daemon` would drag the whole Cuprate graph (152 crates + a C++ RandomX
|
|
* build) through a host compile that never runs the daemon. The UniFFI surface
|
|
* does not fork on a cargo feature — `ChainChoice.InProcessCuprate` is present in
|
|
* both — so the generated Kotlin is the same. `onionwireRustFeatures` is for
|
|
* [cargoBuildAndroid] only.
|
|
*/
|
|
val cargoHostLib by tasks.registering(Exec::class) {
|
|
group = "onionwire"
|
|
description = "Builds libonionwire_sdk.so for the host (used only to emit bindings)."
|
|
workingDir = sdkCrateDir
|
|
environment("ANDROID_HOME", androidSdkDir.absolutePath)
|
|
commandLine(cargoExe, "build", "--release", "--lib")
|
|
}
|
|
|
|
val uniffiBindgen by tasks.registering(Exec::class) {
|
|
group = "onionwire"
|
|
description = "Generates the Kotlin UniFFI bindings into build/generated/uniffi."
|
|
dependsOn(cargoHostLib)
|
|
workingDir = sdkCrateDir
|
|
inputs.file(sdkCrateDir.resolve("src/lib.rs"))
|
|
outputs.dir(uniffiKotlinDir)
|
|
environment("ANDROID_HOME", androidSdkDir.absolutePath)
|
|
doFirst { uniffiKotlinDir.get().asFile.mkdirs() }
|
|
commandLine(
|
|
cargoExe, "run", "--release", "--bin", "uniffi-bindgen", "--",
|
|
"generate",
|
|
"--library", hostCdylib.absolutePath,
|
|
"--language", "kotlin",
|
|
"--no-format",
|
|
"--config", "uniffi.toml",
|
|
"--out-dir", uniffiKotlinDir.get().asFile.absolutePath,
|
|
)
|
|
}
|
|
|
|
val cargoBuildAndroid by tasks.registering(Exec::class) {
|
|
group = "onionwire"
|
|
description = "Cross-compiles crates/onionwire-sdk for ${onionwireAbis.joinToString()}."
|
|
workingDir = sdkCrateDir
|
|
inputs.dir(sdkCrateDir.resolve("src"))
|
|
inputs.file(sdkCrateDir.resolve("Cargo.toml"))
|
|
inputs.file(sdkCrateDir.resolve("Cargo.lock"))
|
|
inputs.dir(repoRoot.resolve("src"))
|
|
inputs.file(repoRoot.resolve("Cargo.toml"))
|
|
// The feature set is an input: `-Ponionwire.features=` … there is no knob
|
|
// (a build that silently dropped `cuprate-daemon` would ship an APK whose
|
|
// on-device node can only fail), but the task must not stay "up to date"
|
|
// across a change to this list.
|
|
inputs.property("rustFeatures", onionwireRustFeatures)
|
|
outputs.dir(jniLibsDir)
|
|
environment("ANDROID_HOME", androidSdkDir.absolutePath)
|
|
environment("ANDROID_NDK_HOME", ndkDir.absolutePath)
|
|
environment("NDK_HOME", ndkDir.absolutePath)
|
|
// `cmake-rs` (RandomX's C++ half) aborts with "Neither the NDK or a standalone
|
|
// toolchain was found" unless ANDROID_NDK itself is exported — NDK_HOME and
|
|
// ANDROID_NDK_HOME are not enough, and `randomx-rs`'s build script then panics
|
|
// inside `cmake`.
|
|
environment("ANDROID_NDK", ndkDir.absolutePath)
|
|
environment("ANDROID_NDK_ROOT", ndkDir.absolutePath)
|
|
// Per-ABI link env. The clang driver is named explicitly because
|
|
// `~/.cargo/config.toml` on the dev machines pins the *API 21* wrapper for
|
|
// `aarch64-linux-android`, and API 21 fails this link (`pthread_atfork` is
|
|
// API 23+); `cargo-ndk`'s own linker wrapper is bypassed on purpose so the
|
|
// `-Wl,…` args below reach clang as link args.
|
|
onionwireAbis.forEach { abi ->
|
|
val target = androidTargets[abi]
|
|
?: error("no Android target mapping for ABI '$abi' — add it to androidTargets in sdk/build.gradle.kts")
|
|
val rustFlagsVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_RUSTFLAGS"
|
|
val linkerVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_LINKER"
|
|
val linker = clangDriver(target)
|
|
require(linker.canExecute()) {
|
|
"NDK clang driver for $abi not found at $linker — NDK $onionwireNdkVersion incomplete?"
|
|
}
|
|
environment(rustFlagsVar, linkFlags(target))
|
|
environment(linkerVar, linker.absolutePath)
|
|
}
|
|
commandLine(
|
|
buildList {
|
|
add(cargoExe); add("ndk")
|
|
onionwireAbis.forEach { add("-t"); add(it) }
|
|
add("--platform"); add(onionwireApiLevel.toString())
|
|
add("-o"); add(jniLibsDir.get().asFile.absolutePath)
|
|
add("build"); add("--release"); add("--lib")
|
|
if (onionwireRustFeatures.isNotEmpty()) {
|
|
add("--features"); add(onionwireRustFeatures.joinToString(","))
|
|
}
|
|
}
|
|
)
|
|
// The CI log has to show the feature actually requested, not merely the task
|
|
// name: "the feature is in the artifact" is checked against this line.
|
|
doFirst {
|
|
logger.lifecycle(
|
|
"cargo ndk build for ${onionwireAbis.joinToString()} " +
|
|
"features=${onionwireRustFeatures.joinToString(",").ifEmpty { "(none)" }} " +
|
|
"api=$onionwireApiLevel ndk=$onionwireNdkVersion",
|
|
)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
android {
|
|
namespace = "com.siriusdevops.onionwire.sdk"
|
|
compileSdk = 36
|
|
ndkVersion = onionwireNdkVersion
|
|
|
|
defaultConfig {
|
|
minSdk = onionwireApiLevel
|
|
consumerProguardFiles("consumer-rules.pro")
|
|
ndk {
|
|
abiFilters += onionwireAbis
|
|
}
|
|
}
|
|
|
|
compileOptions {
|
|
sourceCompatibility = JavaVersion.VERSION_17
|
|
targetCompatibility = JavaVersion.VERSION_17
|
|
}
|
|
|
|
sourceSets["main"].jniLibs.srcDir(jniLibsDir)
|
|
sourceSets["main"].kotlin.srcDir(uniffiKotlinDir)
|
|
|
|
buildTypes {
|
|
release {
|
|
isMinifyEnabled = false
|
|
}
|
|
}
|
|
}
|
|
|
|
kotlin {
|
|
compilerOptions {
|
|
jvmTarget.set(JvmTarget.JVM_17)
|
|
}
|
|
}
|
|
|
|
dependencies {
|
|
// UniFFI's Kotlin backend talks to the Rust cdylib through JNA direct
|
|
// mapping, and the async bindings need coroutines. Both are part of the
|
|
// public API surface, so they are `api` — a consumer of the AAR needs them
|
|
// on its own compile classpath. JNA's `aar` variant is what carries
|
|
// libjnidispatch.so for each ABI.
|
|
api(variantOf(libs.jna) { artifactType("aar") })
|
|
api(libs.kotlinx.coroutines.core)
|
|
}
|
|
|
|
tasks.withType<KotlinCompile>().configureEach {
|
|
dependsOn(uniffiBindgen)
|
|
}
|
|
|
|
/**
|
|
* Fails the build if the SDK's shared object did not link bionic dynamically.
|
|
*
|
|
* `linkFlags()` spells the NDK search path out by hand, and `-L` order decides
|
|
* whether `-lc` resolves to the per-API `libc.so` stub or to the arch
|
|
* directory's `libc.a`. Static bionic inside a `.so` leaves `getauxval` reading
|
|
* an auxv vector only the dynamic linker fills in, so the first C++ static
|
|
* initializer that asks for CPU features null-derefs inside `dlopen` — a crash
|
|
* with no Java stack, at the first SDK call, on every ABI. Reading the built
|
|
* ELF is the only check that catches it before a device does.
|
|
*/
|
|
val verifyDynamicLibc by tasks.registering {
|
|
group = "verification"
|
|
description = "Asserts libonionwire_sdk.so links libc.so dynamically (no static bionic)."
|
|
dependsOn(cargoBuildAndroid)
|
|
val libsDir = jniLibsDir
|
|
val abis = onionwireAbis
|
|
val readelf = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/llvm-readelf")
|
|
doLast {
|
|
abis.forEach { abi ->
|
|
val so = libsDir.get().asFile.resolve(abi).resolve("libonionwire_sdk.so")
|
|
check(so.isFile) { "no $so to verify — did cargoBuildAndroid run for $abi?" }
|
|
val proc = ProcessBuilder(readelf.absolutePath, "-d", so.absolutePath)
|
|
.redirectErrorStream(true)
|
|
.start()
|
|
val dump = proc.inputStream.bufferedReader().use { it.readText() }
|
|
check(proc.waitFor() == 0) { "$readelf failed on $so:\n$dump" }
|
|
check(dump.lineSequence().any { it.contains("(NEEDED)") && it.contains("libc.so") }) {
|
|
"$so has no libc.so in DT_NEEDED — it linked the static libc.a. " +
|
|
"That is the `-L` order in linkFlags() regressing; a device crashes " +
|
|
"with a null deref in getauxval the first time the SDK is dlopen'd.\n$dump"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
tasks.matching { it.name == "preBuild" }.configureEach {
|
|
dependsOn(cargoBuildAndroid, uniffiBindgen, verifyDynamicLibc)
|
|
}
|