Modern Apps git

← Modern-Apps.git

pdf: OCR handle freed under live recognizeText call (#944)

Commit
62717130767a554302c5b2776ca2b5b4774a2a9a
Author
Vayun Mathur <[email protected]>
When
2026-11-28 07:11 UTC (8 days ago)
Parents
3dcd527
MTE tag-mismatch SIGSEGV inside MlNative.recognizeText on DefaultDispatcher after repeated opens from WhatsApp. The audit found the fitting lifetime hazard: OcrEngine holds its coroutine Mutex across the native call, but close() is a non-suspend call that cannot take that mutex, and the viewer calls it from DisposableEffect.onDispose — closing one document while its OCR pass was still in flight freed the OcrHandle under the live native call (heap use-after-free = MTE mismatch); TextRecognizer compounded it with unsynchronised handle/pixels fields and a shared IntArray across passes.

Both layers now enforce the lifetime: TextRecognizer serialises passes on an internal lock, close() defers the native destroy until the last in-flight pass exits (refcount), pixel counts are overflow-guarded, and the Rust side holds a new OCR_LIFETIME RwLock (recognize holds read for the whole pass, destroyOcr takes write), so the contract holds even if a future caller misbehaves. A tombstone from a guarded build, or an HWASan close-during-recognize repro, would confirm finally; the buffer path itself was audited sound.

Verified: cargo modelrunner 895 passed, :library:ml:testDebugUnitTest + :library:ocr:testDebugUnitTest green, ml/ocr lint clean.

Diff

library/ml/AGENTS.md
diff --git a/library/ml/AGENTS.md b/library/ml/AGENTS.mdindex e6f7368697..b0874b6c65 100644--- a/library/ml/AGENTS.md+++ b/library/ml/AGENTS.md@@ -13,7 +13,7 @@ **Purpose:** All on-device inference — session wrappers for every runtime (ONNX, LiteRT, ExecuTorch, Vulkan compute) plus per-model handles: Whisper (speech), NLLB (translate), Gemma (assistant), Maia (chess), CLIP/faces/segmentation (photos/camera), Supertonic (TTS), OCR post. No vendor SDKs. **How to use:** Pick the runtime session (`OnnxSessions` / `LiteRtSessions` / `ExecutorchSessions` / `VulkanSessions`), then the model handle (`WhisperHandle`, `NllbHandle`, `GemmaTypes`, `MaiaHandle`, `ClipHandle`, `SelfieSegmenter`, …). Pre/post via `OnnxPreprocess`, `OcrPost`, `SegmentationMask`. **Entry points:** The `*Handle` for your model → its `*Sessions` runtime → `VulkanBridge`/`VulkanWire` if GPU.-**Gotchas:** Model files are large and versioned per consumer — never share weights across models without checking compatibility; GPU paths need device-specific testing.+**Gotchas:** Model files are large and versioned per consumer — never share weights across models without checking compatibility; GPU paths need device-specific testing. `TextRecognizer` is thread-safe without caller locks: passes are serialised internally and `close()` defers the native destroy until any in-flight pass returns; the Rust side enforces the same lifetime with the `OCR_LIFETIME` RwLock in `bridge.rs` (recognise holds the read side, `destroyOcr` the write side), so a handle is never freed under a live `recognizeText` call.  ## Key files - com/vayunmathur/library/ml/OnnxSessions.kt
library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.ktindex 0e82d6f160..e43d8c5561 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt@@ -47,10 +47,10 @@ data class RecognizedLine(  *  * # Threading  *- * Not thread-safe, and holding a lock across the whole of [recognize] and [close] is- * required rather than advisable: the native handle is freed by [close] and reading it- * afterwards is a use-after-free. See `BokehAnalyzer`, whose comments record what that- * looked like when it happened.+ * Thread-safe: recognise passes are serialised internally and [close] defers+ * the native destruction until any in-flight pass has returned, so no caller+ * has to hold its own lock across [recognize] and [close] to avoid freeing+ * the native handle under a live call.  *  * Not cheap to construct either - two nets, two arenas, two command buffers - so build one  * per batch of images and [close] it, rather than one per image.@@ -64,6 +64,47 @@ class TextRecognizer(     private var handle: Long = 0L     private var pixels: IntArray? = null +    // Lifetime guard for the native handle (issue #944). This class used to rely+    // on every caller holding an external lock across recognise + close; the pdf+    // viewer's OcrEngine holds its Mutex across recognise but its close() is a+    // plain non-suspend call that cannot, so closing a document while an OCR+    // pass was still running on Dispatchers.Default freed the OcrHandle under+    // the native call — a use-after-free that surfaces as an MTE tag mismatch+    // inside recognizeText. The guard is therefore internal now:+    //  - [callLock] serialises the native calls themselves (the handle's pixel+    //    Vec and Vulkan nets are single-user, and [pixels] is a reused buffer);+    //  - [stateLock] + [inFlight] make [close] non-destroying while a call is+    //    in flight: destruction is deferred to the last call's exit.+    private val callLock = Any()+    private val stateLock = Any()+    private var inFlight = 0+    private var closeRequested = false++    /** Mark a native call as started, or refuse it once closing. */+    private fun beginUse(): Boolean = synchronized(stateLock) {+        if (closeRequested || handle == 0L) {+            false+        } else {+            inFlight+++            true+        }+    }++    /** Mark a native call as finished; destroys the handle if [close] deferred it. */+    private fun endUse() {+        val destroy = synchronized(stateLock) {+            inFlight--+            if (closeRequested && inFlight == 0 && handle != 0L) {+                val live = handle+                handle = 0L+                live+            } else {+                0L+            }+        }+        if (destroy != 0L) MlNative.destroyOcr(destroy)+    }+     init {         handle = if (!MlNative.isAvailable) {             0L@@ -82,7 +123,7 @@ class TextRecognizer(     }      /** True if both networks came up and the dictionary parsed. */-    val isAvailable: Boolean get() = handle != 0L+    val isAvailable: Boolean get() = synchronized(stateLock) { handle != 0L && !closeRequested }      /**      * Recognise every line in [bitmap], in reading order.@@ -92,23 +133,43 @@ class TextRecognizer(      * logcat under `ModelRunner`. The caller's [bitmap] is not recycled.      */     fun recognize(bitmap: Bitmap): List<RecognizedLine> {-        if (handle == 0L) return emptyList()-        // `HARDWARE` bitmaps cannot be read with getPixels, and a null config means the-        // bitmap was already recycled.-        val readable = if (bitmap.config == Bitmap.Config.ARGB_8888) {-            bitmap-        } else {-            bitmap.copy(Bitmap.Config.ARGB_8888, false) ?: return emptyList()-        }+        if (!beginUse()) return emptyList()         try {-            val count = readable.width * readable.height-            val buffer = pixels?.takeIf { it.size == count } ?: IntArray(count).also { pixels = it }-            readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)-            val packed = MlNative.recognizeText(handle, buffer, readable.width, readable.height)-                ?: return emptyList()-            return parse(packed)+            // Serialised: the reused pixel buffer and the native handle's own+            // scratch Vec are single-user, so two concurrent passes would+            // interleave pixels even without a close in between.+            synchronized(callLock) {+                // `HARDWARE` bitmaps cannot be read with getPixels, and a null config means the+                // bitmap was already recycled.+                val readable = if (bitmap.config == Bitmap.Config.ARGB_8888) {+                    bitmap+                } else {+                    bitmap.copy(Bitmap.Config.ARGB_8888, false) ?: return emptyList()+                }+                try {+                    if (readable.isRecycled) return emptyList()+                    // Long arithmetic: width*height as Int wraps negative on a+                    // bitmap past 2^31 pixels and would size the array from the wrap.+                    val countLong = readable.width.toLong() * readable.height.toLong()+                    if (countLong > Int.MAX_VALUE) return emptyList()+                    val count = countLong.toInt()+                    val buffer = pixels?.takeIf { it.size == count } ?: IntArray(count).also { pixels = it }+                    try {+                        readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)+                    } catch (expected: IllegalStateException) {+                        // Recycled between the check above and here by whoever+                        // owns the bitmap: that is "no text", not a crash.+                        return emptyList()+                    }+                    val packed = MlNative.recognizeText(handle, buffer, readable.width, readable.height)+                        ?: return emptyList()+                    return parse(packed)+                } finally {+                    if (readable !== bitmap) readable.recycle()+                }+            }         } finally {-            if (readable !== bitmap) readable.recycle()+            endUse()         }     } @@ -140,20 +201,39 @@ class TextRecognizer(         cropBottom: Int,         rotationDegrees: Int,     ): List<RecognizedLine>? {-        if (handle == 0L || !buffer.isDirect) return null-        val packed = MlNative.recognizeTextBuffer(-            handle, buffer, width, height, rowStride, pixelStride,-            cropLeft, cropTop, cropRight, cropBottom, rotationDegrees,-        ) ?: return null-        return parse(packed)+        if (!buffer.isDirect || !beginUse()) return null+        try {+            synchronized(callLock) {+                val packed = MlNative.recognizeTextBuffer(+                    handle, buffer, width, height, rowStride, pixelStride,+                    cropLeft, cropTop, cropRight, cropBottom, rotationDegrees,+                ) ?: return null+                return parse(packed)+            }+        } finally {+            endUse()+        }     } -    /** Free both networks. Idempotent. */+    /**+     * Free both networks. Idempotent, and safe to call while a recognise pass+     * is running on another thread: the native destruction is deferred until+     * the last in-flight pass returns (see the lifetime guard above), so this+     * never frees the handle under a live native call.+     */     override fun close() {-        val live = handle-        handle = 0L-        pixels = null-        if (live != 0L) MlNative.destroyOcr(live)+        val destroy = synchronized(stateLock) {+            closeRequested = true+            pixels = null+            if (inFlight == 0 && handle != 0L) {+                val live = handle+                handle = 0L+                live+            } else {+                0L+            }+        }+        if (destroy != 0L) MlNative.destroyOcr(destroy)     }      private companion object {
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 223c3f7737..cbcb936f24 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -368,6 +368,26 @@ struct OcrHandle {     pixels: Vec<i32>, } +/// Lifetime guard for every `OcrHandle` (issue #944).+///+/// The JNI contract used to rest entirely on the Kotlin caller serialising+/// `recognizeText`/`recognizeTextBuffer` against `destroyOcr`. That contract+/// was broken in practice (a non-suspend `close()` cannot take the coroutine+/// Mutex the recognise path holds), and `destroyOcr` then freed the handle+/// while a pass on `Dispatchers.Default` was still reading it — a heap+/// use-after-free, reported as an MTE tag-mismatch SIGSEGV inside+/// `recognizeText`. The guard makes the native side enforce the lifetime+/// itself: recognise passes hold the read side for their whole duration, and+/// destruction takes the write side, so a destroy can only ever run between+/// passes, never inside one. Poison-tolerant like the rest of this bridge: a+/// panicking pass must not wedge every later destroy.+pub(crate) static OCR_LIFETIME: std::sync::RwLock<()> = std::sync::RwLock::new(());++/// The read side of [`OCR_LIFETIME`], held for one whole recognise pass.+pub(crate) fn ocr_use_guard() -> std::sync::RwLockReadGuard<'static, ()> {+    OCR_LIFETIME.read().unwrap_or_else(|poisoned| poisoned.into_inner())+}+ /// `TextRecognizer`'s constructor: detection at a fixed square, recognition at a fixed /// width, and the character table. Returns 0 on failure, having logged why. ///
library/ml/src/main/rust/src/bridge_part1.rs
diff --git a/library/ml/src/main/rust/src/bridge_part1.rs b/library/ml/src/main/rust/src/bridge_part1.rsindex b153868d8c..c4a049aefd 100644--- a/library/ml/src/main/rust/src/bridge_part1.rs+++ b/library/ml/src/main/rust/src/bridge_part1.rs@@ -26,13 +26,16 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_recognize     width: jint,     height: jint, ) -> jstring {+    // Held for the whole pass: `destroyOcr` cannot free the handle mid-call+    // even if a caller breaks the serialisation contract (issue #944).+    let _lifetime = ocr_use_guard();     env.with_env(|env| -> jni::errors::Result<jstring> {         let null = std::ptr::null_mut();         if handle == 0 || width <= 0 || height <= 0 {             return Ok(null);         }-        // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this-        // against `destroyOcr`.+        // SAFETY: the caller guarantees the handle came from `createPpocr`;+        // `OCR_LIFETIME` (held above) guarantees it is not destroyed concurrently.         let state = unsafe { &mut *(handle as *mut OcrHandle) };          if let Err(e) = read_pixels(env, &pixels, width, height, &mut state.pixels) {@@ -117,8 +120,14 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyOc     if handle == 0 {         return;     }+    // The write side of `OCR_LIFETIME`: waits for any in-flight recognise pass+    // to finish before the handle is freed (issue #944). Each `Net`'s Drop+    // waits for the device to go idle.+    let _lifetime = OCR_LIFETIME+        .write()+        .unwrap_or_else(|poisoned| poisoned.into_inner());     // SAFETY: the caller guarantees this came from `createPpocr` and has not been-    // destroyed. Each `Net`'s Drop waits for the device to go idle.+    // destroyed; the guard guarantees no pass is using it concurrently.     drop(unsafe { Box::from_raw(handle as *mut OcrHandle) }); } 
library/ml/src/main/rust/src/bridge_part12.rs
diff --git a/library/ml/src/main/rust/src/bridge_part12.rs b/library/ml/src/main/rust/src/bridge_part12.rsindex b3e72334fb..81b5ce99db 100644--- a/library/ml/src/main/rust/src/bridge_part12.rs+++ b/library/ml/src/main/rust/src/bridge_part12.rs@@ -39,13 +39,15 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_recognize     crop_bottom: jint,     rotation_degrees: jint, ) -> jstring {+    // Held for the whole pass, as in `recognizeText` (issue #944).+    let _lifetime = ocr_use_guard();     env.with_env(|env| -> jni::errors::Result<jstring> {         let null = std::ptr::null_mut();         if handle == 0 || width <= 0 || height <= 0 || row_stride <= 0 || pixel_stride <= 0 {             return Ok(null);         }-        // SAFETY: as `recognizeText` — the caller guarantees the handle is-        // live and serialises this against `destroyOcr`.+        // SAFETY: the caller guarantees the handle came from `createPpocr`;+        // `OCR_LIFETIME` (held above) guarantees it is not destroyed concurrently.         let state = unsafe { &mut *(handle as *mut OcrHandle) };         let address = match env.get_direct_buffer_address(&buffer) {             Ok(a) if !a.is_null() => a,