Modern Apps git

← Modern-Apps.git

photos: fix secure folder OOM on large videos and recycled bitmap crash on >=4 columns

Commit
194e91006a58cf2e85f8258d57713b27198de335
Author
Vayun Mathur <[email protected]>
When
2026-07-31 19:14 UTC (4 months ago)
Parents
1d5677f
Fix 1 - OOM on +150MB videos: AES/GCM via CipherOutputStream in Conscrypt buffers entire plaintext until doFinal in ByteArrayOutputStream (OpenSSLAeadCipher.appendToBuf). Switched to chunked encryption with 1MiB chunks, each with fresh IV, format [SEC2][IV+len+ciphertext]. Backward compatible with legacy single-IV files.

Fix 2 - Recycled bitmap crash when columnCount>=4: LRU cache size 32 recycled bitmaps synchronously in removeEldestEntry while _thumbnails StateFlow and Compose still held references. With >=4 columns more thumbnails visible -> LRU overflow -> canvas tries to draw recycled bitmap. Fix removes recycling on eviction, increases cap to 64, clears _thumbnails before recycling in onCleared, and adds isRecycled guard in VaultPhotoItem.

Diff

photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.ktindex b505c23fe3..363d96b497 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt@@ -167,7 +167,10 @@ fun VaultPhotoItem(             ),         contentAlignment = Alignment.Center     ) {-        if (bitmap != null) {+        // Guard against recycled bitmaps - defense in depth for the LRU cache bug.+        // When column count >=4, more thumbnails are visible and cache eviction+        // previously recycled bitmaps still being drawn by Compose.+        if (bitmap != null && !bitmap.isRecycled) {             Image(                 bitmap = bitmap.asImageBitmap(),                 contentDescription = null,
photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.ktindex 1991490d51..0a8ba78df6 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderManager.kt@@ -9,15 +9,16 @@ import android.os.Environment import android.provider.MediaStore import android.util.Size import com.vayunmathur.photos.data.VaultPhoto+import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.FileOutputStream+import java.io.InputStream+import java.io.OutputStream import java.nio.charset.StandardCharsets import java.security.MessageDigest import javax.crypto.Cipher-import javax.crypto.CipherInputStream-import javax.crypto.CipherOutputStream import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec@@ -45,58 +46,154 @@ class SecureFolderManager(val context: Context) {         return cipher     } +    // Chunked streaming encryption to avoid OOM on large files.+    // AES/GCM via CipherOutputStream in Conscrypt buffers the entire plaintext+    // until doFinal() (OpenSSLAeadCipher.appendToBuf), causing OutOfMemoryError+    // for +100MB files. We split into 1MiB chunks, each encrypted independently+    // with a fresh random IV and written as: [MAGIC(4)][IV(12)][len(4)][ciphertext].+    companion object {+        private const val GCM_IV_LENGTH = 12+        private const val CHUNK_SIZE = 1024 * 1024 // 1 MiB+        private val MAGIC_SEC2 = byteArrayOf(0x53, 0x45, 0x43, 0x32) // "SEC2" = Secure v2 chunked+    }++    private fun InputStream.readFully(buffer: ByteArray, offset: Int = 0, length: Int = buffer.size - offset): Boolean {+        var remaining = length+        var off = offset+        while (remaining > 0) {+            val r = read(buffer, off, remaining)+            if (r == -1) return false+            remaining -= r+            off += r+        }+        return true+    }++    private fun encryptStreamChunked(input: InputStream, output: OutputStream, key: SecretKey) {+        output.write(MAGIC_SEC2)+        val buffer = ByteArray(CHUNK_SIZE)+        while (true) {+            val read = input.read(buffer)+            if (read == -1) break+            if (read == 0) continue+            val cipher = getCipher(Cipher.ENCRYPT_MODE, key)+            val iv = cipher.iv // 12 bytes random+            val encrypted = cipher.doFinal(buffer, 0, read)+            output.write(iv)+            output.write((encrypted.size ushr 24) and 0xFF)+            output.write((encrypted.size ushr 16) and 0xFF)+            output.write((encrypted.size ushr 8) and 0xFF)+            output.write(encrypted.size and 0xFF)+            output.write(encrypted)+        }+    }++    /**+     * Decrypts both new chunked format (SEC2) and legacy single-IV format.+     * Returns false on malformed / auth failure.+     */+    private fun decryptToOutputStream(input: InputStream, output: OutputStream, key: SecretKey): Boolean {+        val first4 = ByteArray(4)+        if (!input.readFully(first4)) return false++        val isChunked = first4.contentEquals(MAGIC_SEC2)+        if (isChunked) {+            val lenBytes = ByteArray(4)+            while (true) {+                // Detect clean EOF+                val firstIvByte = input.read()+                if (firstIvByte == -1) break // done+                val iv = ByteArray(GCM_IV_LENGTH)+                iv[0] = firstIvByte.toByte()+                if (!input.readFully(iv, 1, GCM_IV_LENGTH - 1)) return false++                if (!input.readFully(lenBytes)) return false+                val encLen = ((lenBytes[0].toInt() and 0xFF) shl 24) or+                        ((lenBytes[1].toInt() and 0xFF) shl 16) or+                        ((lenBytes[2].toInt() and 0xFF) shl 8) or+                        (lenBytes[3].toInt() and 0xFF)+                if (encLen <= 0) return false++                val encData = ByteArray(encLen)+                if (!input.readFully(encData)) return false++                try {+                    val cipher = getCipher(Cipher.DECRYPT_MODE, key, iv)+                    val decrypted = cipher.doFinal(encData)+                    output.write(decrypted)+                } catch (e: Exception) {+                    return false+                }+            }+            return true+        } else {+            // Legacy format: [12 byte IV][ciphertext+tag] single GCM encryption+            val iv = ByteArray(GCM_IV_LENGTH)+            System.arraycopy(first4, 0, iv, 0, 4)+            if (!input.readFully(iv, 4, 8)) return false+            return try {+                val cipher = getCipher(Cipher.DECRYPT_MODE, key, iv)+                val encrypted = input.readBytes()+                val decrypted = cipher.doFinal(encrypted)+                output.write(decrypted)+                true+            } catch (e: Exception) {+                false+            }+        }+    }+     fun encryptAndMove(uri: Uri, name: String, password: String): Pair<String, String> {         val key = getSecretKey(password)         val timestamp = System.currentTimeMillis()         val fileName = "${timestamp}_${name}.enc"         val thumbName = "${timestamp}_${name}_thumb.enc"-        +         val outputFile = File(secureFolder, fileName)         val thumbFile = File(secureFolder, thumbName)-        -        // 1. Generate Thumbnail-        val bitmap = context.contentResolver.loadThumbnail(uri, Size(512, 512), null)--        // 2. Encrypt Thumbnail-        val baos = ByteArrayOutputStream()-        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)-        bitmap.recycle()-        val thumbBytes = baos.toByteArray()-        -        FileOutputStream(thumbFile).use { fos ->-            val cipher = getCipher(Cipher.ENCRYPT_MODE, key)-            fos.write(cipher.iv)-            CipherOutputStream(fos, cipher).use { output ->-                output.write(thumbBytes)-            }-        } -        // 3. Encrypt Main File-        context.contentResolver.openInputStream(uri)?.use { input ->-            FileOutputStream(outputFile).use { fos ->-                val cipher = getCipher(Cipher.ENCRYPT_MODE, key)-                fos.write(cipher.iv)-                CipherOutputStream(fos, cipher).use { output ->-                    input.copyTo(output)+        try {+            // 1. Generate Thumbnail+            val bitmap = context.contentResolver.loadThumbnail(uri, Size(512, 512), null)++            // 2. Encrypt Thumbnail (small, but also use chunked format for consistency)+            val baos = ByteArrayOutputStream()+            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)+            bitmap.recycle()+            val thumbBytes = baos.toByteArray()++            FileOutputStream(thumbFile).use { fos ->+                ByteArrayInputStream(thumbBytes).use { input ->+                    encryptStreamChunked(input, fos, key)                 }             }++            // 3. Encrypt Main File with streaming chunks to avoid OOM on large videos+            context.contentResolver.openInputStream(uri)?.use { input ->+                FileOutputStream(outputFile).use { fos ->+                    encryptStreamChunked(input, fos, key)+                }+            } ?: throw IllegalStateException("Unable to open input stream for $uri")++            return outputFile.absolutePath to thumbFile.absolutePath+        } catch (e: Exception) {+            // Don't leave partial/corrupt encrypted files behind+            outputFile.delete()+            thumbFile.delete()+            throw e         }-        -        return outputFile.absolutePath to thumbFile.absolutePath     }      fun decryptThumbnail(path: String, password: String): Bitmap? {         val file = File(path)         if (!file.exists()) return null-        +         val key = getSecretKey(password)         return try {             FileInputStream(file).use { fis ->-                val iv = ByteArray(12)-                if (fis.read(iv) != 12) return null-                val cipher = getCipher(Cipher.DECRYPT_MODE, key, iv)-                CipherInputStream(fis, cipher).use { input ->-                    val bytes = input.readBytes()+                ByteArrayOutputStream().use { baos ->+                    if (!decryptToOutputStream(fis, baos, key)) return null+                    val bytes = baos.toByteArray()                     BitmapFactory.decodeByteArray(bytes, 0, bytes.size)                 }             }@@ -124,19 +221,27 @@ class SecureFolderManager(val context: Context) {          val uri = context.contentResolver.insert(collection, contentValues) ?: return null -        context.contentResolver.openOutputStream(uri)?.use { output ->-            FileInputStream(inputFile).use { fis ->-                val iv = ByteArray(12)-                if (fis.read(iv) != 12) {-                    // Don't leave an empty MediaStore row behind on a malformed file.-                    context.contentResolver.delete(uri, null, null)-                    return null-                }-                val cipher = getCipher(Cipher.DECRYPT_MODE, key, iv)-                CipherInputStream(fis, cipher).use { input ->-                    input.copyTo(output)+        var success = false+        try {+            context.contentResolver.openOutputStream(uri)?.use { output ->+                FileInputStream(inputFile).use { fis ->+                    if (!decryptToOutputStream(fis, output, key)) {+                        context.contentResolver.delete(uri, null, null)+                        return null+                    }+                    success = true                 }             }+        } catch (e: Exception) {+            if (!success) {+                context.contentResolver.delete(uri, null, null)+            }+            return null+        }++        if (!success) {+            context.contentResolver.delete(uri, null, null)+            return null         }          // Delete encrypted files@@ -145,5 +250,4 @@ class SecureFolderManager(val context: Context) {          return uri     }- }
photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.ktindex d42a070b86..e3b82b5c61 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt@@ -60,16 +60,18 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica      private val sfm: SecureFolderManager by lazy { SecureFolderManager(application) } -    // Bounded LRU cache for decrypted thumbnails. Cap 32 to prevent unbounded-    // bitmap retention while scrolling large vaults. Eldest entries are recycled-    // synchronously on eviction.-    private val thumbCache = object : LinkedHashMap<String, Bitmap>(32, 0.75f, true) {+    // Bounded LRU cache for decrypted thumbnails. Cap 64 to prevent unbounded+    // bitmap retention while scrolling large vaults.+    // NOTE: Previous implementation recycled bitmaps synchronously in+    // removeEldestEntry while _thumbnails and Compose UI still held references,+    // causing "Canvas: trying to use a recycled bitmap" when column count >=4+    // (more thumbnails visible -> cache overflow -> recycled while drawing).+    // Fix: No recycling on eviction; let LRU evict without recycle and keep+    // _thumbnails in sync with cache (snapshot). Recycling only happens in+    // onCleared() after _thumbnails is emptied.+    private val thumbCache = object : LinkedHashMap<String, Bitmap>(64, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Bitmap>): Boolean {-            if (size > 32) {-                try { eldest.value.recycle() } catch (e: Exception) { Log.w(TAG, "Failed to recycle evicted thumbnail", e) }-                return true-            }-            return false+            return size > 64         }     } @@ -110,27 +112,40 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica      */     fun requestThumbnail(thumbnailPath: String, password: String) {         synchronized(thumbCache) {-            thumbCache[thumbnailPath]?.let { cached ->-                if (_thumbnails.value[thumbnailPath] !== cached) {-                    _thumbnails.update { it + (thumbnailPath to cached) }+            val cached = thumbCache[thumbnailPath]+            if (cached != null) {+                if (!cached.isRecycled) {+                    if (_thumbnails.value[thumbnailPath] !== cached) {+                        // Keep _thumbnails in sync with cache snapshot+                        _thumbnails.value = thumbCache.toMap()+                    }+                    return+                } else {+                    // Drop recycled entry if it somehow ended up recycled+                    thumbCache.remove(thumbnailPath)                 }-                return             }         }         viewModelScope.launch(Dispatchers.IO) {             try {                 val bmp = sfm.decryptThumbnail(thumbnailPath, password) ?: return@launch+                val snapshot: Map<String, Bitmap>                 synchronized(thumbCache) {                     val existing = thumbCache[thumbnailPath]-                    if (existing != null) {+                    if (existing != null && !existing.isRecycled) {+                        // Another thread already inserted, recycle the duplicate we just decrypted                         try { bmp.recycle() } catch (e: Exception) { Log.w(TAG, "Failed to recycle duplicate thumbnail", e) }+                        snapshot = thumbCache.toMap()                     } else {+                        if (existing != null) {+                            // Existing was recycled, remove it+                            thumbCache.remove(thumbnailPath)+                        }                         thumbCache[thumbnailPath] = bmp+                        snapshot = thumbCache.toMap()                     }                 }-                _thumbnails.update { current ->-                    current + (thumbnailPath to synchronized(thumbCache) { thumbCache[thumbnailPath]!! })-                }+                _thumbnails.value = snapshot             } catch (e: Exception) {                 Log.e(TAG, "decryptThumbnail failed for $thumbnailPath", e)             }@@ -224,13 +239,14 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica      override fun onCleared() {         super.onCleared()+        // Clear _thumbnails first so Compose no longer holds references, then recycle+        _thumbnails.value = emptyMap()         synchronized(thumbCache) {             thumbCache.values.forEach { bmp ->                 try { if (!bmp.isRecycled) bmp.recycle() } catch (e: Exception) { Log.w(TAG, "Failed to recycle thumbnail on clear", e) }             }             thumbCache.clear()         }-        _thumbnails.value = emptyMap()     }      companion object {