diff --git a/.clusterfuzzlite/Dockerfile b/.clusterfuzzlite/Dockerfile new file mode 100644 index 0000000..c33294b --- /dev/null +++ b/.clusterfuzzlite/Dockerfile @@ -0,0 +1,11 @@ +# Build image of the ClusterFuzzLite fuzzers (see build.sh). Pinned by digest; Dependabot or a manual bump +# moves it. tcl is needed to build the SQLite amalgamation, OpenSSL 3 is built by build.sh. +FROM gcr.io/oss-fuzz-base/base-builder@sha256:1f9cf74bc3d7029b528494542f9d9851b256dceed38d3f420989434dc5ae0760 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends tcl zip \ + && rm -rf /var/lib/apt/lists/* + +COPY . $SRC/sealite +WORKDIR $SRC/sealite +COPY .clusterfuzzlite/build.sh $SRC/build.sh diff --git a/.clusterfuzzlite/build.sh b/.clusterfuzzlite/build.sh new file mode 100755 index 0000000..4177a32 --- /dev/null +++ b/.clusterfuzzlite/build.sh @@ -0,0 +1,69 @@ +#!/bin/bash -eu +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 pasichdev +# +# Builds the libFuzzer target fuzz/sealite_fuzz.c against the SQLCipher amalgamation. ClusterFuzzLite +# provides CC, CFLAGS (sanitizer and coverage instrumentation), LIB_FUZZING_ENGINE, SRC and OUT. +# SQLCipher's and OpenSSL's versions and sha256 are read from the Gradle build so there is one place to +# bump them. OpenSSL 3 is built from source, statically, with the same instrumentation as the harness: the +# base image ships OpenSSL 1.1, which SQLCipher's provider (EVP_MAC) does not build against. Only the sha256 +# of the tarball is checked here, not the PGP signature the Gradle build also checks. + +set -eu +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)" +[ -f "$root/fuzz/sealite_fuzz.c" ] || root="$SRC/sealite" +build_file="$root/build-logic/src/main/kotlin/sealite.native.gradle.kts" +version="$(sed -n 's/^val sqlcipherVersion = "\(.*\)"/\1/p' "$build_file")" +sha256="$(sed -n 's/^val sqlcipherSha256 = "\(.*\)"/\1/p' "$build_file")" +cross_file="$root/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/SealiteCrossPlugin.kt" +ossl_version="$(sed -n 's/^ *val osslVersion = "\(.*\)"/\1/p' "$cross_file")" +ossl_sha256="$(sed -n 's/^ *val osslSha256 = "\(.*\)"/\1/p' "$cross_file")" +[ -n "$version" ] && [ -n "$sha256" ] && [ -n "$ossl_version" ] && [ -n "$ossl_sha256" ] + +work="$(mktemp -d)" +curl -fsSL -o "$work/sqlcipher.tar.gz" "https://github.com/sqlcipher/sqlcipher/archive/refs/tags/v${version}.tar.gz" +echo "${sha256} $work/sqlcipher.tar.gz" | sha256sum -c - +tar -xzf "$work/sqlcipher.tar.gz" -C "$work" + +curl -fsSL -o "$work/openssl.tar.gz" \ + "https://github.com/openssl/openssl/releases/download/openssl-${ossl_version}/openssl-${ossl_version}.tar.gz" +echo "${ossl_sha256} $work/openssl.tar.gz" | sha256sum -c - +tar -xzf "$work/openssl.tar.gz" -C "$work" +mkdir "$work/ossl" +( + cd "$work/ossl" + # Instrumented like the harness (CC and CFLAGS), static, only what SQLCipher's provider calls. + CC="$CC" CFLAGS="$CFLAGS" "$work/openssl-${ossl_version}/Configure" no-shared no-tests no-apps no-docs \ + no-module no-engine no-legacy no-ssl no-tls no-dtls no-quic no-comp no-autoload-config > configure.log + make -j"$(nproc)" build_libs > make.log +) +ossl_include=(-I "$work/openssl-${ossl_version}/include" -I "$work/ossl/include") + +mkdir "$work/bld" +( + cd "$work/bld" + # The sanitizer flags are for the objects we compile below, not for the build tools of the amalgamation. + CFLAGS= CXXFLAGS= LDFLAGS= "$work"/sqlcipher-*/configure --with-tempstore=yes CFLAGS=-DSQLITE_HAS_CODEC > configure.log + CFLAGS= CXXFLAGS= LDFLAGS= make sqlite3.c > make.log +) + +# The flags of the shipped library (NativeFlags.kt), without the progress handler switch (the harness +# uses it to stop runaway queries) and with the same threading mode. +defines=( + -DSQLITE_HAS_CODEC -DSQLCIPHER_CRYPTO_OPENSSL -DSQLITE_TEMP_STORE=3 -DSQLITE_THREADSAFE=2 + -DSQLITE_EXTRA_INIT=sqlcipher_extra_init -DSQLITE_EXTRA_SHUTDOWN=sqlcipher_extra_shutdown + -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_SECURE_DELETE + -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS5 + -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MATH_FUNCTIONS -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_STAT4 + -DSQLITE_ENABLE_COLUMN_METADATA -DSQLITE_ENABLE_NORMALIZE -DSQLITE_OMIT_DEPRECATED + -DSQLITE_OMIT_SHARED_CACHE -DSQLITE_HAVE_ISNAN -DHAVE_USLEEP=1 +) + +"$CC" $CFLAGS "${defines[@]}" -w -I "$work/bld" "${ossl_include[@]}" \ + "$root/fuzz/sealite_fuzz.c" "$work/bld/sqlite3.c" \ + $LIB_FUZZING_ENGINE "$work/ossl/libcrypto.a" -lpthread -ldl -lm -o "$OUT/sealite_fuzz" + +cp "$root/fuzz/sealite_fuzz.dict" "$OUT/sealite_fuzz.dict" +printf '[libfuzzer]\nmax_len = 4096\ntimeout = 20\n' > "$OUT/sealite_fuzz.options" +(cd "$root/fuzz/corpus" && zip -q -j "$OUT/sealite_fuzz_seed_corpus.zip" ./*) +rm -rf "$work" diff --git a/.clusterfuzzlite/project.yaml b/.clusterfuzzlite/project.yaml new file mode 100644 index 0000000..33ac971 --- /dev/null +++ b/.clusterfuzzlite/project.yaml @@ -0,0 +1,5 @@ +language: c +sanitizers: + - address + - undefined +main_repo: https://github.com/pasichDev/sealite diff --git a/.github/workflows/fuzz-batch.yml b/.github/workflows/fuzz-batch.yml new file mode 100644 index 0000000..c99a9c3 --- /dev/null +++ b/.github/workflows/fuzz-batch.yml @@ -0,0 +1,51 @@ +name: fuzz-batch + +# ClusterFuzzLite, batch mode: a longer weekly run of the same harness on main, for the inputs a +# five-minute pull-request run does not reach. The corpus is not stored between runs (that needs a +# separate repository and a token); every run starts from the seed corpus in fuzz/corpus. + +on: + schedule: + - cron: '17 3 * * 3' + workflow_dispatch: + +permissions: {} + +concurrency: + group: fuzz-batch + cancel-in-progress: false + +jobs: + fuzz: + name: fuzz (${{ matrix.sanitizer }}) + runs-on: ubuntu-24.04 + timeout-minutes: 90 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + sanitizer: [address, undefined] + steps: + - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build the fuzzers (${{ matrix.sanitizer }}) + id: build + uses: google/clusterfuzzlite/actions/build_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1 + with: + language: c + sanitizer: ${{ matrix.sanitizer }} + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Run the fuzzers (${{ matrix.sanitizer }}) + uses: google/clusterfuzzlite/actions/run_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fuzz-seconds: 3000 + mode: batch + sanitizer: ${{ matrix.sanitizer }} + report-unreproducible-crashes: false + output-sarif: false diff --git a/.github/workflows/fuzz-pr.yml b/.github/workflows/fuzz-pr.yml new file mode 100644 index 0000000..b37dd55 --- /dev/null +++ b/.github/workflows/fuzz-pr.yml @@ -0,0 +1,56 @@ +name: fuzz-pr + +# ClusterFuzzLite, code-change mode: fuzzes the SQLCipher harness (fuzz/sealite_fuzz.c) for a few minutes +# on pull requests that touch the native code or the fuzz setup, with AddressSanitizer and UBSan, and +# fails on a crash or a sanitizer finding. Kept out of ci.yml: it is not part of the required checks. + +on: + pull_request: + branches: [main] + paths: + - 'sealite/src/native/**' + - 'fuzz/**' + - '.clusterfuzzlite/**' + - 'build-logic/src/main/kotlin/sealite.native.gradle.kts' + - '.github/workflows/fuzz-pr.yml' + +permissions: {} + +concurrency: + group: fuzz-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + fuzz: + name: fuzz (${{ matrix.sanitizer }}) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + sanitizer: [address, undefined] + steps: + - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build the fuzzers (${{ matrix.sanitizer }}) + id: build + uses: google/clusterfuzzlite/actions/build_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1 + with: + language: c + sanitizer: ${{ matrix.sanitizer }} + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Run the fuzzers (${{ matrix.sanitizer }}) + uses: google/clusterfuzzlite/actions/run_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fuzz-seconds: 300 + mode: code-change + sanitizer: ${{ matrix.sanitizer }} + report-unreproducible-crashes: false + output-sarif: false diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml new file mode 100644 index 0000000..91173e2 --- /dev/null +++ b/.github/workflows/sanitizers.yml @@ -0,0 +1,79 @@ +name: sanitizers + +# Weekly run of the JVM tests against a JNI library built with AddressSanitizer (SQLCipher and the glue) +# and UBSan (the glue), on Linux x86-64: `jvmTestAsan`, see build-logic/.../sealite.asan.gradle.kts and +# CONTRIBUTING.md. Any finding stops the process and fails the job (halt_on_error, -fno-sanitize-recover), +# and the report is uploaded. Kept out of ci.yml: it is slow and not a required check. + +on: + schedule: + - cron: '47 2 * * 2' + workflow_dispatch: + +permissions: {} + +concurrency: + group: sanitizers + cancel-in-progress: false + +jobs: + asan: + name: asan + ubsan (linux-x64) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + permissions: + contents: read + steps: + - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: ${{ github.ref != 'refs/heads/main' }} + # clang 18 explicitly (the one Ubuntu 24.04 ships), and put it first on the PATH as plain `clang`, + # which is the name the Gradle task calls: the runner image may carry another default. + - name: Install clang 18, its sanitizer runtime, the OpenSSL headers and the tools that build SQLCipher + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends clang-18 libclang-rt-18-dev libssl-dev make tcl + mkdir -p "${RUNNER_TEMP}/toolchain" + ln -s /usr/bin/clang-18 "${RUNNER_TEMP}/toolchain/clang" + echo "${RUNNER_TEMP}/toolchain" >> "$GITHUB_PATH" + "${RUNNER_TEMP}/toolchain/clang" --version + # The shipped natives come from the Mac job and are not used here: an empty prebuilt layout only + # keeps Gradle from trying to build them. The sanitizer library is built on this host. + - name: Tests against the sanitizer build + timeout-minutes: 50 + env: + PREBUILT: ${{ runner.temp }}/no-natives + run: | + mkdir -p "${PREBUILT}/jvm/natives" + ./gradlew :sealite:jvmTestAsan -Psealite.prebuiltNatives="${PREBUILT}" --stacktrace + # With log_path set, a finding is written to asan. next to the test reports, so a red job + # always has the report to read. + - name: A finding fails the job even if Gradle did not + if: always() + run: | + if compgen -G "sealite/build/reports/asan/asan.*" > /dev/null; then + echo "::error::a sanitizer report was written" + head -n 80 sealite/build/reports/asan/asan.* + exit 1 + fi + - name: Upload reports + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: reports-sanitizers + path: | + sealite/build/reports/asan + sealite/build/reports/tests + sealite/build/test-results + if-no-files-found: ignore + retention-days: 14 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5f7195b..fc3740d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -94,6 +94,44 @@ The Kotlin library code must stay at **100 % line and branch coverage** of the J against it and writes line and branch coverage of `sealite_jni.c` and `sealite_key.c` (not the SQLCipher amalgamation) to `sealite/build/reports/c-coverage/`. +### Sanitizers and fuzzing + +Two checks look for memory errors in the C code. Neither is part of `ci.yml` or of the required checks. + +**Sanitizer run** (`sanitizers.yml`, every Tuesday and on demand; locally `./gradlew :sealite:jvmTestAsan`, +on a Mac with no other setup, on Linux with `-Psealite.prebuiltNatives=` where `/jvm/natives` +may be empty). It builds the SQLCipher amalgamation and the JNI glue with AddressSanitizer, builds our own +C (`sealite/src/native/jni`) also with UBSan (`-fno-sanitize-recover`), preloads the sanitizer runtime into +the JVM and runs the whole JVM test suite against that library, including the boundary tests +(`BoundaryInputTest`, `CloseRaceTest`: invalid SQL, U+0000, unpaired surrogates, empty and multi-megabyte +values, long paths, statement and connection misuse, close racing prepare and step). A finding stops the +process and fails the job; the report is uploaded as `reports-sanitizers`. + +What it covers: use-after-free, overflows and leaks of the glue and of SQLCipher/SQLite on Linux x86-64 +(and, locally, macOS arm64); undefined behaviour in the glue; every code path the shared tests reach. + +What it does not cover: + +- the shipped libraries are different builds: Windows, Android and Apple code, CommonCrypto, the static + OpenSSL of the release libraries and the Kotlin/Native bindings (`NativeRawDb`, `NativeStatement`) are not + sanitized. On Linux the system OpenSSL is linked and is not instrumented; +- UBSan is off for the SQLite amalgamation, which trips it by design (for example a signed overflow when + a statement is bound at index `Int.MIN_VALUE`, wrapped before SQLite's own range check); +- leak detection is off (the JVM would report its own allocations); +- the tests choose the inputs: the sanitizer finds what they reach. The fuzzer below picks its own; +- Java and Kotlin memory safety, and races between threads (no ThreadSanitizer run). + +**Fuzzing** (`fuzz-pr.yml`, `fuzz-batch.yml`; ClusterFuzzLite). `fuzz/sealite_fuzz.c` is a libFuzzer harness +for the C layer without the JVM: it opens a temporary or in-memory SQLCipher database, keys it the way the +library does (compatibility, KDF iterations, page size, key and rekey from the input), and prepares and +steps SQL from the input with bound text, text16 and blob values. Pull requests that touch the native code +fuzz for five minutes with AddressSanitizer and with UBSan; a weekly batch runs 50 minutes. The seed corpus +is `fuzz/corpus`; the corpus found by a run is not stored between runs. Reproduce a crash with the +`.clusterfuzzlite/build.sh` build (see the file for the variables it reads) and run the binary on the +crashing input. A crash that is a bug of ours becomes a test in `BoundaryInputTest`; one in SQLite or +SQLCipher goes upstream. The harness covers the SQLCipher layer, not the JNI glue (`sealite_jni.c`), +which needs a JVM and is covered by the sanitizer run. + ## Before you open a pull request ```sh @@ -133,6 +171,8 @@ ci.yml (pull requests, main) `- ci-ok fails unless every job above succeeded pr-title.yml the pull request title is a Conventional Commit codeql.yml CodeQL for the C glue +sanitizers.yml weekly: the JVM tests against an ASan + UBSan build (Linux) +fuzz-pr.yml, fuzz-batch.yml ClusterFuzzLite: the SQLCipher harness, five minutes per pull request, weekly batch security.yml zizmor, the linter for the workflows themselves scorecard.yml OpenSSF Scorecard release-please.yml, release.yml see Releases diff --git a/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/BuildJniLibraryTask.kt b/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/BuildJniLibraryTask.kt index 930bfab..5f4c0de 100644 --- a/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/BuildJniLibraryTask.kt +++ b/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/BuildJniLibraryTask.kt @@ -92,12 +92,20 @@ abstract class BuildJniLibraryTask val jniIncludes = listOf(jdk.resolve("include"), jdk.resolve("include").resolve(jniIncludeSubdir.get())) jniIncludes.forEach { if (!it.isDirectory) throw GradleException("No JNI headers at $it") } - val sysroot = capture("xcrun", "--sdk", "macosx", "--show-sdk-path").trim() - val common = - listOf("clang") + targetArgs.get() + + // An Apple SDK on a Mac; the system headers on a Linux host (the sanitizer build). + val mac = System.getProperty("os.name").startsWith("Mac") + val sysrootArgs = + if (mac) { listOf( "-isysroot", - sysroot, + capture("xcrun", "--sdk", "macosx", "--show-sdk-path").trim(), + ) + } else { + emptyList() + } + val common = + listOf("clang") + targetArgs.get() + sysrootArgs + + listOf( "-fvisibility=hidden", "-fPIC", "-include", @@ -163,7 +171,8 @@ abstract class BuildJniLibraryTask commandLine( listOf( "clang", - ) + targetArgs.get() + listOf("-isysroot", sysroot, "-dynamiclib", "-fvisibility=hidden") + + ) + targetArgs.get() + sysrootArgs + + listOf(if (mac) "-dynamiclib" else "-shared", "-fvisibility=hidden") + objects.map { it.absolutePath } + linkArgs.get() + listOf("-o", lib.absolutePath), ) } diff --git a/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/GenerateRenameHeaderTask.kt b/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/GenerateRenameHeaderTask.kt index c37648c..3423937 100644 --- a/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/GenerateRenameHeaderTask.kt +++ b/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/GenerateRenameHeaderTask.kt @@ -53,29 +53,46 @@ abstract class GenerateRenameHeaderTask @TaskAction fun run() { - if (!System.getProperty("os.name").startsWith("Mac")) { + val osName = System.getProperty("os.name") + val mac = osName.startsWith("Mac") + // Linux hosts build the sanitizer library only (sealite.asan); the shipped ones come from a Mac. + if (!mac && osName != "Linux") { throw GradleException( "Building the Sealite natives needs macOS (Xcode's clang and SDK); this host is " + - "${System.getProperty("os.name")}. Pass -Psealite.prebuiltNatives= with the output " + + "$osName. Pass -Psealite.prebuiltNatives= with the output " + "of ':sealite:collectNativesForCi' (the 'natives' artifact of the CI) to use prebuilt libraries.", ) } val dir = amalgamationDir.get().asFile val work = workDir.get().asFile.also { it.mkdirs() } val probe = work.resolve("probe.o") - val sdk = ByteArrayOutputStream() - exec.exec { - commandLine("xcrun", "--sdk", "macosx", "--show-sdk-path") - standardOutput = sdk - } - val compileArgs = - listOf("clang") + compilerArgs.get() + listOf("-isysroot", sdk.toString().trim()) + - compilerFlags.get() + val sdkArgs = + if (mac) { + val sdk = ByteArrayOutputStream() + exec.exec { + commandLine("xcrun", "--sdk", "macosx", "--show-sdk-path") + standardOutput = sdk + } + listOf("-isysroot", sdk.toString().trim()) + } else { + emptyList() + } + val compileArgs = listOf("clang") + compilerArgs.get() + sdkArgs + compilerFlags.get() val sourceArgs = listOf("-O0", "-w", "-c", dir.resolve("sqlite3.c").absolutePath) exec.exec { commandLine(compileArgs + sourceArgs + listOf("-o", probe.absolutePath)) } val nmOut = ByteArrayOutputStream() exec.exec { - commandLine("nm", "-gU", probe.absolutePath) + commandLine( + if (mac) { + listOf( + "nm", + "-gU", + probe.absolutePath, + ) + } else { + listOf("nm", "-g", "--defined-only", probe.absolutePath) + }, + ) standardOutput = nmOut } // Mach-O symbols carry a leading underscore. @@ -89,7 +106,7 @@ abstract class GenerateRenameHeaderTask .split(Regex("\\s+")) .takeIf { p -> p.size >= 3 } ?.last() - }.map { it.removePrefix("_") } + }.map { if (mac) it.removePrefix("_") else it } .toSet() val apiDeclaration = diff --git a/build-logic/src/main/kotlin/sealite.asan.gradle.kts b/build-logic/src/main/kotlin/sealite.asan.gradle.kts index d3c022b..78ec23e 100644 --- a/build-logic/src/main/kotlin/sealite.asan.gradle.kts +++ b/build-logic/src/main/kotlin/sealite.asan.gradle.kts @@ -1,63 +1,91 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2026 pasichdev -// Convention plugin `sealite.asan`: an opt-in, local run of the JVM tests against a macOS JNI library -// built with AddressSanitizer (the SQLCipher amalgamation and the glue). Not part of `check` or CI. +// Convention plugin `sealite.asan`: an opt-in run of the JVM tests against a JNI library built with +// AddressSanitizer (the SQLCipher amalgamation and the glue) and, for our own C only, UBSan. Not part of +// `check` or the pull-request pipeline; the weekly sanitizers workflow runs it on Linux. // -// ./gradlew :sealite:jvmTestAsan +// ./gradlew :sealite:jvmTestAsan (macOS arm64, no other setup) +// ./gradlew :sealite:jvmTestAsan -Psealite.prebuiltNatives= (Linux; /jvm/natives may be empty) // -// Catches use-after-free and overflows in the native glue and in SQLite itself. The JVM is started with -// the ASan runtime preloaded (DYLD_INSERT_LIBRARIES). Needs a Mac whose CPU is arm64. Apply after -// `sealite.native`. +// Catches use-after-free and overflows in the native glue and in SQLite itself, and undefined behaviour in +// the glue. The JVM is started with the sanitizer runtime preloaded (DYLD_INSERT_LIBRARIES on macOS, +// LD_PRELOAD on Linux). macOS needs an arm64 Mac (CommonCrypto); Linux needs clang, its compiler-rt +// (libclang-rt-dev) and the OpenSSL headers (libssl-dev), and builds with the system OpenSSL, which is +// not itself sanitized. Apply after `sealite.native`. import io.github.pasichdev.sealite.build.BuildJniLibraryTask import io.github.pasichdev.sealite.build.FetchSqlCipherTask import io.github.pasichdev.sealite.build.GenerateRenameHeaderTask import io.github.pasichdev.sealite.build.NativeFlags -val isMac = System.getProperty("os.name").lowercase().contains("mac") +val osName = System.getProperty("os.name").lowercase() +val isMac = osName.contains("mac") +val isLinux = osName.contains("linux") val prebuilt = providers.gradleProperty("sealite.prebuiltNatives").isPresent -if (isMac && !prebuilt) { +// On a Mac the natives are built here, so prebuilt ones mean this is not a local run. On Linux the +// shipped natives are never built (they come from the Mac job), so prebuilt is the normal setup. +if ((isMac && !prebuilt) || isLinux) { val nativeBuild = layout.buildDirectory.dir("native") val reportDir = layout.buildDirectory.dir("reports/asan") val sanitizer = listOf("-fsanitize=address", "-fno-omit-frame-pointer", "-g") + // UBSan on our own C only: the SQLite amalgamation trips it (signed overflow in sqlite3.c, upstream). + // No recovery: the first finding aborts the process, so the run fails. + val ubsan = listOf("-fsanitize=undefined", "-fno-sanitize-recover=all") + val libName = if (isMac) "libsealite_jni.dylib" else "libsealite_jni.so" + val dirName = if (isMac) "macos_arm64_asan" else "linux_asan" val buildAsan = - tasks.register("buildNativeMacosArm64Asan") { + tasks.register("buildNative${if (isMac) "MacosArm64" else "Linux"}Asan") { group = "verification" - description = "Builds libsealite_jni.dylib with AddressSanitizer." + description = "Builds $libName with AddressSanitizer (and UBSan in the glue)." amalgamationDir.set(tasks.named("fetchSqlCipher").flatMap { it.amalgamationDir }) renameHeader.set(tasks.named("generateRenameHeader").flatMap { it.header }) glueDir.set(layout.projectDirectory.dir("src/native/jni")) jdkHome.set(System.getProperty("java.home")) - jniIncludeSubdir.set("darwin") - libName.set("libsealite_jni.dylib") - targetArgs.set(listOf("--target=arm64-apple-macosx11.0")) + jniIncludeSubdir.set(if (isMac) "darwin" else "linux") + this.libName.set(libName) + if (isMac) targetArgs.set(listOf("--target=arm64-apple-macosx11.0")) amalgamationFlags.set( - NativeFlags.amalgamation("SQLCIPHER_CRYPTO_CC") + + NativeFlags.amalgamation(if (isMac) "SQLCIPHER_CRYPTO_CC" else "SQLCIPHER_CRYPTO_OPENSSL") + "-DSQLITE_EXTRA_INIT=sqlcipher_extra_init" + sanitizer, ) + glueFlags.set(ubsan) glueOptimization.set("-O1") linkArgs.set( - listOf( - "-framework", - "Security", - "-framework", - "CoreFoundation", - "-Wl,-install_name,@rpath/libsealite_jni.dylib", - "-fsanitize=address", - ), + if (isMac) { + listOf( + "-framework", + "Security", + "-framework", + "CoreFoundation", + "-Wl,-install_name,@rpath/libsealite_jni.dylib", + "-fsanitize=address,undefined", + ) + } else { + // The runtime is not linked into the library: the JVM preloads it (shared-libsan). + listOf("-fsanitize=address", "-shared-libsan", "-lcrypto") + }, ) - workDir.set(nativeBuild.map { it.dir("macos_arm64_asan-obj") }) - outputDir.set(nativeBuild.map { it.dir("macos_arm64_asan") }) + workDir.set(nativeBuild.map { it.dir("$dirName-obj") }) + outputDir.set(nativeBuild.map { it.dir(dirName) }) } - val asanLibrary = buildAsan.flatMap { it.outputDir.file("libsealite_jni.dylib") } + val asanLibrary = buildAsan.flatMap { it.outputDir.file(libName) } + + fun capture(vararg command: String): String = + ProcessBuilder(*command).redirectErrorStream(false).start().let { process -> + process.inputStream + .bufferedReader() + .readText() + .trim() + .also { process.waitFor() } + } tasks.register("jvmTestAsan") { group = "verification" - description = "The JVM tests against the AddressSanitizer JNI library (opt-in, local, not gated)." + description = "The JVM tests against the sanitizer-built JNI library (opt-in, not gated by check)." val jvmTest = tasks.named("jvmTest").get() testClassesDirs = jvmTest.testClassesDirs classpath = jvmTest.classpath @@ -69,38 +97,28 @@ if (isMac && !prebuilt) { // The sanitizer runtime must be loaded before the JVM maps its first allocation. jvmArgs("-Xshare:off") doFirst { - val runtime = - ProcessBuilder("xcrun", "clang", "--print-file-name=libclang_rt.asan_osx_dynamic.dylib") - .start() - .inputStream - .bufferedReader() - .readText() - .trim() - check(File(runtime).isFile) { "no ASan runtime at '$runtime'" } - // dyld refuses the toolchain's signature inside a hardened JVM ("Sanitizer load violates - // platform policy"): preload an ad-hoc signed copy instead. - val preload = - reportDir - .get() - .asFile - .also { it.mkdirs() } - .resolve("libclang_rt.asan_osx_dynamic.dylib") - File(runtime).copyTo(preload, overwrite = true) - check(ProcessBuilder("codesign", "-f", "-s", "-", preload.path).inheritIO().start().waitFor() == 0) { - "codesign of the ASan runtime failed" + val report = reportDir.get().asFile.also { it.mkdirs() } + val options = + "detect_leaks=0:halt_on_error=1:abort_on_error=0:log_path=" + report.resolve("asan").absolutePath + if (isMac) { + val runtime = capture("xcrun", "clang", "--print-file-name=libclang_rt.asan_osx_dynamic.dylib") + check(File(runtime).isFile) { "no ASan runtime at '$runtime'" } + // dyld refuses the toolchain's signature inside a hardened JVM ("Sanitizer load violates + // platform policy"): preload an ad-hoc signed copy instead. + val preload = report.resolve("libclang_rt.asan_osx_dynamic.dylib") + File(runtime).copyTo(preload, overwrite = true) + check(ProcessBuilder("codesign", "-f", "-s", "-", preload.path).inheritIO().start().waitFor() == 0) { + "codesign of the ASan runtime failed" + } + environment("DYLD_INSERT_LIBRARIES", preload.path) + } else { + val arch = if (System.getProperty("os.arch") == "aarch64") "aarch64" else "x86_64" + val runtime = capture("clang", "--print-file-name=libclang_rt.asan-$arch.so") + check(File(runtime).isFile) { "no ASan runtime at '$runtime' (install libclang-rt-dev)" } + environment("LD_PRELOAD", runtime) } systemProperty("sealite.library.path", asanLibrary.get().asFile.absolutePath) - reportDir.get().asFile.mkdirs() - environment("DYLD_INSERT_LIBRARIES", preload.path) - environment( - "ASAN_OPTIONS", - "detect_leaks=0:halt_on_error=1:abort_on_error=0:log_path=" + - reportDir - .get() - .asFile - .resolve("asan") - .absolutePath, - ) + environment("ASAN_OPTIONS", options) } } } diff --git a/build-logic/src/main/kotlin/sealite.native.gradle.kts b/build-logic/src/main/kotlin/sealite.native.gradle.kts index 7b75ca5..4ecc62a 100644 --- a/build-logic/src/main/kotlin/sealite.native.gradle.kts +++ b/build-logic/src/main/kotlin/sealite.native.gradle.kts @@ -60,8 +60,10 @@ val generateRenameHeader = group = "native" description = "Generates sealite_rename.h (sqlite3_* / sqlcipher_* -> sealite_*)." amalgamationDir.set(fetchSqlCipher.flatMap { it.amalgamationDir }) - compilerArgs.set(listOf("--target=arm64-apple-macosx11.0")) - compilerFlags.set(NativeFlags.amalgamation("SQLCIPHER_CRYPTO_CC") + "-DSQLITE_EXTRA_INIT=sqlcipher_extra_init") + compilerArgs.set(if (appleHost) listOf("--target=arm64-apple-macosx11.0") else emptyList()) + // The probe only needs the declarations; a Linux host (the sanitizer build) has OpenSSL, not CommonCrypto. + val probeCrypto = if (appleHost) "SQLCIPHER_CRYPTO_CC" else "SQLCIPHER_CRYPTO_OPENSSL" + compilerFlags.set(NativeFlags.amalgamation(probeCrypto) + "-DSQLITE_EXTRA_INIT=sqlcipher_extra_init") prefix.set("sealite_") workDir.set(nativeBuild.map { it.dir("rename-probe") }) header.set(nativeBuild.map { it.file("generated/sealite_rename.h") }) diff --git a/fuzz/corpus/create_insert_select b/fuzz/corpus/create_insert_select new file mode 100644 index 0000000..d053792 Binary files /dev/null and b/fuzz/corpus/create_insert_select differ diff --git a/fuzz/corpus/in_memory_no_key b/fuzz/corpus/in_memory_no_key new file mode 100644 index 0000000..a029b6d Binary files /dev/null and b/fuzz/corpus/in_memory_no_key differ diff --git a/fuzz/corpus/invalid_sql b/fuzz/corpus/invalid_sql new file mode 100644 index 0000000..02aed9e Binary files /dev/null and b/fuzz/corpus/invalid_sql differ diff --git a/fuzz/corpus/json_fts5 b/fuzz/corpus/json_fts5 new file mode 100644 index 0000000..282b768 Binary files /dev/null and b/fuzz/corpus/json_fts5 differ diff --git a/fuzz/corpus/nul_and_surrogates b/fuzz/corpus/nul_and_surrogates new file mode 100644 index 0000000..f4ec3fa Binary files /dev/null and b/fuzz/corpus/nul_and_surrogates differ diff --git a/fuzz/corpus/recursive_cte b/fuzz/corpus/recursive_cte new file mode 100644 index 0000000..8afbf97 Binary files /dev/null and b/fuzz/corpus/recursive_cte differ diff --git a/fuzz/corpus/rekey_and_pragmas b/fuzz/corpus/rekey_and_pragmas new file mode 100644 index 0000000..83ec6a3 Binary files /dev/null and b/fuzz/corpus/rekey_and_pragmas differ diff --git a/fuzz/sealite_fuzz.c b/fuzz/sealite_fuzz.c new file mode 100644 index 0000000..f783d31 --- /dev/null +++ b/fuzz/sealite_fuzz.c @@ -0,0 +1,219 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +/* Copyright 2026 pasichdev */ + +/* + * libFuzzer harness for the part of Sealite that is C: SQLCipher keyed the way the library keys it, + * then SQL, bound text and bound blobs taken from the input. No JNI and no JVM, so it builds and runs + * anywhere clang and libFuzzer do (ClusterFuzzLite, see .clusterfuzzlite/ and docs in CONTRIBUTING.md). + * + * Input layout (every field is optional; a short input reads as zeros): + * byte 0 open flags: bit 0 in-memory database, bit 1 skip the key, bit 2 rekey with the same key + * byte 1 cipher_compatibility: 0 = default, 1 to 4 = SQLCipher 1 to 4 + * byte 2 cipher_page_size selector (index into kPageSizes, 0 = default) + * byte 3 key length (0 to 64), then that many key bytes + * byte ... parameter count (0 to 8); per parameter one kind byte, a length byte and the bytes + * rest the SQL text + * + * Bounded on purpose: key derivation runs with one iteration, the SQL is capped, a progress handler + * interrupts runaway queries, ATTACH is refused, and the heap is limited. + */ +#include +#include +#include +#include +#include + +#include "sqlite3.h" + +#define MAX_SQL 4096 +#define MAX_STATEMENTS 8 +#define MAX_ROWS 64 +#define MAX_PARAMS 8 +#define OPS_PER_STATEMENT 20000 + +static const int kPageSizes[] = {0, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536}; + +typedef struct { + const uint8_t *data; + size_t size; + size_t at; +} Reader; + +static uint8_t read_byte(Reader *r) { + return r->at < r->size ? r->data[r->at++] : 0; +} + +static size_t read_bytes(Reader *r, size_t want, const uint8_t **out) { + size_t left = r->size - r->at; + size_t n = want < left ? want : left; + *out = r->data + r->at; + r->at += n; + return n; +} + +static int deny_attach(void *arg, int action, const char *a, const char *b, const char *c, const char *d) { + (void) arg; + (void) a; + (void) b; + (void) c; + (void) d; + return action == SQLITE_ATTACH ? SQLITE_DENY : SQLITE_OK; +} + +static int too_long(void *counter) { + return ++*(int *) counter > OPS_PER_STATEMENT; +} + +static void exec_quiet(sqlite3 *db, const char *sql) { + sqlite3_exec(db, sql, NULL, NULL, NULL); +} + +static void run_statement(sqlite3_stmt *stmt, const uint8_t *kinds, const uint8_t *lengths, + const uint8_t *const *values, int param_count) { + int slots = sqlite3_bind_parameter_count(stmt); + for (int i = 1; i <= slots; i++) { + int p = (i - 1) % (param_count > 0 ? param_count : 1); + if (param_count == 0) { + sqlite3_bind_null(stmt, i); + continue; + } + switch (kinds[p] % 5) { + case 0: + sqlite3_bind_null(stmt, i); + break; + case 1: + sqlite3_bind_int64(stmt, i, (sqlite3_int64) lengths[p] * 0x0101010101010101LL); + break; + case 2: + sqlite3_bind_blob(stmt, i, values[p], lengths[p], SQLITE_TRANSIENT); + break; + case 3: + sqlite3_bind_text(stmt, i, (const char *) values[p], lengths[p], SQLITE_TRANSIENT); + break; + default: + sqlite3_bind_text16(stmt, i, values[p], lengths[p] & ~1, SQLITE_TRANSIENT); + break; + } + } + for (int row = 0; row < MAX_ROWS && sqlite3_step(stmt) == SQLITE_ROW; row++) { + int columns = sqlite3_column_count(stmt); + for (int c = 0; c < columns; c++) { + switch (sqlite3_column_type(stmt, c)) { + case SQLITE_BLOB: + (void) sqlite3_column_blob(stmt, c); + (void) sqlite3_column_bytes(stmt, c); + break; + case SQLITE_TEXT: + (void) sqlite3_column_text16(stmt, c); + (void) sqlite3_column_bytes16(stmt, c); + (void) sqlite3_column_text(stmt, c); + break; + default: + (void) sqlite3_column_int64(stmt, c); + (void) sqlite3_column_double(stmt, c); + break; + } + } + } + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); +} + +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + static int initialized = 0; + if (!initialized) { + sqlite3_initialize(); + sqlite3_config(SQLITE_CONFIG_LOG, NULL, NULL); + sqlite3_hard_heap_limit64(256 * 1024 * 1024); + initialized = 1; + } + Reader r = {data, size, 0}; + uint8_t flags = read_byte(&r); + uint8_t compatibility = read_byte(&r); + uint8_t page_size = read_byte(&r); + uint8_t key_length = read_byte(&r) % 65; + const uint8_t *key; + size_t key_size = read_bytes(&r, key_length, &key); + + int param_count = read_byte(&r) % (MAX_PARAMS + 1); + uint8_t kinds[MAX_PARAMS] = {0}; + uint8_t lengths[MAX_PARAMS] = {0}; + const uint8_t *values[MAX_PARAMS] = {0}; + for (int i = 0; i < param_count; i++) { + kinds[i] = read_byte(&r); + size_t want = read_byte(&r); + lengths[i] = (uint8_t) read_bytes(&r, want, &values[i]); + } + const uint8_t *sql_bytes; + size_t sql_size = read_bytes(&r, MAX_SQL, &sql_bytes); + char *sql = (char *) malloc(sql_size + 1); + if (sql == NULL) return 0; + memcpy(sql, sql_bytes, sql_size); + sql[sql_size] = '\0'; + + char path[64] = ":memory:"; + int on_disk = !(flags & 1); + if (on_disk) { + snprintf(path, sizeof path, "/tmp/sealite-fuzz-%d.db", (int) getpid()); + unlink(path); + } + sqlite3 *db = NULL; + if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) != SQLITE_OK) { + sqlite3_close_v2(db); + free(sql); + return 0; + } + sqlite3_set_authorizer(db, deny_attach, NULL); + sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1 << 20); + sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, MAX_SQL); + int ops = 0; + sqlite3_progress_handler(db, 100, too_long, &ops); + + /* No fsync per input: durability is not under test, speed is. */ + exec_quiet(db, "PRAGMA synchronous = OFF"); + + /* The order the library uses (OpenSequence): key first (SQLCipher derives it lazily, at the first page + * access), then compatibility, overrides and memory security. */ + if (!(flags & 2) && key_size > 0) sqlite3_key_v2(db, "main", key, (int) key_size); + if (compatibility % 5 != 0) { + char pragma[64]; + snprintf(pragma, sizeof pragma, "PRAGMA cipher_compatibility = %d", compatibility % 5); + exec_quiet(db, pragma); + } + exec_quiet(db, "PRAGMA kdf_iter = 1"); + if (page_size % 9 != 0) { + char pragma[64]; + snprintf(pragma, sizeof pragma, "PRAGMA cipher_page_size = %d", kPageSizes[page_size % 9]); + exec_quiet(db, pragma); + } + exec_quiet(db, "PRAGMA cipher_memory_security = ON"); + if ((flags & 4) && !(flags & 2) && key_size > 0) sqlite3_rekey_v2(db, "main", key, (int) key_size); + + const char *tail = sql; + for (int n = 0; n < MAX_STATEMENTS && *tail != '\0'; n++) { + sqlite3_stmt *stmt = NULL; + const char *next = NULL; + ops = 0; + if (sqlite3_prepare_v2(db, tail, -1, &stmt, &next) != SQLITE_OK) break; + if (stmt != NULL) { + run_statement(stmt, kinds, lengths, values, param_count); + sqlite3_finalize(stmt); + } + if (next == NULL || next <= tail) break; + tail = next; + } + + sqlite3_close_v2(db); + if (on_disk) { + char side[80]; + unlink(path); + snprintf(side, sizeof side, "%s-journal", path); + unlink(side); + snprintf(side, sizeof side, "%s-wal", path); + unlink(side); + snprintf(side, sizeof side, "%s-shm", path); + unlink(side); + } + free(sql); + return 0; +} diff --git a/fuzz/sealite_fuzz.dict b/fuzz/sealite_fuzz.dict new file mode 100644 index 0000000..3c6f860 --- /dev/null +++ b/fuzz/sealite_fuzz.dict @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: Apache-2.0 +# Tokens for the SQL part of the input. +"SELECT " +"INSERT INTO " +"CREATE TABLE " +"CREATE VIRTUAL TABLE " +"PRAGMA " +"cipher_integrity_check" +"cipher_compatibility" +"cipher_page_size" +"kdf_iter" +"WITH RECURSIVE " +"UNION ALL " +"zeroblob(" +"randomblob(" +"hex(" +"json_extract(" +"fts5(" +" MATCH " +"BEGIN;" +"COMMIT;" +"ROLLBACK;" +"?1" +"?2" +":a" +"x'00'" +"NULL" +"'\\x00'" diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/BoundaryInputTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/BoundaryInputTest.kt new file mode 100644 index 0000000..92cb11a --- /dev/null +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/BoundaryInputTest.kt @@ -0,0 +1,640 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 pasichdev + +package io.github.pasichdev.sealite + +import androidx.sqlite.SQLiteException +import io.github.pasichdev.sealite.internal.RawDb +import io.github.pasichdev.sealite.internal.exec +import io.github.pasichdev.sealite.internal.rawOpen +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Hostile input across the native boundary: invalid and odd SQL, U+0000, unpaired surrogates, empty + * and large values, paths that can not be opened. Whatever goes in, the answer is a value or a + * [SQLiteException], never a crash and never a corrupted neighbour. The loops use fixed seeds and are + * short; a seed that ever fails is added here as its own test. + */ +class BoundaryInputTest { + private val flags = 0x02 or 0x04 // READWRITE | CREATE + + // Unit, not a generic result: test functions written as `= withRawDb { ... }` must return Unit, + // which Kotlin/Native and JUnit 4 on Android enforce (the JVM runner does not). + private fun withRawDb(block: (RawDb) -> Unit) { + val db = rawOpen(":memory:", flags) + try { + block(db) + } finally { + db.close() + } + } + + private fun RawDb.stillWorks() { + prepare("SELECT 40 + 2").use { + assertTrue(it.step()) + assertEquals(42L, it.getLong(0)) + } + } + + // ---- invalid SQL --------------------------------------------------------------------------- + + @Test + fun invalidSqlIsRefusedWithAnExceptionAndTheConnectionSurvives() = withRawDb { db -> + val invalid = + listOf( + "SELEC 1", + "SELECT * FROM", + "SELECT * FROM no_such_table", + "CREATE TABLE", + "SELECT 'unterminated", + "SELECT \"unterminated", + "SELECT (1", + "SELECT 1 +", + "INSERT INTO", + "PRAGMA no_such_pragma = (", + "\u0001\u0002\u0003", + "SELECT éé FROM é", + "SELECT ?1 ?2 ?", + "(((((((((((((((((((((((((((((((((", + "SELECT " + "(".repeat(5000), + "SELECT " + "1+".repeat(50_000) + "1", // deeper than SQLite's expression depth limit + ) + for (sql in invalid) { + val e = assertFailsWith("sql of length ${sql.length}") { db.prepare(sql) } + assertTrue(e.message.orEmpty().startsWith("Error code: "), e.message) + } + db.stillWorks() + } + + @Test + fun sqlThatFailsOnlyWhenRunIsReportedByStepAndTheStatementCanBeReused() = withRawDb { db -> + db.exec("CREATE TABLE u (v INTEGER UNIQUE)") + db.exec("INSERT INTO u VALUES (1)") + db.prepare("INSERT INTO u VALUES (?)").use { + it.bindLong(1, 1L) + assertFailsWith { it.step() } + assertFailsWith { it.reset() }.also { e -> assertTrue("UNIQUE" in e.message.orEmpty()) } + it.reset() + it.bindLong(1, 2L) + assertFalse(it.step()) + } + db.prepare("SELECT count(*) FROM u").use { + assertTrue(it.step()) + assertEquals(2L, it.getLong(0)) + } + db.prepare("SELECT abs(-9223372036854775808)").use { + assertFailsWith { it.step() } // integer overflow + } + db.stillWorks() + } + + @Test + fun sqlIsReadUpToTheFirstNulAndTheRestIsIgnored() = withRawDb { db -> + db.prepare("SELECT 7\u0000 this is not sql at all (((").use { + assertTrue(it.step()) + assertEquals(7L, it.getLong(0)) + } + // Nothing before the NUL: no statement. + assertFailsWith { db.prepare("\u0000SELECT 1") } + assertFailsWith { db.prepare("\u0000") } + db.stillWorks() + } + + @Test + fun unpairedSurrogatesInSqlTextNeverCrash() = withRawDb { db -> + // SQL text is not sanitized (only bound text is). Either outcome is fine; the process must live. + for (sql in listOf( + "SELECT '\uD800'", + "SELECT '\uDC00'", + "SELECT '\uD800x'", + "SELECT 1 -- \uD83D", + "SELECT \uDE00", + )) { + try { + db.prepare(sql).use { statement -> + if (statement.step()) { + for (i in 0 until statement.getColumnCount()) statement.getText(i) + } + } + } catch (_: SQLiteException) { + // refused: fine + } + } + db.stillWorks() + } + + @Test + fun aLargeSqlTextIsPrepared() = withRawDb { db -> + val literal = "a".repeat(3 * 1024 * 1024) + db.prepare("SELECT length('$literal')").use { + assertTrue(it.step()) + assertEquals(literal.length.toLong(), it.getLong(0)) + } + val many = (1..20_000).joinToString(separator = ",") { "$it" } + db.prepare("SELECT count(*) FROM (SELECT 1 WHERE 1 IN ($many))").use { + assertTrue(it.step()) + } + } + + @Test + fun aMutatedStatementIsEitherPreparedOrRefused() = withRawDb { db -> + db.exec("CREATE TABLE m (a INTEGER, b TEXT, c BLOB)") + val seeds = + listOf( + "INSERT INTO m (a, b, c) VALUES (?, ?, ?)", + "SELECT a, b, c FROM m WHERE a > ? AND b LIKE ? ORDER BY c LIMIT 5", + "UPDATE m SET b = upper(b) || 'x' WHERE a IN (1, 2, 3)", + "WITH RECURSIVE r(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM r WHERE x < 3) SELECT x FROM r", + "CREATE INDEX IF NOT EXISTS mi ON m (a, b)", + "SELECT json_extract('{\"k\": [1, 2]}', '$.k[1]'), hex(zeroblob(4)), printf('%d', 5)", + ) + val random = Random(SEED) + var prepared = 0 + var refused = 0 + repeat(600) { + val chars = seeds[random.nextInt(seeds.size)].toCharArray().toMutableList() + repeat(random.nextInt(1, 4)) { + if (chars.isEmpty()) return@repeat + val at = random.nextInt(chars.size) + when (random.nextInt(4)) { + 0 -> chars.removeAt(at) + 1 -> chars.add(at, FUZZ_CHARS[random.nextInt(FUZZ_CHARS.length)]) + 2 -> chars[at] = FUZZ_CHARS[random.nextInt(FUZZ_CHARS.length)] + else -> while (chars.size > at) chars.removeAt(chars.size - 1) + } + } + val sql = chars.joinToString("") + try { + db.prepare(sql).use { statement -> + prepared++ + // Only look at the shape, never run it: a mutated DROP or DELETE is not the point. + statement.getColumnCount() + } + } catch (e: SQLiteException) { + refused++ + assertTrue(e.message.orEmpty().startsWith("Error code: "), e.message) + } + } + assertTrue(prepared > 0 && refused > 0, "prepared=$prepared refused=$refused") + db.stillWorks() + } + + // ---- U+0000 and unpaired surrogates in bound values ------------------------------------------ + + @Test + fun aBoundTextKeepsEveryNulAtItsPlace() = withRawDb { db -> + db.exec("CREATE TABLE t (s TEXT)") + val values = + listOf( + "\u0000", + "\u0000\u0000\u0000", + "\u0000a", + "a\u0000", + "a\u0000b\u0000c", + "\u0000".repeat(1000), + "x".repeat(70_000) + "\u0000" + "y".repeat(70_000), + "😀\u0000😀", + "\uD83D\u0000\uDE00", + ) + for (value in values) { + db.exec("DELETE FROM t") + db.prepare("INSERT INTO t VALUES (?)").use { + it.bindText(1, value) + assertFalse(it.step()) + } + val expected = value.withoutLoneSurrogates() + db.prepare("SELECT s, length(CAST(s AS BLOB)) FROM t").use { + assertTrue(it.step()) + assertEquals(expected, it.getText(0), "text of ${value.length} units") + assertEquals(expected.encodeToByteArray().size.toLong(), it.getLong(1)) + } + } + } + + @Test + fun aNulInANamedValueDoesNotCutTheNeighboursShort() = withRawDb { db -> + db.prepare("SELECT ?, ?, ?").use { + it.bindText(1, "before\u0000mid") + it.bindBlob(2, byteArrayOf(0, 1, 0, 2, 0)) + it.bindText(3, "after") + assertTrue(it.step()) + assertEquals("before\u0000mid", it.getText(0)) + assertContentEquals(byteArrayOf(0, 1, 0, 2, 0), it.getBlob(1)) + assertEquals("after", it.getText(2)) + } + } + + @Test + fun everyKindOfLoneSurrogateBecomesTheReplacementCharacter() = withRawDb { db -> + val cases = + mapOf( + "\uD800" to "�", + "\uDBFF" to "�", + "\uDC00" to "�", + "\uDFFF" to "�", + "\uD800\uD800" to "��", + "\uDC00\uD800" to "��", // low then high is not a pair + "\uD800𐀀" to "�𐀀", + "\uD800\u0000" to "�\u0000", + "\u0000\uDC00" to "\u0000�", + "ab\uD800" to "ab�", + "\uDC00ab" to "�ab", + ) + db.exec("CREATE TABLE s (v TEXT)") + for ((input, expected) in cases) { + db.exec("DELETE FROM s") + db.prepare("INSERT INTO s VALUES (?)").use { + it.bindText(1, input) + assertFalse(it.step()) + } + db.prepare("SELECT v FROM s").use { + assertTrue(it.step()) + assertEquals(expected, it.getText(0), input.map { c -> c.code.toString(16) }.toString()) + } + } + } + + @Test + fun randomTextWithNulAndSurrogatesRoundTripsAfterReplacement() = withRawDb { db -> + val alphabet = listOf("a", "Z", " ", "\u0000", "é", "中", "\uD800", "\uDBFF", "\uDC00", "\uDFFF", "😀", "�") + val random = Random(SEED) + db.exec("CREATE TABLE f (id INTEGER PRIMARY KEY, v TEXT)") + db.prepare("INSERT INTO f (v) VALUES (?)").use { insert -> + repeat(400) { + val value = + buildString { repeat(random.nextInt(0, 48)) { append(alphabet[random.nextInt(alphabet.size)]) } } + insert.reset() + insert.bindText(1, value) + assertFalse(insert.step()) + db.prepare("SELECT v FROM f WHERE id = last_insert_rowid()").use { + assertTrue(it.step()) + assertEquals(value.withoutLoneSurrogates(), it.getText(0)) + } + } + } + } + + @Test + fun randomBlobsRoundTrip() = withRawDb { db -> + val random = Random(SEED) + db.exec("CREATE TABLE r (id INTEGER PRIMARY KEY, v BLOB)") + db.prepare("INSERT INTO r (v) VALUES (?)").use { insert -> + repeat(200) { + val value = random.nextBytes(random.nextInt(0, 600)) + insert.reset() + insert.bindBlob(1, value) + assertFalse(insert.step()) + db.prepare("SELECT v FROM r WHERE id = last_insert_rowid()").use { + assertTrue(it.step()) + assertContentEquals(value, it.getBlob(0)) + } + } + } + } + + // ---- empty and large values ---------------------------------------------------------------- + + @Test + fun valuesAroundTheSizesWhereBuffersChangeRoundTrip() = withRawDb { db -> + db.exec("CREATE TABLE sz (b BLOB, s TEXT)") + val sizes = + listOf( + 0, + 1, + 2, + 3, + 255, + 256, + 257, + 4095, + 4096, + 4097, + 65_535, + 65_536, + 65_537, + 1_048_577, + 4 * 1024 * 1024 + 3, + ) + for (size in sizes) { + val blob = ByteArray(size) { (it xor (it ushr 8)).toByte() } + val text = CharArray(size) { 'a' + (it % 26) }.concatToString() + db.exec("DELETE FROM sz") + db.prepare("INSERT INTO sz VALUES (?, ?)").use { + it.bindBlob(1, blob) + it.bindText(2, text) + assertFalse(it.step()) + } + db.prepare("SELECT b, s, typeof(b), typeof(s), length(b), length(s) FROM sz").use { + assertTrue(it.step()) + assertContentEquals(blob, it.getBlob(0), "blob of $size") + assertEquals(text, it.getText(1), "text of $size") + assertEquals("blob", it.getText(2)) + assertEquals("text", it.getText(3)) + assertEquals(size.toLong(), it.getLong(4)) + assertEquals(size.toLong(), it.getLong(5)) + } + } + } + + @Test + fun emptyAndNullAreFourDifferentThingsAndNoneOfThemCrashes() = withRawDb { db -> + db.prepare("SELECT ?, ?, ?, ?").use { + it.bindBlob(1, ByteArray(0)) + it.bindText(2, "") + it.bindNull(3) + it.bindBlob(4, ByteArray(1)) + assertTrue(it.step()) + assertEquals(listOf(4, 3, 5, 4), (0..3).map(it::getColumnType)) + assertContentEquals(ByteArray(0), it.getBlob(0)) + assertEquals("", it.getText(1)) + assertContentEquals(ByteArray(0), it.getBlob(2)) // NULL reads as an empty blob + assertEquals("", it.getText(2)) + assertEquals(0L, it.getLong(2)) + assertEquals(0.0, it.getDouble(2)) + assertContentEquals(ByteArray(1), it.getBlob(3)) + } + } + + // ---- statement misuse ---------------------------------------------------------------------- + + @Test + fun columnAndParameterIndexesOutOfRangeThrow() = withRawDb { db -> + db.prepare("SELECT ?1, ?2").use { + for (bad in listOf(0, -1, 3, 1000, Int.MAX_VALUE, Int.MIN_VALUE)) { + assertFailsWith("bind $bad") { it.bindLong(bad, 1L) } + assertFailsWith("bind $bad") { it.bindDouble(bad, 1.0) } + assertFailsWith("bind $bad") { it.bindText(bad, "x") } + assertFailsWith("bind $bad") { it.bindBlob(bad, ByteArray(3)) } + assertFailsWith("bind $bad") { it.bindNull(bad) } + } + it.bindLong(1, 1L) + it.bindLong(2, 2L) + assertTrue(it.step()) + for (bad in listOf(-1, 2, 1000, Int.MAX_VALUE, Int.MIN_VALUE)) { + assertFailsWith("column $bad") { it.getLong(bad) } + assertFailsWith("column $bad") { it.getText(bad) } + assertFailsWith("column $bad") { it.getBlob(bad) } + assertFailsWith("column $bad") { it.getDouble(bad) } + assertFailsWith("column $bad") { it.isNull(bad) } + assertFailsWith("column $bad") { it.getColumnType(bad) } + assertFailsWith("column $bad") { it.getColumnName(bad) } + } + assertEquals(1L, it.getLong(0)) + assertEquals(2L, it.getLong(1)) + } + } + + @Test + fun readingBeforeTheFirstRowOrAfterTheLastThrows() = withRawDb { db -> + db.prepare("SELECT 1").use { + assertFailsWith { it.getLong(0) } + assertFailsWith { it.getText(0) } + assertFailsWith { it.getBlob(0) } + assertFailsWith { it.getDouble(0) } + assertFailsWith { it.isNull(0) } + assertFailsWith { it.getColumnType(0) } + assertEquals("1", it.getColumnName(0)) // names need no row + assertTrue(it.step()) + assertEquals(1L, it.getLong(0)) + assertFalse(it.step()) + assertFailsWith { it.getLong(0) } + assertFailsWith { it.getText(0) } + assertFailsWith { it.getBlob(0) } + } + } + + @Test + fun bindingToAStatementThatIsMidwayThroughItsRowsIsRefusedUntilReset() = withRawDb { db -> + db.prepare("SELECT ?1 UNION ALL SELECT ?1 + 1").use { + it.bindLong(1, 10L) + assertTrue(it.step()) + assertFailsWith { it.bindLong(1, 99L) } + assertEquals(10L, it.getLong(0)) // the failed bind changed nothing + assertTrue(it.step()) + assertEquals(11L, it.getLong(0)) + it.reset() + it.bindLong(1, 20L) + assertTrue(it.step()) + assertEquals(20L, it.getLong(0)) + } + } + + @Test + fun resetAndClearBindingsInEveryStateAreHarmless() = withRawDb { db -> + db.prepare("SELECT ?1 UNION ALL SELECT 2").use { + it.reset() // fresh + it.clearBindings() + it.reset() + it.bindText(1, "kept until cleared") + assertTrue(it.step()) + it.reset() // mid-run + it.reset() // twice + it.clearBindings() + assertTrue(it.step()) + assertTrue(it.isNull(0)) // cleared + assertTrue(it.step()) + assertFalse(it.step()) // done + it.reset() // after done + it.clearBindings() + assertTrue(it.step()) // runs again from the top + } + } + + /** Regression: the row of a running statement may point at a bound value, which clearing freed. */ + @Test + fun clearingBindingsWhileARowIsCurrentEndsTheRunInsteadOfLeavingTheRowDangling() = withRawDb { db -> + db.prepare("SELECT ?1, ?2").use { + it.bindText(1, "text that must not be read after it was freed ".repeat(8)) + it.bindBlob(2, ByteArray(512) { b -> b.toByte() }) + assertTrue(it.step()) + it.clearBindings() + assertFailsWith { it.getText(0) } + assertFailsWith { it.getBlob(1) } + assertTrue(it.step()) // runs again from the top, now with nothing bound + assertTrue(it.isNull(0)) + assertTrue(it.isNull(1)) + } + db.stillWorks() + } + + @Test + fun manyStatementsOpenAtOnceAreFinalizedInAnyOrder() = withRawDb { db -> + val random = Random(SEED) + val statements = List(64) { db.prepare("SELECT $it, ?") } + statements.forEachIndexed { i, s -> + s.bindText(1, "v$i") + if (i % 3 != 0) assertTrue(s.step()) + } + for (s in statements.shuffled(random)) { + s.close() + s.close() + } + statements.forEach { assertFailsWith { it.step() } } + db.stillWorks() + } + + private fun randomCall(s: androidx.sqlite.SQLiteStatement, random: Random) { + when (random.nextInt(11)) { + 0, 1 -> s.step() + 2 -> s.reset() + 3 -> s.clearBindings() + 4 -> s.bindLong(random.nextInt(-1, 3), 5L) + 5 -> s.bindText(random.nextInt(-1, 3), "t\u0000\uD800") + 6 -> s.getText(random.nextInt(-1, 3)) + 7 -> s.getBlob(random.nextInt(-1, 3)) + 8 -> s.isNull(random.nextInt(-1, 3)) + 9 -> s.close() + else -> s.getColumnName(random.nextInt(-1, 3)) + } + } + + @Test + fun scriptedOperationsOnStatementsAndAConnectionNeverEndInAnythingButAnSqliteException() { + val sqls = + listOf( + "SELECT ?", + "SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3", + "SELEC nope", + "", + "SELECT x FROM nowhere", + "SELECT zeroblob(1000)", + ) + val random = Random(SEED) + repeat(30) { round -> + val db = rawOpen(":memory:", flags) + val statements = mutableListOf() + var connectionClosed = false + repeat(150) { + val outcome = + runCatching { + when (random.nextInt(14)) { + 0, 1 -> { + statements += db.prepare(sqls[random.nextInt(sqls.size)]) + } + + 2 -> { + db.inTransaction() + } + + 3 -> { + if (random.nextInt(25) == 0) { + db.close() + connectionClosed = true + } + } + + else -> { + statements.randomOrNull(random)?.let { randomCall(it, random) } + } + } + } + val failure = outcome.exceptionOrNull() + if (failure != null) assertTrue(failure is SQLiteException, "round $round: $failure") + if (connectionClosed) { + assertFailsWith { db.prepare("SELECT 1") } + } + } + db.close() + statements.forEach { assertFailsWith { it.step() } } + } + } + + // ---- paths --------------------------------------------------------------------------------- + + @Test + fun aPathThatIsTooLongIsRefusedByTheOpen() { + for (length in listOf(300, 5_000, 70_000)) { + val path = "/" + "d".repeat(length) + "/x.db" + assertFailsWith("path of $length") { rawOpen(path, flags) } + } + val name = newTempDatabasePath().let { it + "-" + "n".repeat(400) } + try { + assertFailsWith { rawOpen(name, flags) } // a file name above NAME_MAX + } finally { + deleteDatabaseFiles(name) + } + } + + @Test + fun aLongButLegalFileNameOpensAndWorks() { + val base = newTempDatabasePath() + val path = base + "-" + "n".repeat(120) + try { + SealiteDriver(rawKey(3)).use { driver -> + driver.open(path).use { it.createNotes("long name") } + driver.open(path).use { assertEquals(listOf("long name"), it.notes()) } + } + } finally { + deleteDatabaseFiles(path) + deleteDatabaseFiles(base) + } + } + + @Test + fun aPathWithAnEmbeddedNulIsRefusedAndNoTruncatedFileIsCreated() { + val base = newTempDatabasePath() + try { + val withNul = base + "\u0000" + "-tail" + assertFailsWith { rawOpen(withNul, flags) }.also { + assertTrue("NUL" in it.message.orEmpty(), it.message) + } + assertNull(readFileBytes(base), "a path cut at its NUL must not have been created") + // Through the driver too: whatever it throws, nothing may appear at the cut path. + val outcome = runCatching { SealiteDriver(rawKey(4)).use { it.open(withNul).close() } } + assertTrue(outcome.isFailure, "the driver opened a path with a NUL") + assertNull(readFileBytes(base), "a path cut at its NUL must not have been created") + } finally { + deleteDatabaseFiles(base) + } + } + + @Test + fun anEmptyPathIsAnAnonymousTemporaryDatabaseNotAFileNamedNothing() { + // SQLite's own rule, kept: "" opens a private temporary database. It must work and vanish. + val db = rawOpen("", flags) + try { + db.exec("CREATE TABLE e (x)") + db.stillWorks() + } finally { + db.close() + } + } + + private fun String.withoutLoneSurrogates(): String { + val out = StringBuilder() + var i = 0 + while (i < length) { + val c = this[i] + when { + c.isHighSurrogate() && i + 1 < length && this[i + 1].isLowSurrogate() -> { + out.append(c).append(this[i + 1]) + i++ + } + + c.isSurrogate() -> { + out.append('�') + } + + else -> { + out.append(c) + } + } + i++ + } + return out.toString() + } + + private companion object { + /** Fixed: a failure is reproduced by the same run, and a failing seed becomes its own test. */ + const val SEED = 20_260_101 + + const val FUZZ_CHARS = " ()',;\"*?%-/=+0123456789abcSELCTFROMWHERE\u0000\uD800é" + } +} diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseRaceTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseRaceTest.kt new file mode 100644 index 0000000..944e25d --- /dev/null +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseRaceTest.kt @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 pasichdev + +package io.github.pasichdev.sealite + +import androidx.sqlite.SQLiteException +import io.github.pasichdev.sealite.internal.rawOpen +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.yield +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +/** + * Close racing prepare, bind, step, reset and statement close on several threads, with fixed seeds + * for the delays and a bound on the run time. A call that loses the race ends in a [SQLiteException]; + * after the close returned, every call says "closed". Nothing may crash, hang or throw anything else. + */ +class CloseRaceTest { + private val flags = 0x02 or 0x04 // READWRITE | CREATE + + @Test + fun closeRacingPrepareBindStepAndResetOnManyThreads() = runTest(timeout = 120.seconds) { + repeat(80) { round -> + val random = Random(SEED + round) + val db = rawOpen(":memory:", flags) + val closeAfter = random.nextLong(0, 12) + val failures = + withContext(Dispatchers.Default) { + coroutineScope { + val workers = + List(4) { worker -> + async { + val rng = Random(SEED + round * 31 + worker) + // runCatching, not a catch: whatever stops the loop is the result. + val thrown = + runCatching { + while (true) { + yield() // the closer needs a thread of the pool too + val s = db.prepare("SELECT ?, ?, hex(zeroblob(64))") + try { + s.bindText(1, "w$worker\u0000\uD800") + s.bindBlob(2, rng.nextBytes(rng.nextInt(0, 256))) + while (s.step()) { + s.getText(0) + s.getBlob(1) + s.getText(2) + } + if (rng.nextBoolean()) s.reset() + if (rng.nextBoolean()) s.clearBindings() + } finally { + s.close() + } + } + }.exceptionOrNull() + listOfNotNull(thrown) + } + } + val closer = + async { + delay(closeAfter) + db.close() + } + closer.await() + workers.awaitAll().flatten() + } + } + assertEquals(4, failures.size, "every worker must stop with exactly one failure") + for (failure in failures) assertTrue(failure is SQLiteException, "round $round: $failure") + val e = assertFailsWith { db.prepare("SELECT 1") } + assertTrue("closed" in e.message.orEmpty(), e.message) + db.close() + } + } + + @Test + fun closeRacingAnInterruptibleQueryAndPreparesOfNewOnes() = runTest(timeout = 120.seconds) { + val longQuery = + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 300000000) SELECT count(*) FROM c" + repeat(20) { round -> + val random = Random(SEED + round) + val db = rawOpen(":memory:", flags) + val outcomes = + // IO, not Default: the runner and the preparer block their threads in native code, and + // on a two-core device Default has only two, so the closer would run only after the + // whole query had finished and the race under test would never happen. + withContext(Dispatchers.IO) { + coroutineScope { + val runner = async { runCatching { db.prepare(longQuery).use { it.step() } } } + val preparer = + async { + runCatching { + while (true) { + yield() + db.prepare("SELECT 1").use { it.step() } + } + } + } + val closer = + async { + delay(5 + random.nextLong(0, 20)) + db.close() + } + closer.await() + listOf(runner.await(), preparer.await()) + } + } + for (outcome in outcomes) { + val failure = outcome.exceptionOrNull() + assertTrue(failure is SQLiteException, "round $round: $outcome") + } + } + } + + @Test + fun closingStatementsAndTheConnectionAtTheSameTimeFinalizesEachOnce() = runTest(timeout = 120.seconds) { + repeat(60) { round -> + val random = Random(SEED + round) + val db = rawOpen(":memory:", flags) + val statements = List(16) { db.prepare("SELECT $it, ?") } + val jobs = + withContext(Dispatchers.Default) { + coroutineScope { + val closers = + statements.shuffled(random).map { s -> + async { + delay(random.nextLong(0, 4)) + s.close() + s.close() + } + } + val steppers = + statements.map { s -> + async { + runCatching { + s.bindText(1, "x") + s.step() + s.reset() + } + } + } + val dbCloser = + async { + delay(random.nextLong(0, 4)) + db.close() + } + closers.awaitAll() + dbCloser.await() + steppers.awaitAll() + } + } + for (outcome in jobs) { + val failure = outcome.exceptionOrNull() + assertTrue(failure == null || failure is SQLiteException, "round $round: $outcome") + } + statements.forEach { assertFailsWith { it.step() } } + } + } + + private companion object { + const val SEED = 20_260_102L + } +} diff --git a/sealite/src/native/jni/sealite_jni.c b/sealite/src/native/jni/sealite_jni.c index d07a06f..2a5c7f9 100644 --- a/sealite/src/native/jni/sealite_jni.c +++ b/sealite/src/native/jni/sealite_jni.c @@ -448,6 +448,10 @@ static void JNICALL nativeReset(JNIEnv *env, jclass clazz, jlong stmtPointer) { static void JNICALL nativeClearBindings(JNIEnv *env, jclass clazz, jlong stmtPointer) { sqlite3_stmt *stmt = (sqlite3_stmt *) (intptr_t) stmtPointer; + /* The current row of a running statement can point at a bound value without copying it; freeing + * the binding would leave getText / getBlob reading freed memory. End the run first: the row is + * then refused ("no row") instead of read. */ + if (sqlite3_stmt_busy(stmt) != 0) sqlite3_reset(stmt); int rc = sqlite3_clear_bindings(stmt); if (rc != SQLITE_OK) { throwSQLiteExceptionFromDb(env, rc, sqlite3_db_handle(stmt)); diff --git a/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeStatement.kt b/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeStatement.kt index 5e1785a..b6ca3e3 100644 --- a/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeStatement.kt +++ b/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeStatement.kt @@ -199,6 +199,10 @@ internal class NativeStatement( } override fun clearBindings() = locked { + // The current row of a running statement can point at a bound value without copying it; + // freeing the binding would leave getText / getBlob reading freed memory. End the run first: + // the row is then refused ("no row") instead of read. + if (sealite_sqlite3_stmt_busy(stmtPointer) != 0) sealite_sqlite3_reset(stmtPointer) val resultCode = sealite_sqlite3_clear_bindings(stmtPointer) if (resultCode != SQLITE_OK) { throwSQLiteException(resultCode, dbPointer.getErrorMsg())