diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 430d2b0..e9cc639 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -70,8 +70,6 @@ jobs: "build-tools;34.0.0" \ "ndk;$ANDROID_NDK_VERSION" >/dev/null set -o pipefail - echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$ANDROID_NDK_VERSION" \ - >> "$GITHUB_ENV" - name: Resolve version and variant id: metadata @@ -132,79 +130,31 @@ jobs: echo "DAWNSHELL_RELEASE_KEY_PASSWORD=$KEY_PASSWORD" } >> "$GITHUB_ENV" - - name: Build bootstrap runtime from pinned source + - name: Lint shell scripts shell: bash run: | set -euo pipefail "$DAWNSHELL_SHELLCHECK" --version - "$DAWNSHELL_SHELLCHECK" scripts/*.sh app/src/main/assets/bfu/*.sh - # Report which script failed. A bare list of commands collapses into - # one opaque step failure that hides the actual stage. - for stage in \ - scripts/test-release-compliance.sh \ - scripts/build-bootstrap-runtime.sh \ - scripts/test-hardware-codec-bridge.sh \ - scripts/test-ffmpeg-bridge-plan.sh \ - scripts/test-kernel-quirk-guards.sh \ - scripts/test-gpu-status-tool.sh \ - scripts/test-live-codec-pipeline.sh \ - scripts/test-host-reboot-isolation.sh \ - scripts/test-compatibility-policy.sh \ - scripts/test-dashboard-settings-ux.sh \ - scripts/test-rootfs-path-resolution.sh \ - scripts/test-lifecycle-control-policy.sh \ - scripts/test-croc-compatibility-wrapper.sh \ - scripts/test-documentation.sh ; do - echo "::group::$stage" - stage_log="$RUNNER_TEMP/$(basename "$stage").log" - if ! "./$stage" 2>&1 | tee "$stage_log"; then - echo "::endgroup::" - echo "::error::failing stage: $stage" - trace_log="$RUNNER_TEMP/$(basename "$stage").trace.log" - set +e - bash -x "./$stage" > "$trace_log" 2>&1 - trace_status=$? - set -e - trace_tail="$(tail -n 40 "$trace_log" | tr '\n' ' ' | tr '\r' ' ')" - trace_tail="${trace_tail//'%'/'%25'}" - trace_tail="${trace_tail//$'\r'/'%0D'}" - trace_tail="${trace_tail//$'\n'/'%0A'}" - echo "::error::failure trace exit=$trace_status: $trace_tail" - # The job summary survives log-access restrictions, so record - # the failing stage there as well. - { - echo "failing stage: $stage" - echo "trace exit: $trace_status" - echo - echo '```text' - tail -n 240 "$trace_log" - echo '```' - } >> "$GITHUB_STEP_SUMMARY" - exit 1 - fi - echo "::endgroup::" - done + "$DAWNSHELL_SHELLCHECK" scripts/*.sh scripts/tests/*/*.sh app/src/main/assets/bfu/*.sh - - name: Build and test Android application + - name: Build, verify and test Android application id: apk shell: bash env: VARIANT: ${{ steps.metadata.outputs.variant }} run: | set -euo pipefail - if [[ "$VARIANT" == release ]]; then - ./gradlew --no-daemon clean \ - :app:assembleRelease :app:lintRelease :app:testDebugUnitTest - else - ./gradlew --no-daemon clean \ - :app:assembleDebug :app:lintDebug :app:testDebugUnitTest - fi + # Gradle compiles the bundled native runtime from pinned source for + # every ABI, then runs the policy scripts, lint and unit tests. + task_variant="${VARIANT^}" + ./gradlew --no-daemon --console=plain clean policyChecks \ + ":app:assemble$task_variant" ":app:lint$task_variant" :app:testDebugUnitTest apk_path="$(find "app/build/outputs/apk/$VARIANT" \ -maxdepth 1 -type f -name '*.apk' -print -quit)" [[ -n "$apk_path" && -s "$apk_path" ]] "$ANDROID_HOME/build-tools/34.0.0/apksigner" \ verify --verbose --print-certs "$apk_path" - ./scripts/test-release-compliance.sh "$apk_path" + ./scripts/tests/host/test-release-compliance.sh "$apk_path" echo "apk_path=$apk_path" >> "$GITHUB_OUTPUT" - name: Package APK, corresponding source, licenses and checksums diff --git a/README.ko.md b/README.ko.md index 6edd0f9..49c0972 100644 --- a/README.ko.md +++ b/README.ko.md @@ -115,12 +115,13 @@ PIN 입력 전에 사용할 데이터에는 재사용 auth key, API token, SSH ```sh export JAVA_HOME=/path/to/jdk17 export ANDROID_HOME=/path/to/android-sdk -export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865" -./scripts/build-all.sh +./gradlew clean policyChecks :app:lintDebug :app:testDebugUnitTest :app:stageDebugApk ``` -기본값은 `make -j"$(nproc)"`이며 `DAWNSHELL_BUILD_JOBS`로 병렬 작업 수를 제한할 -수 있습니다. debug APK는 `dist/dawnshell-app_v+debug.apk`에 생성됩니다. +Gradle이 내장 네이티브 런타임을 고정 소스에서 모든 ABI용으로 컴파일하며, SDK에 +NDK `29.0.14206865`가 설치되어 있어야 합니다. 기본값은 `make -j"$(nproc)"`이며 +`DAWNSHELL_BUILD_JOBS`로 병렬 작업 수를 제한할 수 있습니다. debug APK는 +`dist/dawnshell-app_v+debug.apk`에 생성됩니다. 필요 패키지, Windows/MSYS2, 개별 검사, 서명, CI와 Release 묶음은 [빌드와 배포](docs/building.ko.md)를 참고하세요. 공개 debug 키는 제품용 서명 키가 diff --git a/README.md b/README.md index 8dbde47..c84a46c 100644 --- a/README.md +++ b/README.md @@ -125,13 +125,13 @@ The short path is: ```sh export JAVA_HOME=/path/to/jdk17 export ANDROID_HOME=/path/to/android-sdk -export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865" -./scripts/build-all.sh +./gradlew clean policyChecks :app:lintDebug :app:testDebugUnitTest :app:stageDebugApk ``` -Compilation uses `make -j"$(nproc)"` by default. Set `DAWNSHELL_BUILD_JOBS` to -limit parallel jobs. The debug APK is written as -`dist/dawnshell-app_v+debug.apk`. +Gradle compiles the bundled native runtime for every ABI from pinned source; +NDK `29.0.14206865` must be installed in the SDK. Compilation uses +`make -j"$(nproc)"` by default. Set `DAWNSHELL_BUILD_JOBS` to limit parallel +jobs. The debug APK is written as `dist/dawnshell-app_v+debug.apk`. See [Build and release](docs/building.md) for dependencies, Windows/MSYS2, individual checks, signing, CI behavior, and release packaging. The public debug diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a8568c7..e494394 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,4 +1,6 @@ import com.android.build.api.variant.impl.VariantOutputImpl +import me.aroxu.dawnshell.gradle.BfuRuntimeAssetsTask +import me.aroxu.dawnshell.gradle.registerBfuRuntime import java.util.Locale plugins { @@ -52,8 +54,11 @@ fun validateVersionName(versionName: String) { } } +val bfuNdkVersion = "29.0.14206865" + android { namespace = "me.aroxu.dawnshell" + ndkVersion = bfuNdkVersion compileSdk { version = release(37) { @@ -119,9 +124,18 @@ android { } +val bfuRuntimeAssets = registerBfuRuntime( + ndkDirectory = androidComponents.sdkComponents.ndkDirectory, + ndkVersion = bfuNdkVersion, + androidApi = providers.gradleProperty("minSdkVersion").map { it.toInt() }, + abiIds = providers.gradleProperty("dawnshellBfuAbis") + .orElse("armeabi-v7a,arm64-v8a,x86_64").get().split(","), +) + androidComponents { onVariants { variant -> variant.sources.assets?.addStaticSourceDirectory(generatedLicenseAssetsDir.get().asFile.path) + variant.sources.assets?.addGeneratedSourceDirectory(bfuRuntimeAssets, BfuRuntimeAssetsTask::outputDirectory) val apkName = "dawnshell-app_" + apkVersionTag.ifEmpty { "v${android.defaultConfig.versionName}+${variant.buildType}" } + ".apk" variant.outputs.forEach { (it as VariantOutputImpl).outputFileName.set(apkName) } } @@ -154,14 +168,7 @@ tasks.register("versionName") { } } -val bfuBootstrapAbis = listOf("armeabi-v7a", "arm64-v8a", "x86_64") -val bfuBootstrapExecutables = listOf( - "dawnshell-toolbox", "pkgdetails", "gpgv", "bfu-namespace-probe", - "dawnshell-fdguard", - "dawnshell-codec", "dawnshell-codec-worker") -val bfuBootstrapAssets = (bfuBootstrapAbis.flatMap { abi -> - bfuBootstrapExecutables.map { "bin/$abi/$it" } + "bin/$abi/runtime.properties" -} + listOf( +val bfuBootstrapAssets = listOf( "bootstrap/debootstrap_1.0.141.tgz", "bootstrap/debian-archive-keyring_2025.1_all.deb", "bootstrap/SOURCES.lock", @@ -179,7 +186,7 @@ val bfuBootstrapAssets = (bfuBootstrapAbis.flatMap { abi -> "dawnshell-codec-long-run.sh", "dawnshell-codec-concurrency-test.sh", "dawnshell-codec-error-test.sh", -)).map { file("src/main/assets/bfu/$it") } +).map { file("src/main/assets/bfu/$it") } val requiredLicenseFiles = listOf( "README.md", @@ -266,6 +273,41 @@ val verifyBfuBootstrapRuntime = tasks.register("verifyBfuBootstrapRuntime") { } } +val policyCheckTasks = fileTree(rootDir.resolve("scripts/tests/host")) { include("*.sh") }.files + .sortedBy { it.name } + .map { script -> + val taskName = "policyCheck" + script.nameWithoutExtension.removePrefix("test-") + .split("-").joinToString("") { it.replaceFirstChar(Char::uppercase) } + tasks.register(taskName) { + group = "verification" + description = "Runs scripts/tests/host/${script.name}." + workingDir = rootDir + commandLine("bash", script.path) + // Scripts that inspect the built binaries declare it by reading the generated assets directory. + if (script.readText().contains("DAWNSHELL_BFU_ASSETS_DIR")) dependsOn(bfuRuntimeAssets) + doFirst { + environment("DAWNSHELL_BFU_ASSETS_DIR", bfuRuntimeAssets.get().outputDirectory.get().asFile.resolve("bfu").path) + } + } + } + +val policyChecks = tasks.register("policyChecks") { + group = "verification" + description = "Runs every host-side policy and regression script in scripts/tests/host/." + dependsOn(policyCheckTasks) +} + +tasks.named("check") { + dependsOn(policyChecks) +} + +tasks.register("stageDebugApk") { + description = "Copies the debug APK to dist/ for scripts/install.sh and the device tests." + dependsOn("assembleDebug") + from(layout.buildDirectory.dir("outputs/apk/debug")) { include("*.apk") } + into(rootProject.layout.projectDirectory.dir("dist")) +} + tasks.named("preBuild") { dependsOn(verifyBfuBootstrapRuntime) dependsOn(verifyOpenSourceLicenses) diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe b/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe deleted file mode 100755 index d7d56d8..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec b/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec deleted file mode 100755 index bf2435f..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec-worker b/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec-worker deleted file mode 100755 index 1649b5e..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-codec-worker and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-fdguard b/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-fdguard deleted file mode 100755 index 181dd44..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-fdguard and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-toolbox b/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-toolbox deleted file mode 100755 index fd25769..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/dawnshell-toolbox and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/gpgv b/app/src/main/assets/bfu/bin/arm64-v8a/gpgv deleted file mode 100755 index 4ba907f..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/gpgv and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/pkgdetails b/app/src/main/assets/bfu/bin/arm64-v8a/pkgdetails deleted file mode 100755 index 5c4d570..0000000 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/pkgdetails and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/runtime.properties b/app/src/main/assets/bfu/bin/arm64-v8a/runtime.properties deleted file mode 100644 index e1c7b32..0000000 --- a/app/src/main/assets/bfu/bin/arm64-v8a/runtime.properties +++ /dev/null @@ -1,9 +0,0 @@ -android_abi=arm64-v8a -debian_architecture=arm64 -android_api=24 -busybox=1.38.0 -pkgdetails_base_installer=1.226 -gpgv=2.4.9 -dawnshell_codec_protocol=1 -dawnshell_codec_transport=inherited_memfd_eventfd -dawnshell_codec_worker=ndk_mediacodec diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe b/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe deleted file mode 100755 index 6933d0e..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec b/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec deleted file mode 100755 index 77c78fe..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec-worker b/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec-worker deleted file mode 100755 index a74e24e..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-codec-worker and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-fdguard b/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-fdguard deleted file mode 100755 index 1cdeca5..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-fdguard and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-toolbox b/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-toolbox deleted file mode 100755 index 0bc5ef3..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/dawnshell-toolbox and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/gpgv b/app/src/main/assets/bfu/bin/armeabi-v7a/gpgv deleted file mode 100755 index 79bb370..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/gpgv and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/pkgdetails b/app/src/main/assets/bfu/bin/armeabi-v7a/pkgdetails deleted file mode 100755 index c7e99ee..0000000 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/pkgdetails and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/runtime.properties b/app/src/main/assets/bfu/bin/armeabi-v7a/runtime.properties deleted file mode 100644 index 0af34b5..0000000 --- a/app/src/main/assets/bfu/bin/armeabi-v7a/runtime.properties +++ /dev/null @@ -1,9 +0,0 @@ -android_abi=armeabi-v7a -debian_architecture=armhf -android_api=24 -busybox=1.38.0 -pkgdetails_base_installer=1.226 -gpgv=2.4.9 -dawnshell_codec_protocol=1 -dawnshell_codec_transport=inherited_memfd_eventfd -dawnshell_codec_worker=ndk_mediacodec diff --git a/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe b/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe deleted file mode 100755 index 04496ca..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec b/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec deleted file mode 100755 index 3ed2a04..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec-worker b/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec-worker deleted file mode 100755 index f7cd73a..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/dawnshell-codec-worker and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/dawnshell-fdguard b/app/src/main/assets/bfu/bin/x86_64/dawnshell-fdguard deleted file mode 100755 index bc22004..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/dawnshell-fdguard and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/dawnshell-toolbox b/app/src/main/assets/bfu/bin/x86_64/dawnshell-toolbox deleted file mode 100755 index 0e6638b..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/dawnshell-toolbox and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/gpgv b/app/src/main/assets/bfu/bin/x86_64/gpgv deleted file mode 100755 index 779a398..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/gpgv and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/pkgdetails b/app/src/main/assets/bfu/bin/x86_64/pkgdetails deleted file mode 100755 index 96fdd79..0000000 Binary files a/app/src/main/assets/bfu/bin/x86_64/pkgdetails and /dev/null differ diff --git a/app/src/main/assets/bfu/bin/x86_64/runtime.properties b/app/src/main/assets/bfu/bin/x86_64/runtime.properties deleted file mode 100644 index f84f733..0000000 --- a/app/src/main/assets/bfu/bin/x86_64/runtime.properties +++ /dev/null @@ -1,9 +0,0 @@ -android_abi=x86_64 -debian_architecture=amd64 -android_api=24 -busybox=1.38.0 -pkgdetails_base_installer=1.226 -gpgv=2.4.9 -dawnshell_codec_protocol=1 -dawnshell_codec_transport=inherited_memfd_eventfd -dawnshell_codec_worker=ndk_mediacodec diff --git a/bfu-runtime/README.ko.md b/bfu-runtime/README.ko.md index 39ac036..40e6333 100644 --- a/bfu-runtime/README.ko.md +++ b/bfu-runtime/README.ko.md @@ -23,12 +23,13 @@ ABI는 CPU에 맞는 네이티브 실행 파일 규칙입니다. - 고정 소스와 SHA-256: `sources/SOURCES.lock` - Android용 패치: `patches/` - 최소 빌드 설정: `config/` -- 빌드 스크립트: `../scripts/build-bootstrap-runtime.sh` +- 빌드 태스크: `../buildSrc/` (`BfuRuntime.kt`가 등록) - 서드파티 라이선스: [THIRD_PARTY_NOTICES.ko.md](THIRD_PARTY_NOTICES.ko.md) 일반 사용자는 이 디렉터리의 파일을 휴대전화에 직접 복사할 필요가 없습니다. 앱이 현재 ABI에 맞는 검증된 결과만 DE 저장소에 배치합니다. 소스를 바꿨다면 전체 -`scripts/build-all.sh`를 실행해 세 ABI와 라이선스 검사를 함께 통과시키세요. +`./gradlew policyChecks :app:assembleDebug`를 실행해 세 ABI와 라이선스 검사를 함께 +통과시키세요. 바이너리는 빌드할 때 생성되며 커밋하지 않습니다. 실제 기기의 키, PID(Process Identifier), 로그와 `authorized_keys`는 이 저장소에 커밋하지 않습니다. 앱의 DE(Device Encrypted) 저장소 또는 검토된 Debian diff --git a/bfu-runtime/README.md b/bfu-runtime/README.md index feb9d15..64d80f1 100644 --- a/bfu-runtime/README.md +++ b/bfu-runtime/README.md @@ -16,12 +16,13 @@ installer preflight. - Pinned sources and hashes: `sources/SOURCES.lock` - Android patches: `patches/` - Minimal build configuration: `config/` -- Build script: `../scripts/build-bootstrap-runtime.sh` +- Build tasks: `../buildSrc/` (`BfuRuntime.kt` registers them) - Third-party licensing: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) Users do not copy these files to a phone manually. The app provisions only the verified output matching the current ABI into DE storage. After any source -change, run `scripts/build-all.sh` so all ABI and license checks run together. +change, run `./gradlew policyChecks :app:assembleDebug` so all ABI and license checks run +together. The binaries are generated at build time and are not committed. Never commit device keys, PIDs, logs, or `authorized_keys`. Runtime state belongs only in app Device Encrypted storage or the reviewed Debian rootfs. diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..cc02e63 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `kotlin-dsl` +} + +repositories { + gradlePluginPortal() +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuCompileTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuCompileTask.kt new file mode 100644 index 0000000..0cc0171 --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuCompileTask.kt @@ -0,0 +1,55 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction + +/** Compiles one DawnShell-owned C program with the pinned NDK clang, strips it and validates the ELF. */ +@CacheableTask +abstract class BfuCompileTask : BfuNativeTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sources: ConfigurableFileCollection + + @get:InputFiles + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val headers: ConfigurableFileCollection + + @get:Input + abstract val compilerArguments: ListProperty + + @get:Input + abstract val linkerArguments: ListProperty + + @get:Input + abstract val elfKind: Property + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + @TaskAction + fun compile() { + val tools = ndk + val output = outputFile.get().asFile + output.parentFile.mkdirs() + runner.run( + null, + *tools.clangArguments.toTypedArray(), + *compilerArguments.get().toTypedArray(), + *sources.files.map { it.path }.toTypedArray(), + *linkerArguments.get().toTypedArray(), + "-o", output.path, + ) + runner.run(null, tools.strip.path, "--strip-unneeded", output.path) + makePrivateExecutable(output) + ElfValidator(runner, tools).validate(output, elfKind.get()) + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuNativeTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuNativeTask.kt new file mode 100644 index 0000000..2c1230b --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuNativeTask.kt @@ -0,0 +1,61 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Internal +import org.gradle.process.ExecOperations +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.nio.file.attribute.PosixFilePermissions +import javax.inject.Inject + +abstract class BfuNativeTask : DefaultTask() { + @get:Inject + abstract val execOperations: ExecOperations + + @get:Internal + abstract val ndkDirectory: DirectoryProperty + + @get:Input + abstract val ndkVersion: Property + + @get:Input + abstract val abiId: Property + + @get:Input + abstract val androidApi: Property + + @get:Input + abstract val sourceDateEpoch: Property + + @get:Internal + protected val abi get() = Abi.of(abiId.get()) + + @get:Internal + protected val ndk get() = NdkTools(ndkDirectory.get().asFile, abi, androidApi.get()) + + @get:Internal + protected val runner + get() = CommandRunner( + execOperations, + mapOf("LC_ALL" to "C", "TZ" to "UTC", "SOURCE_DATE_EPOCH" to sourceDateEpoch.get()), + ) + + protected fun cleanWorkDirectory(): File = temporaryDir.resolve("work").apply { + deleteRecursively() + mkdirs() + } + + protected fun installExecutable(source: File, target: File) { + target.parentFile.mkdirs() + Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) + makePrivateExecutable(target) + } + + protected fun makePrivateExecutable(file: File) { + if (!isWindowsHost) Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("rwx------")) + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntime.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntime.kt new file mode 100644 index 0000000..0bc8604 --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntime.kt @@ -0,0 +1,124 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.GradleException +import org.gradle.api.Project +import org.gradle.api.file.Directory +import org.gradle.api.provider.Provider +import org.gradle.api.tasks.TaskProvider + +private const val DEFAULT_SOURCE_DATE_EPOCH = "1758672000" + +private val COMPILE_FLAGS = listOf("-std=c17", "-Os", "-fPIE", "-fstack-protector-strong", "-Wall", "-Wextra", "-Werror", "-Wformat=2") +private val LINK_FLAGS = listOf("-Wl,-pie", "-Wl,-z,relro,-z,now", "-Wl,--gc-sections") + +/** + * Registers the source builds of every bundled native program for each ABI and returns the task that + * assembles them into generated assets. + */ +fun Project.registerBfuRuntime( + ndkDirectory: Provider, + ndkVersion: String, + androidApi: Provider, + abiIds: List, +): TaskProvider { + val runtimeDir = rootProject.layout.projectDirectory.dir("bfu-runtime") + val sourcesDir = runtimeDir.dir("sources") + val cppDir = layout.projectDirectory.dir("src/main/cpp") + val binariesDir = layout.buildDirectory.dir("bfuRuntime/bin") + val sourceDateEpoch = providers.environmentVariable("SOURCE_DATE_EPOCH").orElse(DEFAULT_SOURCE_DATE_EPOCH) + val jobs = providers.environmentVariable("DAWNSHELL_BUILD_JOBS") + .map { value -> + value.toIntOrNull()?.takeIf { it > 0 } + ?: throw GradleException("DAWNSHELL_BUILD_JOBS must be a positive integer: $value") + } + .orElse(Runtime.getRuntime().availableProcessors()) + + val extractPkgdetails = tasks.register("extractPkgdetailsSource", ExtractArchiveMemberTask::class.java) { + archive.set(sourcesDir.file("base-installer_1.226.tar.xz")) + sourceLock.set(sourcesDir.file("SOURCES.lock")) + member.set("base-installer/pkgdetails.c") + outputFile.set(layout.buildDirectory.file("bfuRuntime/pkgdetails.c")) + } + + val abis = abiIds.map { Abi.of(it) } + val allTasks = abis.flatMap { abi -> + fun BfuNativeTask.configureCommon(program: String) { + group = "bfu runtime" + description = "Builds $program for ${abi.id}." + this.ndkDirectory.set(ndkDirectory) + this.ndkVersion.set(ndkVersion) + abiId.set(abi.id) + this.androidApi.set(androidApi) + this.sourceDateEpoch.set(sourceDateEpoch) + } + + fun compile( + program: String, + sources: List, + compilerArguments: List, + linkerArguments: List, + kind: ElfKind, + ) = tasks.register("buildBfu${abi.taskSuffix}${program.split('-').joinToString("") { it.replaceFirstChar(Char::uppercase) }}", BfuCompileTask::class.java) { + configureCommon(program) + this.sources.from(sources) + headers.from(fileTree(cppDir)) + this.compilerArguments.set(compilerArguments) + this.linkerArguments.set(linkerArguments) + elfKind.set(kind) + outputFile.set(binariesDir.map { it.file("${abi.id}/$program") }) + } + + fun cpp(name: String) = cppDir.file(name) + val hardened = COMPILE_FLAGS + LINK_FLAGS + + listOf( + tasks.register("buildBfu${abi.taskSuffix}Busybox", BusyBoxTask::class.java) { + configureCommon("dawnshell-toolbox") + sourceArchive.set(sourcesDir.file("busybox-1.38.0.tar.bz2")) + sourceLock.set(sourcesDir.file("SOURCES.lock")) + patchFile.set(runtimeDir.file("patches/busybox/0001-android-mount-without-addmntent.patch")) + configFragment.set(runtimeDir.file("config/busybox-bootstrap.config")) + this.jobs.set(jobs) + outputFile.set(binariesDir.map { it.file("${abi.id}/dawnshell-toolbox") }) + }, + tasks.register("buildBfu${abi.taskSuffix}Gpgv", GpgvTask::class.java) { + configureCommon("gpgv") + sourceArchives.from( + listOf( + "libgpg-error-1.59.tar.bz2", "libgcrypt-1.12.1.tar.bz2", "libassuan-3.0.2.tar.bz2", + "libksba-1.6.8.tar.bz2", "npth-1.8.tar.bz2", "gnupg-2.4.9.tar.bz2", + ).map { sourcesDir.file(it) }, + ) + sourceLock.set(sourcesDir.file("SOURCES.lock")) + libgpgErrorPatch.set(runtimeDir.file("patches/libgpg-error/0001-skip-deprecated-config-self-test.patch")) + this.jobs.set(jobs) + outputFile.set(binariesDir.map { it.file("${abi.id}/gpgv") }) + }, + compile( + "pkgdetails", listOf(extractPkgdetails.map { it.outputFile }), + listOf("-std=c17", "-Os", "-fPIE", "-fstack-protector-strong", "-Wall", "-Wextra", "-Wformat=2", "-Wno-format-nonliteral", "-Wl,-pie,-z,relro,-z,now"), + emptyList(), ElfKind.DYNAMIC, + ), + compile("bfu-namespace-probe", listOf(cpp("bfu_namespace_probe.c")), hardened, emptyList(), ElfKind.DYNAMIC), + compile("dawnshell-fdguard", listOf(cpp("dawnshell_fdguard.c")), hardened, emptyList(), ElfKind.DYNAMIC), + compile( + "dawnshell-codec", listOf(cpp("dawnshell_codec_client.c")), + listOf("-std=c17", "-Os", "-static", "-fPIE", "-fstack-protector-strong", "-Wall", "-Wextra", "-Werror", "-Wformat=2", "-Wl,-z,relro,-z,now", "-Wl,--gc-sections"), + emptyList(), ElfKind.STATIC, + ), + compile( + "dawnshell-codec-worker", listOf(cpp("dawnshell_codec_worker.c"), cpp("dawnshell_codec_ndk.c")), + hardened, listOf("-lmediandk", "-landroid", "-ldl"), ElfKind.CODEC_WORKER, + ), + ) + } + + return tasks.register("assembleBfuRuntimeAssets", BfuRuntimeAssetsTask::class.java) { + group = "bfu runtime" + description = "Builds every bundled native program for all configured ABIs and stages them as assets." + dependsOn(allTasks) + binariesDirectory.set(binariesDir) + this.abiIds.set(abiIds) + this.androidApi.set(androidApi) + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntimeAssetsTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntimeAssetsTask.kt new file mode 100644 index 0000000..00fb887 --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntimeAssetsTask.kt @@ -0,0 +1,51 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputDirectory +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction + +/** Lays the per-ABI binaries out as assets/bfu/bin// and writes each ABI's runtime.properties. */ +abstract class BfuRuntimeAssetsTask : DefaultTask() { + @get:InputDirectory + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val binariesDirectory: DirectoryProperty + + @get:Input + abstract val abiIds: ListProperty + + @get:Input + abstract val androidApi: Property + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun assemble() { + val root = outputDirectory.get().asFile + root.deleteRecursively() + abiIds.get().map { Abi.of(it) }.forEach { abi -> + val target = root.resolve("bfu/bin/${abi.id}") + binariesDirectory.get().asFile.resolve(abi.id).copyRecursively(target) + target.resolve("runtime.properties").writeText( + listOf( + "android_abi=${abi.id}", + "debian_architecture=${abi.debianArch}", + "android_api=${androidApi.get()}", + "busybox=1.38.0", + "pkgdetails_base_installer=1.226", + "gpgv=2.4.9", + "dawnshell_codec_protocol=1", + "dawnshell_codec_transport=inherited_memfd_eventfd", + "dawnshell_codec_worker=ndk_mediacodec", + ).joinToString("\n", postfix = "\n"), + ) + } + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BusyBoxTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BusyBoxTask.kt new file mode 100644 index 0000000..47464a3 --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BusyBoxTask.kt @@ -0,0 +1,88 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.GradleException +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import java.io.ByteArrayInputStream + +/** Cross-builds the BusyBox toolbox from the pinned source, Android patch and config fragment. */ +@CacheableTask +abstract class BusyBoxTask : BfuNativeTask() { + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sourceArchive: RegularFileProperty + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sourceLock: RegularFileProperty + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val patchFile: RegularFileProperty + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val configFragment: RegularFileProperty + + @get:Internal + abstract val jobs: Property + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + private val requiredSymbols = listOf( + "BUSYBOX", "FEATURE_INSTALLER", "FEATURE_MD5_SHA1_SUM_CHECK", "FEATURE_STAT_FORMAT", "ASH", "AWK", + "CHROOT", "DPKG_DEB", "MOUNT", "SED", "SHA256SUM", "STAT", "TAR", "UNSHARE", "WGET", "ZCAT", "XZCAT", + ) + + @TaskAction + fun build() { + val archive = sourceArchive.get().asFile + SourceLock.verify(sourceLock.get().asFile, archive) + val tools = ndk + val work = cleanWorkDirectory() + runner.run(work, "tar", "-xf", archive.path, "-C", work.path) + val source = work.resolve(archive.name.removeSuffix(".tar.bz2")) + runner.run(source, "patch", "-p1", "-i", patchFile.get().asFile.path) + mergeConfig(source) + + runner.run( + source, "make", "-j${jobs.get()}", + "CC=${tools.cc}", "HOSTCC=gcc", + "AR=${tools.ar}", "NM=${tools.nm}", "STRIP=${tools.strip}", "OBJCOPY=${tools.objcopy}", + "EXTRA_CFLAGS=-Wno-ignored-optimization-argument -Wno-unused-command-line-argument", + ) + runner.run(source, tools.strip.path, "--strip-unneeded", "busybox") + installExecutable(source.resolve("busybox"), outputFile.get().asFile) + + val config = source.resolve(".config").readLines() + requiredSymbols.forEach { symbol -> + if ("CONFIG_$symbol=y" !in config) { + throw GradleException("BusyBox output is missing required config symbol: CONFIG_$symbol=y") + } + } + ElfValidator(runner, tools).validate(outputFile.get().asFile, ElfKind.DYNAMIC) + } + + private fun mergeConfig(source: java.io.File) { + runner.run(source, "make", "allnoconfig") + val configFile = source.resolve(".config") + val lines = configFile.readLines().toMutableList() + configFragment.get().asFile.readLines() + .filter { it.startsWith("CONFIG_") && it.endsWith("=y") } + .forEach { setting -> + val unset = lines.indexOf("# ${setting.substringBefore('=')} is not set") + if (unset >= 0) lines[unset] = setting else if (setting !in lines) lines += setting + } + configFile.writeText(lines.joinToString("\n", postfix = "\n")) + // oldconfig asks about every symbol the fragment did not decide; answer with the defaults. + runner.run(source, "make", "oldconfig", stdin = ByteArrayInputStream("\n".repeat(1 shl 16).toByteArray())) + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/ExtractArchiveMemberTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/ExtractArchiveMemberTask.kt new file mode 100644 index 0000000..3d9a75e --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/ExtractArchiveMemberTask.kt @@ -0,0 +1,46 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.process.ExecOperations +import javax.inject.Inject + +/** Extracts one verified file from a pinned upstream archive (Gradle's tarTree cannot read xz). */ +@CacheableTask +abstract class ExtractArchiveMemberTask : DefaultTask() { + @get:Inject + abstract val execOperations: ExecOperations + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val archive: RegularFileProperty + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sourceLock: RegularFileProperty + + @get:Input + abstract val member: Property + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + @TaskAction + fun extract() { + SourceLock.verify(sourceLock.get().asFile, archive.get().asFile) + outputFile.get().asFile.outputStream().use { output -> + execOperations.exec { + commandLine("tar", "-xOf", archive.get().asFile.path, member.get()) + standardOutput = output + } + } + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/GpgvTask.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/GpgvTask.kt new file mode 100644 index 0000000..e3e4aaf --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/GpgvTask.kt @@ -0,0 +1,146 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import java.io.File + +/** Cross-builds gpgv and its static library chain (libgpg-error, libgcrypt, libassuan, libksba, npth). */ +@CacheableTask +abstract class GpgvTask : BfuNativeTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sourceArchives: ConfigurableFileCollection + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sourceLock: RegularFileProperty + + @get:InputFile + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val libgpgErrorPatch: RegularFileProperty + + @get:Internal + abstract val jobs: Property + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + private lateinit var work: File + private lateinit var prefix: File + private lateinit var toolEnvironment: Map + + @TaskAction + fun build() { + SourceLock.verify(sourceLock.get().asFile, *sourceArchives.files.toTypedArray()) + val tools = ndk + work = cleanWorkDirectory() + prefix = work.resolve("prefix").apply { mkdirs() } + sourceArchives.files.forEach { runner.run(work, "tar", "-xf", it.path, "-C", work.path) } + runner.run(sourceDir("libgpg-error"), "patch", "-p1", "-i", libgpgErrorPatch.get().asFile.path) + + toolEnvironment = mapOf( + "CC" to tools.cc, "AR" to tools.ar.path, "NM" to tools.nm.path, + "RANLIB" to tools.ranlib.path, "STRIP" to tools.strip.path, + "CPPFLAGS" to "-I$prefix/include", + "CFLAGS" to "-Os -fPIC -fstack-protector-strong", + "LDFLAGS" to "-L$prefix/lib -Wl,-z,relro,-z,now", + "PKG_CONFIG_LIBDIR" to "$prefix/lib/pkgconfig", + "PKG_CONFIG_PATH" to "$prefix/lib/pkgconfig", + "PATH" to "$prefix/bin${File.pathSeparator}${System.getenv("PATH")}", + ) + + configureStaticLibrary( + "libgpg-error", "--disable-nls", "--disable-doc", "--disable-tests", "--disable-install-gpg-error-config", + ) + configureStaticLibrary("libgcrypt", "--disable-doc", "--disable-asm", "--with-libgpg-error-prefix=$prefix") + configureStaticLibrary("libassuan", "--disable-doc", "--with-libgpg-error-prefix=$prefix") + configureStaticLibrary("libksba", "--disable-doc", "--with-libgpg-error-prefix=$prefix") + buildNpth() + // gpgrt-config recursively invokes itself under MSYS path translation. The legacy, generated + // config scripts are sufficient for this cross-build. + prefix.resolve("bin/gpgrt-config").delete() + val gpgv = buildGnupg(tools) + + installExecutable(gpgv, outputFile.get().asFile) + ElfValidator(runner, tools).validate(outputFile.get().asFile, ElfKind.DYNAMIC) + } + + private fun sourceDir(name: String) = work.listFiles { file -> file.name.startsWith("$name-") }!!.single() + + private fun buildTriplet(source: File) = runner.run(source, source.resolve("build-aux/config.guess").path).trim() + + private fun hostConfigureArguments(source: File) = + listOf("--host=${abi.gnuHost}", "--build=${buildTriplet(source)}") + + private fun configureStaticLibrary(name: String, vararg arguments: String) { + val source = sourceDir(name) + // Keep runtime directory macros deterministic under MSYS path translation. + val msys = if (isWindowsHost) mapOf("MSYS2_ARG_CONV_EXCL" to "-DLOCALEDIR;-DSYSCONFDIR;-DLOCALSTATEDIR;-DDATADIR") else emptyMap() + val environment = toolEnvironment + msys + runner.run( + source, "./configure", *hostConfigureArguments(source).toTypedArray(), + "--prefix=$prefix", "--enable-static", "--disable-shared", *arguments, environment = environment, + ) + // Runtime directory constants must not contain the temporary build prefix. Override them only while + // compiling; make install keeps using the private staging prefix and never writes to host /system. + runner.run( + source, "make", "-j${jobs.get()}", + "localedir=/system/share/locale", "sysconfdir=/system/etc", + "localstatedir=/system/var", "datadir=/system/share", + environment = environment, + ) + runner.run(source, "make", "install", environment = environment) + } + + private fun buildNpth() { + val source = sourceDir("npth") + val environment = toolEnvironment + ("ac_cv_search_pthread_cancel" to "none required") + runner.run( + source, "./configure", *hostConfigureArguments(source).toTypedArray(), + "--prefix=$prefix", "--enable-static", "--disable-shared", "--disable-tests", + environment = environment, + ) + runner.run(source, "make", "-j${jobs.get()}", environment = toolEnvironment) + runner.run(source, "make", "install", environment = toolEnvironment) + } + + private fun buildGnupg(tools: NdkTools): File { + val source = sourceDir("gnupg") + // Preserve the fixed /system paths embedded by GnuPG instead of letting MSYS rewrite -D arguments. + val msys = if (isWindowsHost) mapOf("MSYS2_ARG_CONV_EXCL" to "-DGNUPG_;-DLOCALEDIR") else emptyMap() + val environment = toolEnvironment + msys + mapOf( + "CFLAGS" to "-Os -fPIE -fstack-protector-strong", + "GPG_ERROR_CONFIG" to sourceDir("libgpg-error").resolve("src/gpg-error-config-old").path, + "LIBGCRYPT_CONFIG" to "$prefix/bin/libgcrypt-config", + "LIBASSUAN_CONFIG" to "$prefix/bin/libassuan-config", + "KSBA_CONFIG" to "$prefix/bin/ksba-config", + "NPTH_CONFIG" to sourceDir("npth").resolve("npth-config").path, + ) + val disabled = listOf( + "nls", "doc", "tests", "gpgsm", "scdaemon", "dirmngr", "keyboxd", "tpm2d", "gpgtar", "wks-tools", + "ccid-driver", "ldap", "zip", "bzip2", "sqlite", + ).map { "--disable-$it" } + runner.run( + source, "./configure", *hostConfigureArguments(source).toTypedArray(), + "--prefix=/system", *disabled.toTypedArray(), + "--without-libiconv-prefix", "--without-libintl-prefix", + "--with-libgpg-error-prefix=$prefix", "--with-libgcrypt-prefix=$prefix", "--with-libassuan-prefix=$prefix", + environment = environment, + ) + listOf("common", "regexp", "kbx").forEach { + runner.run(source, "make", "-j${jobs.get()}", "-C", it, environment = environment) + } + runner.run(source, "make", "-j${jobs.get()}", "-C", "g10", "gpgv", environment = environment) + runner.run(source, tools.strip.path, "--strip-unneeded", "g10/gpgv") + return source.resolve("g10/gpgv") + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/SourceLock.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/SourceLock.kt new file mode 100644 index 0000000..5969f92 --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/SourceLock.kt @@ -0,0 +1,27 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.GradleException +import java.io.File +import java.security.MessageDigest + +object SourceLock { + /** Checks archives against the SHA-256 recorded in bfu-runtime/sources/SOURCES.lock. */ + fun verify(lock: File, vararg archives: File) { + val hashes = lock.readLines().map { it.trim() }.filter { it.isNotEmpty() && !it.startsWith("#") } + .map { it.split(Regex("\\s+")) }.associate { it[1] to it[0] } + archives.forEach { archive -> + val expected = hashes[archive.name] ?: throw GradleException("${archive.name} is not listed in ${lock.name}") + val digest = MessageDigest.getInstance("SHA-256") + archive.inputStream().use { input -> + val buffer = ByteArray(1 shl 16) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + val actual = digest.digest().joinToString("") { "%02x".format(it) } + if (actual != expected) throw GradleException("SHA-256 mismatch for ${archive.name}: $actual != $expected") + } + } +} diff --git a/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/Toolchain.kt b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/Toolchain.kt new file mode 100644 index 0000000..7f7562b --- /dev/null +++ b/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/Toolchain.kt @@ -0,0 +1,139 @@ +package me.aroxu.dawnshell.gradle + +import org.gradle.api.GradleException +import org.gradle.process.ExecOperations +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream + +enum class Abi( + val id: String, + private val clangTriple: String, + val gnuHost: String, + val debianArch: String, + val machine: String, + val interpreter: String, +) { + ARMEABI_V7A("armeabi-v7a", "armv7a-linux-android", "armv7a-linux-androideabi", "armhf", "ARM", "/system/bin/linker"), + ARM64_V8A("arm64-v8a", "aarch64-linux-android", "aarch64-linux-androideabi", "arm64", "AArch64", "/system/bin/linker64"), + X86_64( + "x86_64", "x86_64-linux-android", "x86_64-linux-androideabi", "amd64", + "Advanced Micro Devices X86-64", "/system/bin/linker64", + ); + + fun clangTarget(api: Int) = "$clangTriple$api" + + val taskSuffix get() = id.split('-', '_').joinToString("") { it.replaceFirstChar(Char::uppercase) } + + companion object { + fun of(id: String) = entries.firstOrNull { it.id == id } ?: throw GradleException("Unsupported ABI: $id") + } +} + +val isWindowsHost = System.getProperty("os.name").startsWith("Windows") + +class NdkTools(ndkDir: File, val abi: Abi, val api: Int) { + private val binDir = ndkDir.resolve("toolchains/llvm/prebuilt/${hostTag()}/bin") + + val clang = tool("clang") + val ar = tool("llvm-ar") + val nm = tool("llvm-nm") + val ranlib = tool("llvm-ranlib") + val strip = tool("llvm-strip") + val objcopy = tool("llvm-objcopy") + val readelf = tool("llvm-readelf") + val strings = tool("llvm-strings") + + val clangArguments = listOf(clang.path, "--target=${abi.clangTarget(api)}") + val cc get() = clangArguments.joinToString(" ") + + private fun hostTag(): String { + val os = System.getProperty("os.name") + return when { + os.startsWith("Linux") -> "linux-x86_64" + os.startsWith("Mac") -> "darwin-x86_64" + os.startsWith("Windows") -> "windows-x86_64" + else -> throw GradleException("Unsupported build host: $os") + } + } + + private fun tool(name: String) = listOf(name, "$name.exe", "$name.cmd").map { binDir.resolve(it) } + .firstOrNull { it.isFile } ?: throw GradleException("Missing NDK tool: $name in $binDir") +} + +class CommandRunner(private val exec: ExecOperations, private val baseEnvironment: Map) { + fun run( + workDir: File?, + vararg command: String, + environment: Map = emptyMap(), + stdin: InputStream? = null, + ): String { + val output = ByteArrayOutputStream() + val result = exec.exec { + commandLine(*command) + workDir?.let { workingDir = it } + environment(baseEnvironment + environment) + stdin?.let { standardInput = it } + standardOutput = output + errorOutput = output + isIgnoreExitValue = true + } + val text = output.toString(Charsets.UTF_8) + if (result.exitValue != 0) { + throw GradleException( + "Command failed with exit code ${result.exitValue}: ${command.joinToString(" ")}\n" + + text.lines().takeLast(200).joinToString("\n"), + ) + } + return text + } +} + +enum class ElfKind { DYNAMIC, STATIC, CODEC_WORKER } + +/** Mirrors the former validate_elf, validate_static_elf and validate_codec_worker_elf shell checks. */ +class ElfValidator(private val runner: CommandRunner, private val ndk: NdkTools) { + private val fixedDataPath = Regex("/data/(data|user|user_de)/[^/ ]+") + private val hostPath = Regex("[A-Za-z]:/Users/") + private val workDirectory = Regex("dawnshell-bootstrap-runtime") + + fun validate(binary: File, kind: ElfKind) { + val header = runner.run(null, ndk.readelf.path, "-h", binary.path) + val program = runner.run(null, ndk.readelf.path, "-l", binary.path) + val dynamic = runner.run(null, ndk.readelf.path, "-d", binary.path) + val libraries = Regex("""Shared library: \[([^\]]*)]""").findAll(dynamic).map { it.groupValues[1] }.toSet() + val machine = Regex("Machine:\\s+" + Regex.escape(ndk.abi.machine)) + + require(machine.containsMatchIn(header), binary) { "unexpected machine type" } + when (kind) { + ElfKind.STATIC -> { + require(Regex("Type:\\s+EXEC").containsMatchIn(header), binary) { "not a static EXEC" } + require("Requesting program interpreter" !in program, binary) { "unexpected program interpreter" } + require(libraries.isEmpty(), binary) { "unexpected shared dependencies $libraries" } + } + ElfKind.DYNAMIC, ElfKind.CODEC_WORKER -> { + require(Regex("Type:\\s+DYN").containsMatchIn(header), binary) { "not a PIE DYN" } + require(ndk.abi.interpreter in program, binary) { "missing interpreter ${ndk.abi.interpreter}" } + val allowed = if (kind == ElfKind.DYNAMIC) { + setOf("libc.so", "libdl.so") + } else { + setOf("libandroid.so", "libc.so", "libdl.so", "libmediandk.so") + } + require(if (kind == ElfKind.DYNAMIC) allowed.containsAll(libraries) else libraries == allowed, binary) { + "unexpected Android native dependencies $libraries" + } + } + } + + val strings = runner.run(null, ndk.strings.path, binary.path).lines() + require(strings.none { fixedDataPath.containsMatchIn(it) }, binary) { "fixed Android data path embedded" } + require(strings.none { hostPath.containsMatchIn(it) }, binary) { "host build path embedded" } + if (kind == ElfKind.DYNAMIC) { + require(strings.none { workDirectory.containsMatchIn(it) }, binary) { "non-reproducible build path embedded" } + } + } + + private fun require(condition: Boolean, binary: File, message: () -> String) { + if (!condition) throw GradleException("ELF validation failed for ${binary.name}: ${message()}") + } +} diff --git a/docs/building.ko.md b/docs/building.ko.md index 14c04f2..d301b61 100644 --- a/docs/building.ko.md +++ b/docs/building.ko.md @@ -35,36 +35,40 @@ BusyBox, `pkgdetails`, `gpgv`, debootstrap 자료와 namespace 런처는 고정 ```sh export JAVA_HOME=/path/to/jdk17 export ANDROID_HOME=/path/to/android-sdk -export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865" ``` -NDK 변수를 생략하면 빌드 스크립트가 위 SDK 경로의 고정 버전을 사용합니다. +SDK에 NDK `29.0.14206865`를 설치하세요(`sdkmanager "ndk;29.0.14206865"`). Gradle이 +`ndkVersion`으로 정확히 그 버전을 선택하므로 `ANDROID_NDK_HOME`은 필요 없습니다. ## 전체 빌드 ```sh -./scripts/build-all.sh +./gradlew clean policyChecks :app:lintDebug :app:testDebugUnitTest :app:stageDebugApk ``` 이 명령은 다음 작업을 수행합니다. -1. 고정 소스에서 세 ABI의 부트스트랩 런타임을 빌드합니다. -2. Docker, USB, 코덱, FFmpeg, 재부팅 격리와 lifecycle 정책 검사를 실행합니다. +1. `buildSrc/`의 Gradle 태스크가 고정 소스에서 세 ABI의 부트스트랩 런타임(BusyBox, + `pkgdetails`, `gpgv`, namespace 런처, `dawnshell-fdguard`, 코덱 client·worker)을 + 빌드하고 모든 ELF를 검증해 생성 asset으로 포함합니다. 바이너리는 커밋하지 + 않습니다. +2. Docker, USB, 코덱, FFmpeg, 재부팅 격리 정책 검사를 실행합니다. 3. Android unit test와 lint를 실행합니다. 4. debug APK를 만들고 `dist/`에 복사합니다. -기본 병렬 빌드는 `make -j"$(nproc)"`입니다. 메모리가 부족하거나 다른 작업과 -병행한다면 작업 수를 제한합니다. +네이티브 소스가 바뀌지 않았다면 Gradle의 up-to-date 검사와 빌드 캐시로 결과를 +재사용합니다. 기본 병렬 빌드는 `make -j"$(nproc)"`입니다. 메모리가 부족하거나 다른 +작업과 병행한다면 작업 수를 제한합니다. ```sh -DAWNSHELL_BUILD_JOBS=4 ./scripts/build-all.sh +DAWNSHELL_BUILD_JOBS=4 ./gradlew assembleBfuRuntimeAssets ``` -이미 같은 소스에서 런타임을 빌드했고 Android 코드만 빠르게 확인하려면 다음을 -사용할 수 있습니다. Release 검증에는 사용하지 마세요. +하나의 ABI만 빠르게 확인하려면 다음을 사용할 수 있습니다. Release 검증에는 사용하지 +마세요. ```sh -DAWNSHELL_SKIP_BOOTSTRAP_SOURCE_BUILD=1 ./scripts/build-all.sh +./gradlew -PdawnshellBfuAbis=arm64-v8a :app:assembleDebug ``` 기본 출력 파일 이름은 다음 형식입니다. @@ -75,23 +79,22 @@ dist/dawnshell-app_v+debug.apk ## 자주 쓰는 개별 검사 +`./gradlew policyChecks`가 `scripts/tests/host/*.sh`를 모두 실행하며 `./gradlew check`에도 +포함됩니다. Gradle이 디렉터리로 스크립트를 찾으므로 이 디렉터리에 새 스크립트를 두면 +빌드 파일을 고치지 않아도 됩니다. `DAWNSHELL_BFU_ASSETS_DIR`를 읽는(빌드된 바이너리를 +검사하는) 스크립트는 네이티브 런타임 빌드 뒤에 자동으로 실행됩니다. 각 스크립트를 +단독으로 실행할 수도 있으며, 먼저 `./gradlew assembleBfuRuntimeAssets`로 바이너리를 +빌드하세요. + ```sh -./scripts/test-release-compliance.sh -./scripts/test-compatibility-policy.sh -./scripts/test-docker-ipc-wrapper.sh -./scripts/test-host-usb-policy.sh -./scripts/test-hardware-codec-bridge.sh -./scripts/test-ffmpeg-bridge-plan.sh -./scripts/test-live-codec-pipeline.sh -./scripts/test-gpu-status-tool.sh -./scripts/test-native-output.sh -./scripts/test-host-reboot-isolation.sh -./scripts/test-rootfs-path-resolution.sh -./scripts/test-lifecycle-control-policy.sh -./scripts/test-documentation.sh +./gradlew policyChecks +./scripts/tests/host/test-release-compliance.sh ./gradlew :app:lintDebug :app:testDebugUnitTest :app:assembleDebug ``` +실기기와 `adb`가 필요한 스크립트는 `scripts/tests/device/`에 있으며 Gradle이 실행하지 +않습니다. + 실기기 없이 통과하는 검사는 빌드·패키징·정적 정책을 확인합니다. BFU broadcast, Magisk/SELinux, 실제 vendor MediaCodec과 네트워크 복구는 [실기기 테스트](testing.ko.md)가 별도로 필요합니다. diff --git a/docs/building.md b/docs/building.md index 4f34dd8..0e8ee26 100644 --- a/docs/building.md +++ b/docs/building.md @@ -24,9 +24,12 @@ cd dawnshell export JAVA_HOME=/path/to/jdk17 export ANDROID_HOME=/path/to/android-sdk -export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865" ``` +Install NDK `29.0.14206865` in the SDK (`sdkmanager "ndk;29.0.14206865"`). Gradle +selects exactly that version through `ndkVersion`, so `ANDROID_NDK_HOME` is not +needed. + DawnShell does not depend on separate Termux repositories. BusyBox, `pkgdetails`, `gpgv`, debootstrap material, and the namespace launcher are built from pinned source and patches in this repository. @@ -34,23 +37,28 @@ from pinned source and patches in this repository. ## Full build ```sh -./scripts/build-all.sh +./gradlew clean policyChecks :app:lintDebug :app:testDebugUnitTest :app:stageDebugApk ``` -The script builds `armeabi-v7a`, `arm64-v8a`, and `x86_64` bootstrap runtimes, -runs policy and bridge regressions, executes Android lint and unit tests, and -copies the debug APK to `dist/`. +Gradle builds the `armeabi-v7a`, `arm64-v8a`, and `x86_64` bootstrap runtimes +(BusyBox, `pkgdetails`, `gpgv`, the namespace launcher, `dawnshell-fdguard`, and +the codec client and worker) from the pinned sources with the tasks in +`buildSrc/`, validates every ELF, and packages the result as generated assets. +The binaries are not committed. Gradle then runs the policy and bridge +regressions, Android lint and unit tests, and copies the debug APK to `dist/`. +Unchanged native sources are reused from Gradle's up-to-date checks and build +cache. Compilation defaults to `make -j"$(nproc)"`. Limit parallelism when necessary: ```sh -DAWNSHELL_BUILD_JOBS=4 ./scripts/build-all.sh +DAWNSHELL_BUILD_JOBS=4 ./gradlew assembleBfuRuntimeAssets ``` -For a local Android-only iteration after building identical native sources: +For a local iteration on one ABI: ```sh -DAWNSHELL_SKIP_BOOTSTRAP_SOURCE_BUILD=1 ./scripts/build-all.sh +./gradlew -PdawnshellBfuAbis=arm64-v8a :app:assembleDebug ``` Do not use that shortcut as release evidence. The normal output is: @@ -61,23 +69,22 @@ dist/dawnshell-app_v+debug.apk ## Individual checks +`./gradlew policyChecks` runs every `scripts/tests/host/*.sh` script (also part of +`./gradlew check`). Gradle discovers them by directory, so a new script there needs +no build change; scripts that read `DAWNSHELL_BFU_ASSETS_DIR` (they inspect the +built binaries) automatically run after the native runtime build. Each script can +also be run on its own; build the binaries first with +`./gradlew assembleBfuRuntimeAssets`. + ```sh -./scripts/test-release-compliance.sh -./scripts/test-compatibility-policy.sh -./scripts/test-docker-ipc-wrapper.sh -./scripts/test-host-usb-policy.sh -./scripts/test-hardware-codec-bridge.sh -./scripts/test-ffmpeg-bridge-plan.sh -./scripts/test-live-codec-pipeline.sh -./scripts/test-gpu-status-tool.sh -./scripts/test-native-output.sh -./scripts/test-host-reboot-isolation.sh -./scripts/test-rootfs-path-resolution.sh -./scripts/test-lifecycle-control-policy.sh -./scripts/test-documentation.sh +./gradlew policyChecks +./scripts/tests/host/test-release-compliance.sh ./gradlew :app:lintDebug :app:testDebugUnitTest :app:assembleDebug ``` +Scripts that need a phone and `adb` live in `scripts/tests/device/` and are never +run by Gradle. + These prove host-build and static policy properties. Direct Boot broadcasts, Magisk/SELinux behavior, vendor MediaCodec, and network recovery still require the [physical-device test plan](testing.md). diff --git a/docs/testing.ko.md b/docs/testing.ko.md index 50f35cb..ce5cfaa 100644 --- a/docs/testing.ko.md +++ b/docs/testing.ko.md @@ -143,7 +143,7 @@ USB 저장장치는 Android와 Debian 중 한쪽에서만 마운트합니다. ```sh BFU_PHONE_HOST=PHONE_IP \ BFU_SSH_KEY=/path/to/dawnshell-ed25519 \ -./scripts/test-final-bfu.sh +./scripts/tests/device/test-final-bfu.sh ``` 수정 ROM이 BFU에서 앱 CE를 노출한다는 사실을 이미 확인했고 예외 정책을 @@ -220,7 +220,7 @@ Android `MediaExtractor`/하드웨어 `MediaCodec`이 DE 파일을 직접 읽습 `dawnshell-codec health --format json`은 새 private worker가 `worker_state=ready`에 도달하는지, `dawnshell-codec negative-test`는 잘못된 요청을 격리한 뒤 후속 worker가 다시 동작하는지 확인합니다. 최종 5회 -시험은 `BFU_REQUIRE_HARDWARE_CODEC=1 BFU_CYCLES=5 scripts/test-final-bfu.sh`로 +시험은 `BFU_REQUIRE_HARDWARE_CODEC=1 BFU_CYCLES=5 scripts/tests/device/test-final-bfu.sh`로 잠금 해제 전후에 동일한 검사를 실행합니다. 기존 프로그램 자동 연동은 Debian에서 `dawnshell-ffmpeg`로 확인합니다. @@ -233,7 +233,7 @@ dawnshell-ffmpeg -i input.mp4 -vf scale=640:480 -c:v libx264 out.mp4 첫 명령은 hardware 경로로 처리되어야 하고, filter를 사용한 두 번째 명령은 실제 FFmpeg로 위임되어야 합니다. `require` 모드는 software fallback을 오류로 만들므로 성능 비교 시 software 결과를 hardware로 오인하지 않게 합니다. 명령줄 판정 자체는 -`scripts/test-ffmpeg-bridge-plan.sh`가 기기 없이 회귀로 고정합니다. +`scripts/tests/host/test-ffmpeg-bridge-plan.sh`가 기기 없이 회귀로 고정합니다. 앱의 **단기 성능·품질·오류 회귀 검사**는 다음을 한 번에 수행합니다. @@ -263,7 +263,7 @@ software 대비 CPU 감소율을 기록하되 임의의 수치로 실패시키 BFU_REQUIRE_HARDWARE_CODEC=1 \ BFU_REQUIRE_CODEC_PERFORMANCE=1 \ BFU_CYCLES=5 \ -scripts/test-final-bfu.sh +scripts/tests/device/test-final-bfu.sh ``` 결과 `summary.tsv`에는 cycle별 Android boot ID와 systemd PID, BFU/AFU private diff --git a/docs/testing.md b/docs/testing.md index 988b85d..9a44927 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -75,7 +75,7 @@ times. The harness is: ```sh BFU_PHONE_HOST=PHONE_IP \ BFU_SSH_KEY=/path/to/dawnshell-ed25519 \ -./scripts/test-final-bfu.sh +./scripts/tests/device/test-final-bfu.sh ``` Use `BFU_EXPECT_CE_READABLE_OVERRIDE=1` only on a ROM whose unsafe CE exposure has @@ -124,7 +124,7 @@ The first command must run on hardware; the filtered command must be delegated to the real FFmpeg. `require` turns a software fallback into an error so a software result cannot be mistaken for hardware during benchmarking. Command routing itself is pinned without a device by -`scripts/test-ffmpeg-bridge-plan.sh`. +`scripts/tests/host/test-ffmpeg-bridge-plan.sh`. The short performance, quality, and error-regression button additionally checks the inherited memfd/eventfd path, B-frame MP4 timestamps, a matching 1080p diff --git a/scripts/build-all.sh b/scripts/build-all.sh deleted file mode 100755 index 9ab00f1..0000000 --- a/scripts/build-all.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -dist_dir="$root_dir/dist" - -: "${JAVA_HOME:?Set JAVA_HOME to JDK 17}" -: "${ANDROID_HOME:?Set ANDROID_HOME to the Android SDK}" -ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-$ANDROID_HOME/ndk/29.0.14206865}" -export ANDROID_NDK_HOME - -case "$(uname -s)" in - MINGW*|MSYS*|CYGWIN*) - # The OpenSSH interoperability unit test runs Windows ssh-keygen. MSYS2's - # default PATH contains System32 but not its OpenSSH subdirectory. - windows_openssh=/c/Windows/System32/OpenSSH - if [[ -x "$windows_openssh/ssh-keygen.exe" ]]; then - export PATH="$windows_openssh:$PATH" - fi - ;; -esac - -if [[ "${DAWNSHELL_SKIP_BOOTSTRAP_SOURCE_BUILD:-0}" != 1 ]]; then - "$root_dir/scripts/build-bootstrap-runtime.sh" -fi -"$root_dir/scripts/test-compatibility-policy.sh" -"$root_dir/scripts/test-docker-ipc-wrapper.sh" -"$root_dir/scripts/test-host-usb-policy.sh" -"$root_dir/scripts/test-hardware-codec-bridge.sh" -"$root_dir/scripts/test-ffmpeg-bridge-plan.sh" -"$root_dir/scripts/test-kernel-quirk-guards.sh" -"$root_dir/scripts/test-live-codec-pipeline.sh" -"$root_dir/scripts/test-gpu-status-tool.sh" -"$root_dir/scripts/test-host-reboot-isolation.sh" -"$root_dir/scripts/test-rootfs-path-resolution.sh" -"$root_dir/scripts/test-lifecycle-control-policy.sh" -"$root_dir/scripts/test-native-output.sh" -"$root_dir/scripts/test-documentation.sh" -"$root_dir/gradlew" -p "$root_dir" \ - clean :app:assembleDebug :app:lintDebug :app:testDebugUnitTest - -mkdir -p "$dist_dir" -apk_path="$(find "$root_dir/app/build/outputs/apk/debug" -maxdepth 1 \ - -type f -name '*.apk' -print -quit)" -[[ -n "$apk_path" && -s "$apk_path" ]] -output_apk="$dist_dir/$(basename "$apk_path")" -cp "$apk_path" "$output_apk" - -sha256sum "$output_apk" -echo "Package: me.aroxu.dawnshell" -echo "Debug APK uses a public development key; use a private key for production." diff --git a/scripts/build-bfu-namespace-probe.sh b/scripts/build-bfu-namespace-probe.sh deleted file mode 100755 index 5afb05f..0000000 --- a/scripts/build-bfu-namespace-probe.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Kept as a compatibility entry point for existing build automation. The -# namespace probe now shares the same three-ABI source build and validation as -# the complete standalone bootstrap runtime. -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -exec "$repo_dir/scripts/build-bootstrap-runtime.sh" diff --git a/scripts/build-bootstrap-runtime.sh b/scripts/build-bootstrap-runtime.sh deleted file mode 100755 index 77d25dd..0000000 --- a/scripts/build-bootstrap-runtime.sh +++ /dev/null @@ -1,613 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -sources_dir="$repo_dir/bfu-runtime/sources" -assets_dir="$repo_dir/app/src/main/assets/bfu" -output_dir="$assets_dir/bin" -bootstrap_assets_dir="$assets_dir/bootstrap" -if [[ -n "${DAWNSHELL_BUILD_JOBS:-}" ]]; then - jobs="$DAWNSHELL_BUILD_JOBS" -elif command -v nproc >/dev/null 2>&1; then - jobs="$(nproc)" -elif command -v getconf >/dev/null 2>&1; then - jobs="$(getconf _NPROCESSORS_ONLN 2>/dev/null || printf '4')" -else - jobs=4 -fi -[[ "$jobs" =~ ^[1-9][0-9]*$ ]] || { - echo "DAWNSHELL_BUILD_JOBS must be a positive integer: $jobs" >&2 - exit 2 -} - -: "${ANDROID_NDK_HOME:?Set ANDROID_NDK_HOME to Android NDK 29.0.14206865}" - -export LC_ALL=C -export TZ=UTC -export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-1758672000}" - -case "$(uname -s)" in - Linux*) host_tag=linux-x86_64 ;; - Darwin*) host_tag=darwin-x86_64 ;; - MINGW*|MSYS*|CYGWIN*) host_tag=windows-x86_64 ;; - *) echo "Unsupported build host: $(uname -s)" >&2; exit 2 ;; -esac - -ndk_properties="$ANDROID_NDK_HOME/source.properties" -if [[ ! -f "$ndk_properties" ]] \ - || ! grep -Fqx 'Pkg.Revision = 29.0.14206865' "$ndk_properties"; then - echo "Android NDK 29.0.14206865 is required: $ANDROID_NDK_HOME" >&2 - exit 2 -fi - -toolchain="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$host_tag" -ndk_bin="$toolchain/bin" - -find_ndk_tool() { - local name="$1" - local candidate - for candidate in "$ndk_bin/$name" "$ndk_bin/$name.exe" "$ndk_bin/$name.cmd"; do - if [[ -f "$candidate" ]]; then - printf '%s\n' "$candidate" - return 0 - fi - done - echo "Missing NDK tool: $name" >&2 - return 1 -} - -clang="$(find_ndk_tool clang)" -llvm_ar="$(find_ndk_tool llvm-ar)" -llvm_nm="$(find_ndk_tool llvm-nm)" -llvm_ranlib="$(find_ndk_tool llvm-ranlib)" -llvm_strip="$(find_ndk_tool llvm-strip)" -llvm_objcopy="$(find_ndk_tool llvm-objcopy)" -llvm_readelf="$(find_ndk_tool llvm-readelf)" -llvm_strings="$(find_ndk_tool llvm-strings)" - -required_host_tools=( - awk bash chmod gcc grep install make mkdir patch rm sed sha256sum sort tar yes -) -for command_name in "${required_host_tools[@]}"; do - command -v "$command_name" >/dev/null 2>&1 || { - echo "Missing host build tool: $command_name" >&2 - exit 3 - } -done - -verify_source() { - local hash="$1" - local filename="$2" - local path="$sources_dir/$filename" - [[ -f "$path" ]] || { - echo "Missing vendored source: $path" >&2 - exit 4 - } - printf '%s %s\n' "$hash" "$path" | sha256sum -c - -} - -verify_source 34f9ea6ff8636f2c9241153b9114eefa9e65674a45318ae1ef95bb5f31c53bb2 busybox-1.38.0.tar.bz2 -verify_source 232ec755f4b1f445f829996885846abba6f1b6fd55d049476ab26ddd8c4b4e1b debootstrap_1.0.141.tar.gz -verify_source 48bd396167f3d592f624e1e9012208a9a2adcb531cf56c90e27f0690a05f170e base-installer_1.226.tar.xz -verify_source dd17ab2e9a04fd79d39d853f599cbc852062ddb9ab52a4ddeb4176fd8b302964 gnupg-2.4.9.tar.bz2 -verify_source d2931cdad266e633510f9970e1a2f346055e351bb19f9b78912475b8074c36f6 libassuan-3.0.2.tar.bz2 -verify_source 7df5c08d952ba33f9b6bdabdb06a61a78b2cf62d2122c2d1d03a91a79832aa3c libgcrypt-1.12.1.tar.bz2 -verify_source a19bc5087fd97026d93cb4b45d51638d1a25202a5e1fbc3905799f424cfa6134 libgpg-error-1.59.tar.bz2 -verify_source 0f4510f1c7a679c3545990a31479f391ad45d84e039176309d42f80cf41743f5 libksba-1.6.8.tar.bz2 -verify_source 8bd24b4f23a3065d6e5b26e98aba9ce783ea4fd781069c1b35d149694e90ca3e npth-1.8.tar.bz2 -verify_source 9ea7778e443144ca490668737a8ab22dd3e748bb99e805e22ec055abeb3c7fac debian-archive-keyring_2025.1_all.deb -verify_source f376bfae7c864c76483bed094572db5ccb6f0d5f3f79ad021d6f461f0c2af436 debian-archive-keyring_2025.1.dsc -verify_source 2d019c3fa19c42da4d37571e473c296286dad0214cb3bd5cafd99f04a8bf5471 debian-archive-keyring_2025.1.tar.xz - -grep -Fq \ - '2d019c3fa19c42da4d37571e473c296286dad0214cb3bd5cafd99f04a8bf5471 138248 debian-archive-keyring_2025.1.tar.xz' \ - "$sources_dir/debian-archive-keyring_2025.1.dsc" || { - echo "Debian keyring source descriptor does not authenticate the vendored source" >&2 - exit 4 -} - -namespace_source="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" -if grep -Eq 'unshare[[:space:]]*\([[:space:]]*CLONE_NEWIPC' "$namespace_source"; then - echo "Unsafe CLONE_NEWIPC call is forbidden on legacy 4.4-era kernels" >&2 - exit 6 -fi -for marker in \ - 'prepare_devices_cgroup_mount(control_dir, host_usb_policy)' \ - 'init_moved_to_devices_cgroup' \ - 'cgroup_view_devices_bind' \ - 'cleanup_cgroup_subtree_failed' \ - 'devices_cgroup=delegated' \ - 'prepare_unified_cgroup_mount(control_dir, host_usb_policy)' \ - 'cgroup_v2_device_bpf_verified' \ - 'BPF_F_ALLOW_MULTI' \ - 'command_moved_to_cgroup_v2_leaf' \ - 'cgroup_requested=auto' \ - 'fallback=v1' \ - 'cgroup_delegation=delegated' \ - 'CGROUP_POLICY_FORCE_V2' \ - 'CGROUP_POLICY_FORCE_V1' \ - 'HOST_USB_EXCLUSIVE' \ - 'reconcile_exclusive_usb' \ - 'restore_exclusive_usb' \ - 'exclusive_mode_requires_at_least_one_VID:PID'; do - grep -Fq "$marker" "$namespace_source" || { - echo "Missing namespace/cgroup invariant: $marker" >&2 - exit 7 - } -done -if grep -Eq 'uname[[:space:]]*\([^)]*-r|/proc/version' "$namespace_source"; then - echo "Cgroup selection must probe capabilities, not kernel version strings" >&2 - exit 8 -fi - -build_root="$(mktemp -d "${TMPDIR:-/tmp}/dawnshell-bootstrap-runtime.XXXXXX")" -cleanup() { - if [[ "${DAWNSHELL_KEEP_BOOTSTRAP_BUILD:-0}" == 1 ]]; then - echo "Keeping bootstrap build tree: $build_root" - else - rm -rf -- "$build_root" - fi -} -trap cleanup EXIT - -configure_static_library() { - local source_root="$1" - shift - local build_triplet - build_triplet="$("$source_root/build-aux/config.guess")" - ( - cd "$source_root" - case "$(uname -s)" in - MINGW*|MSYS*|CYGWIN*) - # Keep runtime directory macros deterministic while still - # allowing MSYS to translate temporary include/library paths. - # shellcheck disable=SC2030 - export MSYS2_ARG_CONV_EXCL='-DLOCALEDIR;-DSYSCONFDIR;-DLOCALSTATEDIR;-DDATADIR' - ;; - esac - ./configure \ - --host="$gnu_host" \ - --build="$build_triplet" \ - --prefix="$prefix" \ - --enable-static \ - --disable-shared \ - "$@" - # Runtime directory constants must not contain the temporary build - # prefix. Override them only while compiling; make install must keep - # using the private staging prefix and never write to host /system. - make -j"$jobs" \ - localedir=/system/share/locale \ - sysconfdir=/system/etc \ - localstatedir=/system/var \ - datadir=/system/share - make install - ) -} - -validate_elf() { - local binary="$1" - local machine_pattern="$2" - local interpreter="$3" - - # Do not use grep -q here. With pipefail enabled it may close the pipe - # early, make llvm-* exit on SIGPIPE, and invert a successful validation. - "$llvm_readelf" -h "$binary" \ - | grep -E "Machine:[[:space:]]+$machine_pattern" >/dev/null - "$llvm_readelf" -h "$binary" \ - | grep -E 'Type:[[:space:]]+DYN' >/dev/null - "$llvm_readelf" -l "$binary" \ - | grep -F "$interpreter" >/dev/null - if "$llvm_readelf" -d "$binary" | grep -F 'Shared library:' \ - | grep -Ev '\[(libc|libdl)\.so\]' >/dev/null; then - echo "Unexpected Android native dependency in $binary" >&2 - "$llvm_readelf" -d "$binary" | grep -F 'Shared library:' >&2 - exit 5 - fi - if "$llvm_strings" "$binary" \ - | grep -E '/data/(data|user|user_de)/[^/ ]+' \ - >/dev/null; then - echo "Forbidden fixed Android data path embedded in $binary" >&2 - exit 6 - fi - if "$llvm_strings" "$binary" \ - | grep -E 'dawnshell-bootstrap-runtime|[A-Za-z]:/Users/' \ - >/dev/null; then - echo "Non-reproducible host build path embedded in $binary" >&2 - exit 6 - fi -} - -validate_static_elf() { - local binary="$1" - local machine_pattern="$2" - - "$llvm_readelf" -h "$binary" \ - | grep -E "Machine:[[:space:]]+$machine_pattern" >/dev/null - "$llvm_readelf" -h "$binary" \ - | grep -E 'Type:[[:space:]]+EXEC' >/dev/null - if "$llvm_readelf" -l "$binary" | grep -F 'Requesting program interpreter' \ - >/dev/null; then - echo "Static codec client unexpectedly has a program interpreter" >&2 - exit 5 - fi - if "$llvm_readelf" -d "$binary" | grep -F 'Shared library:' >/dev/null; then - echo "Static codec client unexpectedly has shared dependencies" >&2 - exit 5 - fi - if "$llvm_strings" "$binary" \ - | grep -E '/data/(data|user|user_de)/[^/ ]+|[A-Za-z]:/Users/' \ - >/dev/null; then - echo "Forbidden fixed data or host path embedded in $binary" >&2 - exit 6 - fi -} - -validate_codec_worker_elf() { - local binary="$1" - local machine_pattern="$2" - local interpreter="$3" - - "$llvm_readelf" -h "$binary" \ - | grep -E "Machine:[[:space:]]+$machine_pattern" >/dev/null - "$llvm_readelf" -h "$binary" \ - | grep -E 'Type:[[:space:]]+DYN' >/dev/null - "$llvm_readelf" -l "$binary" | grep -F "$interpreter" >/dev/null - local dependencies - dependencies="$($llvm_readelf -d "$binary" \ - | sed -n 's/.*Shared library: \[\([^]]*\)\].*/\1/p' | sort -u)" - local expected=$'libandroid.so\nlibc.so\nlibdl.so\nlibmediandk.so' - if [[ "$dependencies" != "$expected" ]]; then - echo "Unexpected Android codec worker dependencies in $binary" >&2 - printf '%s\n' "$dependencies" >&2 - exit 5 - fi - if "$llvm_strings" "$binary" \ - | grep -E '/data/(data|user|user_de)/[^/ ]+|[A-Za-z]:/Users/' \ - >/dev/null; then - echo "Forbidden fixed data or host path embedded in $binary" >&2 - exit 6 - fi -} - -merge_busybox_config() { - local source_root="$1" - local fragment="$repo_dir/bfu-runtime/config/busybox-bootstrap.config" - ( - cd "$source_root" - make allnoconfig > busybox-config.log - while IFS= read -r setting; do - case "$setting" in - CONFIG_*=y) - local symbol="${setting%%=*}" - if grep -Fqx "# $symbol is not set" .config; then - sed -i "s/^# $symbol is not set$/$setting/" .config - elif ! grep -Fqx "$setting" .config; then - printf '%s\n' "$setting" >> .config - fi - ;; - esac - done < "$fragment" - - set +e - yes '' | make oldconfig >> busybox-config.log - local oldconfig_status="${PIPESTATUS[1]}" - set -e - [[ "$oldconfig_status" -eq 0 ]] - ) -} - -build_busybox() { - local work="$1" - local stage="$2" - tar -xf "$sources_dir/busybox-1.38.0.tar.bz2" -C "$work" - local source_root="$work/busybox-1.38.0" - ( - cd "$source_root" - patch -p1 < "$repo_dir/bfu-runtime/patches/busybox/0001-android-mount-without-addmntent.patch" - ) - merge_busybox_config "$source_root" - ( - cd "$source_root" - make -j"$jobs" \ - CC="$cc" HOSTCC=gcc \ - AR="$llvm_ar" NM="$llvm_nm" STRIP="$llvm_strip" \ - OBJCOPY="$llvm_objcopy" \ - EXTRA_CFLAGS='-Wno-ignored-optimization-argument -Wno-unused-command-line-argument' - "$llvm_strip" --strip-unneeded busybox - install -m 700 busybox "$stage/dawnshell-toolbox" - ) - - local symbol - for symbol in \ - BUSYBOX FEATURE_INSTALLER FEATURE_MD5_SHA1_SUM_CHECK \ - FEATURE_STAT_FORMAT ASH AWK CHROOT DPKG_DEB MOUNT SED SHA256SUM \ - STAT TAR UNSHARE WGET ZCAT XZCAT; do - grep -Fqx "CONFIG_${symbol}=y" "$source_root/.config" || { - echo "BusyBox output is missing required config symbol: CONFIG_${symbol}=y" >&2 - exit 7 - } - done -} - -build_pkgdetails() { - local work="$1" - local stage="$2" - tar -xf "$sources_dir/base-installer_1.226.tar.xz" -C "$work" - "$clang" "--target=$clang_target" \ - -std=c17 -Os -fPIE -fstack-protector-strong \ - -Wall -Wextra -Wformat=2 -Wno-format-nonliteral \ - -Wl,-pie,-z,relro,-z,now \ - "$work/base-installer/pkgdetails.c" -o "$stage/pkgdetails" - "$llvm_strip" --strip-unneeded "$stage/pkgdetails" - chmod 700 "$stage/pkgdetails" -} - -build_gpgv() { - local work="$1" - local stage="$2" - local component - for component in \ - libgpg-error-1.59.tar.bz2 \ - libgcrypt-1.12.1.tar.bz2 \ - libassuan-3.0.2.tar.bz2 \ - libksba-1.6.8.tar.bz2 \ - npth-1.8.tar.bz2 \ - gnupg-2.4.9.tar.bz2; do - tar -xf "$sources_dir/$component" -C "$work" - done - - ( - cd "$work/libgpg-error-1.59" - patch -p1 < "$repo_dir/bfu-runtime/patches/libgpg-error/0001-skip-deprecated-config-self-test.patch" - ) - - prefix="$work/prefix" - mkdir -p "$prefix" - export CC="$cc" - export AR="$llvm_ar" - export NM="$llvm_nm" - export RANLIB="$llvm_ranlib" - export STRIP="$llvm_strip" - export CPPFLAGS="-I$prefix/include" - export CFLAGS='-Os -fPIC -fstack-protector-strong' - export LDFLAGS="-L$prefix/lib -Wl,-z,relro,-z,now" - export PKG_CONFIG_LIBDIR="$prefix/lib/pkgconfig" - export PKG_CONFIG_PATH="$prefix/lib/pkgconfig" - export PATH="$prefix/bin:$PATH" - - configure_static_library "$work/libgpg-error-1.59" \ - --disable-nls --disable-doc --disable-tests \ - --disable-install-gpg-error-config - - configure_static_library "$work/libgcrypt-1.12.1" \ - --disable-doc --disable-asm \ - --with-libgpg-error-prefix="$prefix" - - configure_static_library "$work/libassuan-3.0.2" \ - --disable-doc \ - --with-libgpg-error-prefix="$prefix" - - configure_static_library "$work/libksba-1.6.8" \ - --disable-doc \ - --with-libgpg-error-prefix="$prefix" - - ( - cd "$work/npth-1.8" - local build_triplet - build_triplet="$(./build-aux/config.guess)" - ac_cv_search_pthread_cancel='none required' ./configure \ - --host="$gnu_host" \ - --build="$build_triplet" \ - --prefix="$prefix" \ - --enable-static \ - --disable-shared \ - --disable-tests - make -j"$jobs" - make install - ) - - # gpgrt-config recursively invokes itself under MSYS path translation. - # The legacy, generated config scripts are sufficient for this cross-build. - rm -f "$prefix/bin/gpgrt-config" - - ( - cd "$work/gnupg-2.4.9" - local build_triplet - build_triplet="$(./build-aux/config.guess)" - case "$(uname -s)" in - MINGW*|MSYS*|CYGWIN*) - # Preserve the fixed /system paths embedded by GnuPG instead - # of letting MSYS rewrite -D arguments to a host path. - # shellcheck disable=SC2031 - export MSYS2_ARG_CONV_EXCL='-DGNUPG_;-DLOCALEDIR' - ;; - esac - export CFLAGS='-Os -fPIE -fstack-protector-strong' - export GPG_ERROR_CONFIG="$work/libgpg-error-1.59/src/gpg-error-config-old" - export LIBGCRYPT_CONFIG="$prefix/bin/libgcrypt-config" - export LIBASSUAN_CONFIG="$prefix/bin/libassuan-config" - export KSBA_CONFIG="$prefix/bin/ksba-config" - export NPTH_CONFIG="$work/npth-1.8/npth-config" - ./configure \ - --host="$gnu_host" \ - --build="$build_triplet" \ - --prefix=/system \ - --disable-nls \ - --disable-doc \ - --disable-tests \ - --disable-gpgsm \ - --disable-scdaemon \ - --disable-dirmngr \ - --disable-keyboxd \ - --disable-tpm2d \ - --disable-gpgtar \ - --disable-wks-tools \ - --disable-ccid-driver \ - --disable-ldap \ - --disable-zip \ - --disable-bzip2 \ - --disable-sqlite \ - --without-libiconv-prefix \ - --without-libintl-prefix \ - --with-libgpg-error-prefix="$prefix" \ - --with-libgcrypt-prefix="$prefix" \ - --with-libassuan-prefix="$prefix" - make -j"$jobs" -C common - make -j"$jobs" -C regexp - make -j"$jobs" -C kbx - make -j"$jobs" -C g10 gpgv - "$llvm_strip" --strip-unneeded g10/gpgv - install -m 700 g10/gpgv "$stage/gpgv" - ) -} - -build_namespace_probe() { - local stage="$1" - "$clang" "--target=$clang_target" \ - -std=c17 -Os -fPIE -fstack-protector-strong \ - -Wall -Wextra -Werror -Wformat=2 \ - -Wl,-pie -Wl,-z,relro,-z,now -Wl,--gc-sections \ - "$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" \ - -o "$stage/bfu-namespace-probe" - "$llvm_strip" --strip-unneeded "$stage/bfu-namespace-probe" - chmod 700 "$stage/bfu-namespace-probe" -} - -# Installs a seccomp filter that reports ENOSYS for a pathological -# close_range(2) backport, then executes the requested command. Shell scripts -# cannot install a filter themselves, so the Debian chroot is entered through -# this wrapper. -build_fdguard() { - local stage="$1" - "$clang" "--target=$clang_target" \ - -std=c17 -Os -fPIE -fstack-protector-strong \ - -Wall -Wextra -Werror -Wformat=2 \ - -Wl,-pie -Wl,-z,relro,-z,now -Wl,--gc-sections \ - "$repo_dir/app/src/main/cpp/dawnshell_fdguard.c" \ - -o "$stage/dawnshell-fdguard" - "$llvm_strip" --strip-unneeded "$stage/dawnshell-fdguard" - chmod 700 "$stage/dawnshell-fdguard" -} - -build_codec_client() { - local stage="$1" - "$clang" "--target=$clang_target" \ - -std=c17 -Os -static -fPIE -fstack-protector-strong \ - -Wall -Wextra -Werror -Wformat=2 \ - -Wl,-z,relro,-z,now -Wl,--gc-sections \ - "$repo_dir/app/src/main/cpp/dawnshell_codec_client.c" \ - -o "$stage/dawnshell-codec" - "$llvm_strip" --strip-unneeded "$stage/dawnshell-codec" - chmod 700 "$stage/dawnshell-codec" -} - -build_codec_worker() { - local stage="$1" - "$clang" "--target=$clang_target" \ - -std=c17 -Os -fPIE -fstack-protector-strong \ - -Wall -Wextra -Werror -Wformat=2 \ - -Wl,-pie -Wl,-z,relro,-z,now -Wl,--gc-sections \ - "$repo_dir/app/src/main/cpp/dawnshell_codec_worker.c" \ - "$repo_dir/app/src/main/cpp/dawnshell_codec_ndk.c" \ - -lmediandk -landroid -ldl \ - -o "$stage/dawnshell-codec-worker" - "$llvm_strip" --strip-unneeded "$stage/dawnshell-codec-worker" - chmod 700 "$stage/dawnshell-codec-worker" -} - -build_architecture() { - local abi="$1" - local clang_target="$2" - gnu_host="$3" - local debian_arch="$4" - local machine_pattern="$5" - local interpreter="$6" - local work="$build_root/$abi" - local stage="$work/stage" - mkdir -p "$stage" - - cc="$clang --target=$clang_target" - echo "=== Building $abi (Debian $debian_arch) ===" - build_busybox "$work" "$stage" - build_pkgdetails "$work" "$stage" - build_gpgv "$work" "$stage" - build_namespace_probe "$stage" - build_fdguard "$stage" - build_codec_client "$stage" - build_codec_worker "$stage" - - local binary - for binary in dawnshell-toolbox pkgdetails gpgv bfu-namespace-probe \ - dawnshell-fdguard; do - validate_elf "$stage/$binary" "$machine_pattern" "$interpreter" - done - validate_static_elf "$stage/dawnshell-codec" "$machine_pattern" - validate_codec_worker_elf "$stage/dawnshell-codec-worker" \ - "$machine_pattern" "$interpreter" - - mkdir -p "$output_dir/$abi" - install -m 700 "$stage/dawnshell-toolbox" \ - "$output_dir/$abi/dawnshell-toolbox" - install -m 700 "$stage/pkgdetails" "$output_dir/$abi/pkgdetails" - install -m 700 "$stage/gpgv" "$output_dir/$abi/gpgv" - install -m 700 "$stage/bfu-namespace-probe" \ - "$output_dir/$abi/bfu-namespace-probe" - install -m 700 "$stage/dawnshell-fdguard" \ - "$output_dir/$abi/dawnshell-fdguard" - install -m 700 "$stage/dawnshell-codec" \ - "$output_dir/$abi/dawnshell-codec" - install -m 700 "$stage/dawnshell-codec-worker" \ - "$output_dir/$abi/dawnshell-codec-worker" - - printf '%s\n' \ - "android_abi=$abi" \ - "debian_architecture=$debian_arch" \ - "android_api=24" \ - "busybox=1.38.0" \ - "pkgdetails_base_installer=1.226" \ - "gpgv=2.4.9" \ - "dawnshell_codec_protocol=1" \ - "dawnshell_codec_transport=inherited_memfd_eventfd" \ - "dawnshell_codec_worker=ndk_mediacodec" \ - > "$output_dir/$abi/runtime.properties" - - sha256sum "$output_dir/$abi/"{dawnshell-toolbox,pkgdetails,gpgv,bfu-namespace-probe,dawnshell-fdguard,dawnshell-codec,dawnshell-codec-worker} -} - -mkdir -p "$output_dir" "$bootstrap_assets_dir" -rm -f -- "$output_dir/bfu-namespace-probe-arm64" - -requested_abis="${DAWNSHELL_BOOTSTRAP_ABIS:-armeabi-v7a arm64-v8a x86_64}" -for requested_abi in $requested_abis; do - case "$requested_abi" in - armeabi-v7a) - build_architecture \ - armeabi-v7a armv7a-linux-android24 armv7a-linux-androideabi \ - armhf 'ARM' /system/bin/linker - ;; - arm64-v8a) - build_architecture \ - arm64-v8a aarch64-linux-android24 aarch64-linux-androideabi \ - arm64 'AArch64' /system/bin/linker64 - ;; - x86_64) - build_architecture \ - x86_64 x86_64-linux-android24 x86_64-linux-androideabi \ - amd64 'Advanced Micro Devices X86-64' /system/bin/linker64 - ;; - *) - echo "Unsupported DAWNSHELL_BOOTSTRAP_ABIS entry: $requested_abi" >&2 - exit 8 - ;; - esac -done - -install -m 600 "$sources_dir/debootstrap_1.0.141.tar.gz" \ - "$bootstrap_assets_dir/debootstrap_1.0.141.tgz" -rm -f -- "$bootstrap_assets_dir/debootstrap_1.0.141.tar.gz" -install -m 600 "$sources_dir/debian-archive-keyring_2025.1_all.deb" \ - "$bootstrap_assets_dir/debian-archive-keyring_2025.1_all.deb" -install -m 600 "$sources_dir/SOURCES.lock" \ - "$bootstrap_assets_dir/SOURCES.lock" - -echo "Bootstrap runtime source build completed for: $requested_abis" diff --git a/scripts/package-release.sh b/scripts/package-release.sh index c306d37..03aea41 100755 --- a/scripts/package-release.sh +++ b/scripts/package-release.sh @@ -37,7 +37,6 @@ dirty_source_entries=() while IFS= read -r -d '' entry; do path="${entry:3}" case "$path" in - app/src/main/assets/bfu/bin/*|\ app/src/main/assets/bfu/bootstrap/debootstrap_1.0.141.tgz|\ app/src/main/assets/bfu/bootstrap/debian-archive-keyring_2025.1_all.deb|\ app/src/main/assets/bfu/bootstrap/SOURCES.lock) @@ -64,9 +63,12 @@ required_source_paths=( bfu-runtime/sources/busybox-1.38.0.tar.bz2 bfu-runtime/sources/debian-archive-keyring_2025.1.dsc bfu-runtime/sources/debian-archive-keyring_2025.1.tar.xz - scripts/build-bootstrap-runtime.sh + buildSrc/build.gradle.kts + buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntime.kt + buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BusyBoxTask.kt + buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/GpgvTask.kt scripts/package-release.sh - app/build.gradle + app/build.gradle.kts gradlew gradle/wrapper/gradle-wrapper.properties ) diff --git a/scripts/test-dashboard-settings-ux.sh b/scripts/test-dashboard-settings-ux.sh deleted file mode 100755 index f4b24a2..0000000 --- a/scripts/test-dashboard-settings-ux.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -layout="$repo_dir/app/src/main/res/layout/activity_boot.xml" -navigation="$repo_dir/app/src/main/res/menu/menu_dashboard_navigation.xml" -activity="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BootActivity.java" -service="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuBootService.java" -guide="$repo_dir/docs/user-guide.md" - -for page in dashboard_page_home dashboard_page_access dashboard_page_advanced; do - grep -Fq "android:id=\"@+id/$page\"" "$layout" -done -advanced_line="$(grep -nF 'android:id="@+id/dashboard_page_advanced"' "$layout" | cut -d: -f1)" -diagnostics_line="$(grep -nF 'android:text="@string/dawnshell_section_diagnostics"' "$layout" | cut -d: -f1)" -(( diagnostics_line > advanced_line )) -[[ "$(grep -Fc '&2 - exit 1 -fi - -grep -Fq 'SettingsSnapshot.fromPreferences(this)' "$activity" -grep -Fq 'requested.requiresRuntimeApply(previous)' "$activity" -grep -Fq 'requestRuntimeSettingsApply(this' "$activity" -[[ "$(grep -Fc 'savePreferences(requested)' "$activity")" -eq 1 ]] -if grep -Fq 'savePreferences();' "$activity"; then - echo "immediate command buttons must not silently apply pending settings" >&2 - exit 1 -fi -grep -Fq 'ACTION_APPLY_RUNTIME_SETTINGS' "$service" -grep -Fq 'HostUsbProvisioner.apply(this, layout)' "$service" -grep -Fq 'DockerNetworkProvisioner.apply(' "$service" -[[ "$(grep -Fc '"AFU_settings_apply"' "$service")" -eq 1 ]] -[[ "$(grep -Fc '"AFU_settings_applied"' "$service")" -eq 1 ]] - -grep -Fq '| **Home** |' "$guide" -grep -Fq 'global **Apply** bar' "$guide" - -echo "PASS: dashboard navigation and the single settings apply workflow are pinned." diff --git a/scripts/test-bfu.sh b/scripts/tests/device/test-bfu.sh similarity index 100% rename from scripts/test-bfu.sh rename to scripts/tests/device/test-bfu.sh diff --git a/scripts/test-debian-runtime-bfu.sh b/scripts/tests/device/test-debian-runtime-bfu.sh similarity index 100% rename from scripts/test-debian-runtime-bfu.sh rename to scripts/tests/device/test-debian-runtime-bfu.sh diff --git a/scripts/test-final-bfu.sh b/scripts/tests/device/test-final-bfu.sh similarity index 97% rename from scripts/test-final-bfu.sh rename to scripts/tests/device/test-final-bfu.sh index 728f7cd..18583fb 100755 --- a/scripts/test-final-bfu.sh +++ b/scripts/tests/device/test-final-bfu.sh @@ -17,7 +17,7 @@ if [[ "${BFU_REQUIRE_CODEC_PERFORMANCE:-0}" == "1" exit 2 fi -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" cycles="${BFU_CYCLES:-5}" results_dir="${BFU_RESULTS_DIR:-$repo_dir/test-results/bfu-$(date -u +%Y%m%dT%H%M%SZ)}" @@ -142,7 +142,7 @@ for ((cycle = 1; cycle <= cycles; cycle++)); do echo "============================================================" echo "Final BFU cold cycle $cycle/$cycles" cycle_log="$results_dir/cycle-$(printf '%02d' "$cycle").log" - "$repo_dir/scripts/test-systemd-ssh-bfu.sh" 2>&1 | tee "$cycle_log" + "$repo_dir/scripts/tests/device/test-systemd-ssh-bfu.sh" 2>&1 | tee "$cycle_log" boot_id="$(adb shell cat /proc/sys/kernel/random/boot_id | tr -d '\r\n')" app_pid="$(adb shell pidof me.aroxu.dawnshell | tr -d '\r\n' || true)" @@ -233,7 +233,7 @@ fi echo "============================================================" echo "Running namespace poweroff/reboot/shutdown isolation checks..." -"$repo_dir/scripts/test-systemd-shutdown-isolation.sh" 2>&1 \ +"$repo_dir/scripts/tests/device/test-systemd-shutdown-isolation.sh" 2>&1 \ | tee "$results_dir/shutdown-isolation.log" cp "$summary" "$results_dir/summary.tsv" diff --git a/scripts/test-root-bfu.sh b/scripts/tests/device/test-root-bfu.sh similarity index 100% rename from scripts/test-root-bfu.sh rename to scripts/tests/device/test-root-bfu.sh diff --git a/scripts/test-rootfs-bfu.sh b/scripts/tests/device/test-rootfs-bfu.sh similarity index 100% rename from scripts/test-rootfs-bfu.sh rename to scripts/tests/device/test-rootfs-bfu.sh diff --git a/scripts/test-systemd-shutdown-isolation.sh b/scripts/tests/device/test-systemd-shutdown-isolation.sh similarity index 100% rename from scripts/test-systemd-shutdown-isolation.sh rename to scripts/tests/device/test-systemd-shutdown-isolation.sh diff --git a/scripts/test-systemd-ssh-bfu.sh b/scripts/tests/device/test-systemd-ssh-bfu.sh similarity index 100% rename from scripts/test-systemd-ssh-bfu.sh rename to scripts/tests/device/test-systemd-ssh-bfu.sh diff --git a/scripts/test-compatibility-policy.sh b/scripts/tests/host/test-compatibility-policy.sh similarity index 88% rename from scripts/test-compatibility-policy.sh rename to scripts/tests/host/test-compatibility-policy.sh index 6ba7aeb..9ba54eb 100755 --- a/scripts/test-compatibility-policy.sh +++ b/scripts/tests/host/test-compatibility-policy.sh @@ -1,15 +1,20 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" preferences="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuPreferences.java" launcher="$repo_dir/app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java" native_launcher="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" policy_script="$repo_dir/app/src/main/assets/bfu/configure-docker-network.sh" usb_policy_script="$repo_dir/app/src/main/assets/bfu/configure-host-usb.sh" -layout="$repo_dir/app/src/main/res/layout/activity_boot.xml" +kotlin_dir="$repo_dir/app/src/main/kotlin/me/aroxu/dawnshell" strings="$repo_dir/app/src/main/res/values/strings.xml" -boot_activity="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BootActivity.java" +boot_activity="$kotlin_dir/BootActivity.kt" +boot_screen="$kotlin_dir/BootActivity.BootScreen.kt" +actions="$kotlin_dir/BootScreen.kt" +advanced_page="$kotlin_dir/BootActivity.BootScreen.ConfigurationPage.kt" +compatibility_page="$kotlin_dir/BootScreen.kt" +native_event="$kotlin_dir/NativeEvent.kt" boot_service="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuBootService.java" runtime_probe="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java" system_configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" @@ -32,7 +37,8 @@ grep -Fq 'BfuPreferences.usbPassthroughMode(context)' "$launcher" grep -Fq 'BfuPreferences.usbExclusiveDeviceIds(context)' "$launcher" grep -Fq 'BfuPreferences.cgroupPolicy(context)' "$launcher" grep -Fq 'BfuPreferences.pidNamespaceFallback(context)' "$launcher" -grep -Fq 'cgroup_delegation=delegated' "$launcher" +grep -Fq 'cgroup_delegation=delegated' "$native_launcher" +grep -Fq '@SerialName("cgroup_delegation")' "$native_event" grep -Fq 'KEY_PID_NAMESPACE_FALLBACK, false' "$preferences" grep -Fq '"fallback" : "strict"' "$launcher" grep -Fq '"probe-compat" : "probe"' "$runtime_probe" @@ -130,9 +136,9 @@ grep -Fq 'exec "$real_docker" "${rewritten[@]}"' "$policy_script" # shellcheck disable=SC2016 # Assert literal shell source, not this test's variables. grep -Fq 'existing unmanaged $docker_wrapper was preserved' "$policy_script" grep -Fq 'use /usr/bin/docker to bypass' "$policy_script" -grep -Fq 'android:id="@+id/docker_network_policy_group"' "$layout" -grep -Fq 'android:id="@+id/docker_storage_driver_group"' "$layout" -grep -Fq 'android:id="@+id/docker_storage_vfs"' "$layout" +grep -Fq 'R.string.dawnshell_docker_policy_title' "$compatibility_page" +grep -Fq 'R.string.dawnshell_docker_storage_title' "$compatibility_page" +grep -Fq 'BfuPreferences.DOCKER_STORAGE_VFS' "$compatibility_page" # The storage driver must be pinned explicitly so dockerd cannot silently pick # a different one after an upgrade. grep -Fq '"storage-driver": "overlay2",' "$policy_script" @@ -140,17 +146,16 @@ grep -Fq '"storage-driver": "vfs",' "$policy_script" grep -Fq 'Docker storage driver must be overlay2 or vfs' "$policy_script" # shellcheck disable=SC2016 # Assert literal shell source, not this test's variables. grep -Fq 'storage_driver=$storage_driver' "$policy_script" -grep -Fq 'android:id="@+id/switch_docker_host_ipc_compatibility"' "$layout" -grep -Fq 'android:id="@+id/cgroup_policy_group"' "$layout" -grep -Fq 'android:id="@+id/switch_pid_namespace_fallback"' "$layout" -grep -Fq 'android:id="@+id/usb_passthrough_group"' "$layout" -grep -Fq 'android:id="@+id/usb_passthrough_direct"' "$layout" -grep -Fq 'android:id="@+id/usb_passthrough_exclusive"' "$layout" -grep -Fq 'android:id="@+id/usb_exclusive_device_ids"' "$layout" -grep -Fq 'android:id="@+id/settings_apply_bar"' "$layout" -grep -Fq 'android:id="@+id/save_provision_button"' "$layout" -grep -Fq 'android:id="@+id/dashboard_navigation"' "$layout" -grep -Fq 'requestRuntimeSettingsApply(this' "$boot_activity" +grep -Fq 'R.string.dawnshell_docker_host_ipc_compatibility' "$compatibility_page" +grep -Fq 'R.string.dawnshell_cgroup_policy_title' "$compatibility_page" +grep -Fq 'BfuPreferences.CGROUP_AUTO' "$compatibility_page" +grep -Fq 'R.string.dawnshell_pid_namespace_fallback' "$compatibility_page" +grep -Fq 'BfuPreferences.USB_PASSTHROUGH_DIRECT' "$compatibility_page" +grep -Fq 'BfuPreferences.USB_PASSTHROUGH_EXCLUSIVE' "$compatibility_page" +grep -Fq 's.usbDeviceIds' "$compatibility_page" +grep -Fq 'if (state.settingsDirty) ApplyBar(actions)' "$boot_screen" +grep -Fq 'actions::confirmApplySettings' "$boot_screen" +grep -Fq 'BfuBootService.requestRuntimeSettingsApply(' "$boot_activity" grep -Fq 'ACTION_APPLY_RUNTIME_SETTINGS' "$boot_service" grep -Fq 'RUNTIME_SETTINGS_APPLIED' "$boot_service" grep -Fq 'applyAutomaticDockerMigration(layout, trigger)' "$boot_service" @@ -159,12 +164,11 @@ grep -Eq 'MANAGED_CONFIGURATION_REVISION = [0-9]+;' \ "$repo_dir/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java" grep -Fq 'writeManagedRevision(deContext, MANAGED_CONFIGURATION_REVISION)' \ "$repo_dir/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java" -if grep -Fq 'android:id="@+id/apply_host_usb_policy_button"' "$layout" \ - || grep -Fq 'android:id="@+id/apply_docker_policy_button"' "$layout"; then +if grep -Eq 'fun (confirm)?Apply(HostUsb|Docker)' "$actions"; then echo "USB and Docker must use the single global settings apply action" >&2 exit 1 fi -[[ "$(grep -Fc 'android:text="@string/dawnshell_host_usb_title"' "$layout")" -eq 1 ]] +[[ "$(grep -Fc 'R.string.dawnshell_host_usb_title' "$advanced_page")" -eq 1 ]] grep -Fq 'lsusb_legacy_sysfs_filter=enabled' "$usb_policy_script" grep -Fq '/rx_lanes:\ No\ such\ file\ or\ directory' "$usb_policy_script" grep -Fq '/tx_lanes:\ No\ such\ file\ or\ directory' "$usb_policy_script" diff --git a/scripts/test-croc-compatibility-wrapper.sh b/scripts/tests/host/test-croc-compatibility-wrapper.sh similarity index 97% rename from scripts/test-croc-compatibility-wrapper.sh rename to scripts/tests/host/test-croc-compatibility-wrapper.sh index 9acdd1b..e8caba6 100755 --- a/scripts/test-croc-compatibility-wrapper.sh +++ b/scripts/tests/host/test-croc-compatibility-wrapper.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" wrapper_source="$repo_dir/app/src/main/assets/bfu/dawnshell-croc.sh" configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" runtime_java="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuRuntime.java" diff --git a/scripts/tests/host/test-dashboard-settings-ux.sh b/scripts/tests/host/test-dashboard-settings-ux.sh new file mode 100755 index 0000000..7429dc2 --- /dev/null +++ b/scripts/tests/host/test-dashboard-settings-ux.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +kotlin_dir="$repo_dir/app/src/main/kotlin/me/aroxu/dawnshell" +boot_screen="$kotlin_dir/BootActivity.BootScreen.kt" +actions="$kotlin_dir/BootScreen.kt" +advanced_page="$kotlin_dir/BootActivity.BootScreen.ConfigurationPage.kt" +activity="$kotlin_dir/BootActivity.kt" +service="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuBootService.java" +guide="$repo_dir/docs/user-guide.md" + +grep -Fq 'private enum class DashboardPage { SETUP, HOME, ADVANCED }' "$boot_screen" +[[ "$(grep -Fc 'NavigationItem(page == DashboardPage.' "$boot_screen")" -eq 3 ]] +advanced_line="$(grep -nF 'AdvancedSection(navigate)' "$advanced_page" | cut -d: -f1)" +diagnostics_line="$(grep -nF 'DiagnosticsSection(navigate)' "$advanced_page" | cut -d: -f1)" +(( diagnostics_line > advanced_line )) + +# Pending settings are surfaced by one apply bar on the dashboard and on every detail page. +grep -Fq 'if (state.settingsDirty) ApplyBar(actions)' "$boot_screen" +grep -Fq 'if (s.settingsDirty) ApplyBar(a)' "$boot_screen" +[[ "$(grep -Fc 'actions::confirmApplySettings' "$boot_screen")" -eq 1 ]] + +if grep -Eq 'fun (confirm)?Apply(HostUsb|Docker|Cgroup)' "$actions"; then + echo "settings must not expose feature-specific apply actions" >&2 + exit 1 +fi + +grep -Fq 'SettingsSnapshot.fromPreferences(this)' "$activity" +grep -Fq 'requested.requiresRuntimeApply(previous)' "$activity" +grep -Fq 'BfuBootService.requestRuntimeSettingsApply(' "$activity" +[[ "$(grep -Fc 'savePreferences(requested)' "$activity")" -eq 1 ]] +if grep -Fq 'savePreferences()' "$activity"; then + echo "immediate command buttons must not silently apply pending settings" >&2 + exit 1 +fi +grep -Fq 'ACTION_APPLY_RUNTIME_SETTINGS' "$service" +grep -Fq 'HostUsbProvisioner.apply(this, layout)' "$service" +grep -Fq 'DockerNetworkProvisioner.apply(' "$service" +[[ "$(grep -Fc '"AFU_settings_apply"' "$service")" -eq 1 ]] +[[ "$(grep -Fc '"AFU_settings_applied"' "$service")" -eq 1 ]] + +grep -Fq '| **Home** |' "$guide" +grep -Fq 'global **Apply** bar' "$guide" + +echo "PASS: dashboard navigation and the single settings apply workflow are pinned." diff --git a/scripts/test-docker-ipc-wrapper.sh b/scripts/tests/host/test-docker-ipc-wrapper.sh similarity index 98% rename from scripts/test-docker-ipc-wrapper.sh rename to scripts/tests/host/test-docker-ipc-wrapper.sh index 6d187e9..0e5a58d 100755 --- a/scripts/test-docker-ipc-wrapper.sh +++ b/scripts/tests/host/test-docker-ipc-wrapper.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" policy_script="$repo_dir/app/src/main/assets/bfu/configure-docker-network.sh" temporary_dir="$(mktemp -d)" trap 'rm -rf -- "$temporary_dir"' EXIT diff --git a/scripts/test-documentation.py b/scripts/tests/host/test-documentation.py similarity index 99% rename from scripts/test-documentation.py rename to scripts/tests/host/test-documentation.py index 4dbb6e8..dd0faab 100644 --- a/scripts/test-documentation.py +++ b/scripts/tests/host/test-documentation.py @@ -10,7 +10,7 @@ import urllib.parse -REPO = pathlib.Path(__file__).resolve().parent.parent +REPO = pathlib.Path(__file__).resolve().parents[3] DOCS = REPO / "docs" ROOT_README = REPO / "README.md" ROOT_README_KO = REPO / "README.ko.md" diff --git a/scripts/test-documentation.sh b/scripts/tests/host/test-documentation.sh similarity index 70% rename from scripts/test-documentation.sh rename to scripts/tests/host/test-documentation.sh index cea4578..12b3253 100755 --- a/scripts/test-documentation.sh +++ b/scripts/tests/host/test-documentation.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" if [[ -n "${PYTHON:-}" ]]; then python_command="$PYTHON" @@ -14,4 +14,4 @@ else exit 127 fi -"$python_command" "$repo_dir/scripts/test-documentation.py" +"$python_command" "$repo_dir/scripts/tests/host/test-documentation.py" diff --git a/scripts/test-ffmpeg-bridge-plan.sh b/scripts/tests/host/test-ffmpeg-bridge-plan.sh similarity index 98% rename from scripts/test-ffmpeg-bridge-plan.sh rename to scripts/tests/host/test-ffmpeg-bridge-plan.sh index f2dc485..946d961 100755 --- a/scripts/test-ffmpeg-bridge-plan.sh +++ b/scripts/tests/host/test-ffmpeg-bridge-plan.sh @@ -3,7 +3,7 @@ # Android hardware codec and which fall back to plain FFmpeg. set -euo pipefail -repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" adapter="$repo_dir/app/src/main/assets/bfu/dawnshell-codec-ffmpeg.pl" wrapper_source="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" test -f "$adapter" @@ -249,8 +249,8 @@ while IFS= read -r pipeline_script; do echo "FAIL: $pipeline_script is committed as $mode; run git update-index --chmod=+x" >&2 exit 1 fi -done < <(grep -ho 'scripts/[a-z0-9-]*\.sh' \ - "$repo_dir/.github/workflows/build.yml" "$repo_dir/scripts/build-all.sh" \ +done < <(grep -ho 'scripts/[a-z0-9/-]*\.sh' \ + "$repo_dir/.github/workflows/build.yml" \ | sort -u) echo "PASS: FFmpeg bridge routes supported commands to hardware and falls back otherwise." diff --git a/scripts/test-gpu-status-tool.sh b/scripts/tests/host/test-gpu-status-tool.sh similarity index 99% rename from scripts/test-gpu-status-tool.sh rename to scripts/tests/host/test-gpu-status-tool.sh index da584ed..19c7bb2 100755 --- a/scripts/test-gpu-status-tool.sh +++ b/scripts/tests/host/test-gpu-status-tool.sh @@ -3,7 +3,7 @@ # that publishes different attribute names is caught before shipping. set -euo pipefail -repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" source_script="$repo_dir/app/src/main/assets/bfu/gsmi.sh" configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" test -f "$source_script" diff --git a/scripts/test-hardware-codec-bridge.sh b/scripts/tests/host/test-hardware-codec-bridge.sh similarity index 97% rename from scripts/test-hardware-codec-bridge.sh rename to scripts/tests/host/test-hardware-codec-bridge.sh index 7712f68..e4467db 100755 --- a/scripts/test-hardware-codec-bridge.sh +++ b/scripts/tests/host/test-hardware-codec-bridge.sh @@ -1,13 +1,14 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" client="$repo_dir/app/src/main/cpp/dawnshell_codec_client.c" worker="$repo_dir/app/src/main/cpp/dawnshell_codec_worker.c" ndk_codec="$repo_dir/app/src/main/cpp/dawnshell_codec_ndk.c" transport="$repo_dir/app/src/main/cpp/dawnshell_codec_transport.h" namespace_launcher="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" runtime="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuRuntime.java" +bfu_assets_dir="${DAWNSHELL_BFU_ASSETS_DIR:-$repo_dir/app/build/generated/assets/assembleBfuRuntimeAssets/bfu}" service="$repo_dir/app/src/main/java/me/aroxu/dawnshell/HardwareCodecService.java" configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" ffmpeg_adapter="$repo_dir/app/src/main/assets/bfu/dawnshell-codec-ffmpeg.pl" @@ -107,7 +108,7 @@ if [[ "$(uname -s)" == Linux* ]]; then fi for abi in armeabi-v7a arm64-v8a x86_64; do - directory="$repo_dir/app/src/main/assets/bfu/bin/$abi" + directory="$bfu_assets_dir/bin/$abi" test -s "$directory/dawnshell-codec" test -s "$directory/dawnshell-codec-worker" grep -Fqx 'dawnshell_codec_protocol=1' "$directory/runtime.properties" diff --git a/scripts/test-host-reboot-isolation.sh b/scripts/tests/host/test-host-reboot-isolation.sh similarity index 97% rename from scripts/test-host-reboot-isolation.sh rename to scripts/tests/host/test-host-reboot-isolation.sh index 7f40f9c..c35da73 100755 --- a/scripts/test-host-reboot-isolation.sh +++ b/scripts/tests/host/test-host-reboot-isolation.sh @@ -6,7 +6,7 @@ # the private PID namespace. set -euo pipefail -repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" launcher="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" test -f "$launcher" diff --git a/scripts/test-host-usb-policy.sh b/scripts/tests/host/test-host-usb-policy.sh similarity index 95% rename from scripts/test-host-usb-policy.sh rename to scripts/tests/host/test-host-usb-policy.sh index 88dda2c..5879494 100755 --- a/scripts/test-host-usb-policy.sh +++ b/scripts/tests/host/test-host-usb-policy.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" policy_script="$repo_dir/app/src/main/assets/bfu/configure-host-usb.sh" temporary_dir="$(mktemp -d)" trap 'rm -rf -- "$temporary_dir"' EXIT diff --git a/scripts/test-kernel-quirk-guards.sh b/scripts/tests/host/test-kernel-quirk-guards.sh similarity index 94% rename from scripts/test-kernel-quirk-guards.sh rename to scripts/tests/host/test-kernel-quirk-guards.sh index 08f0636..72dcf38 100755 --- a/scripts/test-kernel-quirk-guards.sh +++ b/scripts/tests/host/test-kernel-quirk-guards.sh @@ -13,7 +13,7 @@ # with ENOKEY and the manager stays degraded. set -euo pipefail -repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" guard_header="$repo_dir/app/src/main/cpp/dawnshell_close_range_guard.h" keyring_header="$repo_dir/app/src/main/cpp/dawnshell_keyring_guard.h" guard_source="$repo_dir/app/src/main/cpp/dawnshell_fdguard.c" @@ -22,7 +22,8 @@ configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" docker_network="$repo_dir/app/src/main/assets/bfu/configure-docker-network.sh" installer="$repo_dir/app/src/main/assets/bfu/install-debian-rootfs.sh" runtime="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuRuntime.java" -bootstrap_builder="$repo_dir/scripts/build-bootstrap-runtime.sh" +bootstrap_builder="$repo_dir/buildSrc/src/main/kotlin/me/aroxu/dawnshell/gradle/BfuRuntime.kt" +bfu_assets_dir="${DAWNSHELL_BFU_ASSETS_DIR:-$repo_dir/app/build/generated/assets/assembleBfuRuntimeAssets/bfu}" for required in "$guard_header" "$guard_source" "$launcher" "$configurator" \ "$docker_network" "$installer" "$runtime" "$bootstrap_builder" \ @@ -78,11 +79,11 @@ grep -Fq 'dawnshell-fdguard $BIN/chroot' "$installer" # The binary must be built for every supported ABI and provisioned to Device # Protected Storage. -grep -Fq 'build_fdguard' "$bootstrap_builder" +grep -Fq 'dawnshell_fdguard.c' "$bootstrap_builder" grep -Fq 'dawnshell-fdguard' "$runtime" for abi in armeabi-v7a arm64-v8a x86_64; do - binary="$repo_dir/app/src/main/assets/bfu/bin/$abi/dawnshell-fdguard" + binary="$bfu_assets_dir/bin/$abi/dawnshell-fdguard" test -s "$binary" # ELF magic keeps a stray text file from being shipped as an executable. magic="$(head -c 4 "$binary" | od -An -tx1 | tr -d ' \n')" diff --git a/scripts/test-lifecycle-control-policy.sh b/scripts/tests/host/test-lifecycle-control-policy.sh similarity index 90% rename from scripts/test-lifecycle-control-policy.sh rename to scripts/tests/host/test-lifecycle-control-policy.sh index 803785b..7729dcb 100755 --- a/scripts/test-lifecycle-control-policy.sh +++ b/scripts/tests/host/test-lifecycle-control-policy.sh @@ -1,12 +1,13 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" service="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BfuBootService.java" receiver="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BootReceiver.java" launcher="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" -activity="$repo_dir/app/src/main/java/me/aroxu/dawnshell/BootActivity.java" -layout="$repo_dir/app/src/main/res/layout/activity_boot.xml" +kotlin_dir="$repo_dir/app/src/main/kotlin/me/aroxu/dawnshell" +activity="$kotlin_dir/BootActivity.kt" +home_page="$kotlin_dir/BootActivity.BootScreen.HomePage.kt" grep -Fq 'lifecycleExecutor = Executors.newSingleThreadExecutor()' "$service" grep -Fq 'lifecycleFuture.cancel(true)' "$service" @@ -17,7 +18,7 @@ grep -Fq 'requestLifecycleOperation(DebianLauncher.Operation.START,' "$service" grep -Fq '"boot_completed_unlocked"' "$service" grep -Fq 'ACTION_DEBIAN_FORCE_STOP' "$service" grep -Fq 'DebianLauncher.Operation.FORCE_STOP' "$activity" -grep -Fq 'android:id="@+id/force_stop_debian_button"' "$layout" +grep -Fq 'a.confirmForceStop()' "$home_page" grep -Fq 'strcmp(argv[1], "force-stop")' "$launcher" grep -Fq 'refusing_to_kill_unverified_supervisor' "$launcher" grep -Fq 'verified_supervisor_is_not_session_leader' "$launcher" diff --git a/scripts/test-live-codec-pipeline.sh b/scripts/tests/host/test-live-codec-pipeline.sh similarity index 97% rename from scripts/test-live-codec-pipeline.sh rename to scripts/tests/host/test-live-codec-pipeline.sh index 13bb8fb..e1de61b 100755 --- a/scripts/test-live-codec-pipeline.sh +++ b/scripts/tests/host/test-live-codec-pipeline.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" adapter="$repo_dir/app/src/main/assets/bfu/dawnshell-codec-ffmpeg.pl" live_encoder="$repo_dir/app/src/main/assets/bfu/dawnshell-live-encode.sh" temporary="$(mktemp -d)" diff --git a/scripts/tests/host/test-namespace-probe-invariants.sh b/scripts/tests/host/test-namespace-probe-invariants.sh new file mode 100755 index 0000000..4f77e19 --- /dev/null +++ b/scripts/tests/host/test-namespace-probe-invariants.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Pins the safety invariants of the namespace/cgroup launcher source. +set -euo pipefail + +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +namespace_source="$repo_dir/app/src/main/cpp/bfu_namespace_probe.c" + +if grep -Eq 'unshare[[:space:]]*\([[:space:]]*CLONE_NEWIPC' "$namespace_source"; then + echo "Unsafe CLONE_NEWIPC call is forbidden on legacy 4.4-era kernels" >&2 + exit 6 +fi +for marker in \ + 'prepare_devices_cgroup_mount(control_dir, host_usb_policy)' \ + 'init_moved_to_devices_cgroup' \ + 'cgroup_view_devices_bind' \ + 'cleanup_cgroup_subtree_failed' \ + 'devices_cgroup=delegated' \ + 'prepare_unified_cgroup_mount(control_dir, host_usb_policy)' \ + 'cgroup_v2_device_bpf_verified' \ + 'BPF_F_ALLOW_MULTI' \ + 'command_moved_to_cgroup_v2_leaf' \ + 'cgroup_requested=auto' \ + 'fallback=v1' \ + 'cgroup_delegation=delegated' \ + 'CGROUP_POLICY_FORCE_V2' \ + 'CGROUP_POLICY_FORCE_V1' \ + 'HOST_USB_EXCLUSIVE' \ + 'reconcile_exclusive_usb' \ + 'restore_exclusive_usb' \ + 'exclusive_mode_requires_at_least_one_VID:PID'; do + grep -Fq "$marker" "$namespace_source" || { + echo "Missing namespace/cgroup invariant: $marker" >&2 + exit 7 + } +done +if grep -Eq 'uname[[:space:]]*\([^)]*-r|/proc/version' "$namespace_source"; then + echo "Cgroup selection must probe capabilities, not kernel version strings" >&2 + exit 8 +fi + +echo "PASS: namespace launcher invariants hold." diff --git a/scripts/test-native-output.sh b/scripts/tests/host/test-native-output.sh similarity index 83% rename from scripts/test-native-output.sh rename to scripts/tests/host/test-native-output.sh index 5c84a27..d0cc6c4 100755 --- a/scripts/test-native-output.sh +++ b/scripts/tests/host/test-native-output.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" work_dir="$(mktemp -d)" trap 'rm -rf -- "$work_dir"' EXIT diff --git a/scripts/test-release-compliance.sh b/scripts/tests/host/test-release-compliance.sh similarity index 97% rename from scripts/test-release-compliance.sh rename to scripts/tests/host/test-release-compliance.sh index 94cd815..4a5c4e6 100755 --- a/scripts/test-release-compliance.sh +++ b/scripts/tests/host/test-release-compliance.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" apk_path="${1:-}" required_licenses=( @@ -69,7 +69,6 @@ grep -Fxq 'CONFIG_FEATURE_STAT_FORMAT=y' \ grep -Fq "stat -c '%u:%g' \"\$TOOLBOX\"" \ "$repo_dir/app/src/main/assets/bfu/install-debian-rootfs.sh" -bash -n "$repo_dir/scripts/build-bootstrap-runtime.sh" bash -n "$repo_dir/scripts/package-release.sh" release_workflow="$repo_dir/.github/workflows/build.yml" diff --git a/scripts/test-rootfs-path-resolution.sh b/scripts/tests/host/test-rootfs-path-resolution.sh similarity index 95% rename from scripts/test-rootfs-path-resolution.sh rename to scripts/tests/host/test-rootfs-path-resolution.sh index a8715c3..2c27d08 100755 --- a/scripts/test-rootfs-path-resolution.sh +++ b/scripts/tests/host/test-rootfs-path-resolution.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" system_configurator="$repo_dir/app/src/main/assets/bfu/configure-debian-systemd.sh" docker_configurator="$repo_dir/app/src/main/assets/bfu/configure-docker-network.sh" host_usb_configurator="$repo_dir/app/src/main/assets/bfu/configure-host-usb.sh"