Modern Apps git

← Modern-Apps.git

pdf: open documents from a file descriptor; no size cap (#951)

Commit
15891aeed95859d1e5278ce57b613119b8a23f53
Author
Vayun Mathur <[email protected]>
When
2026-11-30 21:22 UTC (5 days ago)
Parents
62b653f
Owner-directed replacement of the 256 MiB cap landed earlier for
this issue: refusing large files is not acceptable — the app must
load them. The viewer open path no longer materialises the file at
all: Kotlin acquires a descriptor (provider fd, spool file only
when a provider offers none), passes it to a new native entry, and
the Rust side mmaps it for the synchronous parse. lopdf's Document
owns the parsed objects, so the registry registers from the map
with no extra full copy; the map drops before the call returns.

Eliminated: the Kotlin whole-file ByteArray, the JNI copy, the
second classification read. The byte[] API keeps its 200 MB
native guard for small in-memory callers; the fd path uses new
uncapped open/password-state internals and never consults it.
Classification stays one-attempt: openFromBytes returns handle /
needs-password (rejected-aware) / unsupported / not-a-PDF from the
same mmap. MAX_PDF_BYTES, readUriBytes and readBoundedBytes are
deleted. Cut-and-glue append uses appendPdfFd on the same seam —
no size refusal there either. Lazy redaction probing retained.

SafePdfOpenBoundsTest reworked: the cap-refusal assertions are
gone; a sparse 270,000,000-byte document now opens via the fd
path with correct page count and renders, alongside the 600-page
book, garbage/fake-header and encrypted classifications, and a
reflection seam asserting the old capped reader no longer exists.
Verified: cargo test -p pdf_render 667 passed; :pdf:testDevUnitTest
302 passed; lint errors are the known pre-existing set on
untouched files.

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 278b6d9005..03a75d722b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4270,6 +4270,7 @@ dependencies = [  "jpeg-decoder",  "lopdf",  "md-5 0.11.0",+ "memmap2",  "openjp2",  "rand 0.10.4",  "rand_core 0.10.1",
pdf/AGENTS.md
diff --git a/pdf/AGENTS.md b/pdf/AGENTS.mdindex 38d202536a..7154b3ebc4 100644--- a/pdf/AGENTS.md+++ b/pdf/AGENTS.md@@ -26,7 +26,7 @@ _Install: ./install pdf (dev by default)._ - Adobe YCCK (APP14 transform 2) CMYK JPEGs reach the Rust decoder with all four samples in inverted-ink polarity; the CMYK32 arm inverts all four before converting (transform 0 samples are already true ink) - Wire format is v11: the Image arm carries a per-image `/Interpolate` byte decided in Rust (`image_should_interpolate` — bilevel art is never smoothed, contone and explicit `/Interpolate true` are), and Kotlin applies it as `isFilterBitmap`; bumping the wire version without writing the byte desyncs every later primitive - Outline drawer intent is owned by `ui/PdfOutlineState` (saveable, explicit user action only) and drives the Material drawer state; width changes are layout only and never open or close it, and the wide layout's side pane is derived from the width class, not from drawer state-- Opening reads the document bytes once through a chunked, capped read (`SafePdfDocument.MAX_PDF_BYTES`, 256 MiB): oversized or unreadable inputs fail with the viewer error state instead of loading whole into the heap, the same read classifies encryption for the password prompt, and cut-and-glue appends use the same bounded read; redaction presence is probed lazily once editing starts, not at open+- Opening hands native a file descriptor (`SafePdfDocument.acquireDocumentFd` -> `PdfNative.openDocumentFd`): Rust dups and mmaps it, so no whole-file copy exists in the Kotlin heap or across JNI and file size alone never refuses an open; that one attempt classifies Opened / NeedsPassword / Failed (incl. not-a-PDF). Providers without a descriptor fall back to spooling the stream to a cache file in chunks (O(chunk) memory) and opening its descriptor. Cut-and-glue appends take the same descriptor path (`appendPdfFd`). The byte[] native API remains for small in-memory documents and keeps its own native size guard. Redaction presence is probed lazily once editing starts, not at open  ## Key files ### Root — entry + navigation
pdf/src/main/java/com/vayunmathur/pdf/platform/ComposePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/ComposePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/ComposePdfDocument.ktindex 13f1cf2350..07635958bc 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/ComposePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/ComposePdfDocument.kt@@ -28,6 +28,16 @@ class ComposePdfDocument private constructor(private var handle: Long) {         PdfNative.appendPdf(handle, bytes)     } +    /**+     * Append all pages of the PDF behind [pfd]; returns pages added. The+     * caller keeps and closes [pfd]; native dups the descriptor (see+     * [PdfNative.appendPdfFd]).+     */+    suspend fun appendPdfFd(pfd: android.os.ParcelFileDescriptor): Int = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext 0+        PdfNative.appendPdfFd(handle, pfd)+    }+     /** Append a JPEG image ([w]x[h]) as a new page; returns 1 on success. */     suspend fun appendImage(jpeg: ByteArray, w: Int, h: Int): Int = withContext(Dispatchers.IO) {         if (closed || handle == 0L) return@withContext 0
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.ktindex 867d3f5001..b904ffad6c 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt@@ -4,18 +4,19 @@ import com.vayunmathur.pdf.util.PdfNative  import android.content.Context import android.net.Uri-import android.provider.OpenableColumns+import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log-import java.io.ByteArrayOutputStream-import java.io.InputStream+import java.io.File+import java.io.FileOutputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext  /**  * A parsed PDF for the "safe" viewer, backed by the native Rust renderer.  *- * Reads the [Uri] bytes through the [Context]'s content resolver, hands them to- * [PdfNative.openDocument], and exposes the [pageCount] plus a per-page+ * Opens the [Uri] through a file descriptor handed to+ * [PdfNative.openDocumentFd] (native dups and mmaps it; no whole-file copy+ * ever exists in the Kotlin heap), and exposes the [pageCount] plus a per-page  * [renderPage]. Rendered pages are cached so scrolling back does not re-decode.  * All native work happens on [Dispatchers.IO]; callers must [close] when done.  *@@ -85,9 +86,9 @@ class SafePdfDocument private constructor(     }      /**-     * Outcome of one open attempt, classified from a single bounded read of-     * the document bytes so a failed open never triggers a second full read-     * just to ask whether the file was encrypted.+     * Outcome of one open attempt, classified by the same descriptor open+     * so a failed open never triggers a second read just to ask whether the+     * file was encrypted.      */     sealed interface OpenOutcome {         /** Opened; carries document. */@@ -340,80 +341,79 @@ class SafePdfDocument private constructor(          * most a re-render if that page is requested again. The budget can therefore be tight.          */         private const val MAX_CACHED_BYTES = 96L * 1024 * 1024-        /**-         * Largest document the viewer will materialise, in bytes. The native-         * open API takes the whole file as one [ByteArray], so the Kotlin-         * copy plus the native parse must fit alongside the page cache in a-         * phone heap; past this size opening fails cleanly with the viewer's-         * error state instead of dying in an out-of-memory allocation while-         * reading. Reading itself is chunked and aborts the moment the cap-         * is crossed, so an oversized file is never fully loaded.-         */-        internal const val MAX_PDF_BYTES: Long = 256L * 1024 * 1024-+        /** Chunk size of the spool copy used when no descriptor is available. */         private const val READ_CHUNK_BYTES = 64 * 1024 +        // Negative results of PdfNative.openDocumentFd (see fdopen.rs).+        private const val FD_NEEDS_PASSWORD = -1L+        private const val FD_NOT_PDF = -3L+         /**-         * Read [input] fully in chunks, or return `null` as soon as more-         * than [maxBytes] bytes have been seen (the rest of the stream is-         * never consumed). [expectedSize], when known, pre-sizes the buffer-         * so a large-but-legal file is accumulated in a single allocation-         * instead of a doubling copy.+         * A provider (or spool-file) descriptor plus the spool file backing+         * it, if any. The caller owns [pfd] and must [close] it — native+         * dups the descriptor, so closing the original after the call is+         * always safe and never a double-close. Closing also deletes the+         * spool, which is only valid once native has returned (the parsed+         * document owns its objects by then).          */-        internal fun readBoundedBytes(-            input: InputStream,-            maxBytes: Long,-            expectedSize: Long = -1L,-        ): ByteArray? {-            if (maxBytes < 0L) return null-            val initial = if (expectedSize in 1..maxBytes) expectedSize.toInt() else READ_CHUNK_BYTES-            val out = ByteArrayOutputStream(initial)-            val chunk = ByteArray(READ_CHUNK_BYTES)-            var total = 0L-            while (true) {-                val n = input.read(chunk)-                if (n < 0) break-                total += n-                if (total > maxBytes) return null-                out.write(chunk, 0, n)+        internal class DocumentFd(+            val pfd: ParcelFileDescriptor,+            private val spool: File?,+        ) : java.io.Closeable {+            override fun close() {+                runCatching { pfd.close() }+                spool?.let { runCatching { it.delete() } }             }-            return out.toByteArray()         } -        /** Declared byte size of [uri] when the provider reports one, else -1. */-        private fun declaredSizeBytes(context: Context, uri: Uri): Long = runCatching {-            context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)-                ?.use { cursor ->-                    if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else -1L-                } ?: -1L-        }.getOrDefault(-1L)-         /**-         * The bytes of [uri], read once through [readBoundedBytes]; `null`-         * when unreadable or larger than [maxBytes]. A provider-declared-         * size past the cap is rejected without opening the stream at all.+         * A descriptor for [uri]'s content, or `null` when the content+         * cannot be reached at all.+         *+         * Preferred path: the provider's own descriptor. Where a provider+         * offers none, the stream is spooled to a cache file in+         * [READ_CHUNK_BYTES] chunks — memory stays O(chunk) at any file+         * size — and that file's descriptor is used. There is deliberately+         * no size cap: no path here materialises the file in the heap.          */-        internal suspend fun readUriBytes(-            context: Context,-            uri: Uri,-            maxBytes: Long = MAX_PDF_BYTES,-        ): ByteArray? = withContext(Dispatchers.IO) {-            val declared = declaredSizeBytes(context, uri)-            if (declared > maxBytes) return@withContext null+        internal fun acquireDocumentFd(context: Context, uri: Uri): DocumentFd? {             runCatching {-                context.contentResolver.openInputStream(uri)-                    ?.use { readBoundedBytes(it, maxBytes, declared) }+                context.contentResolver.openFileDescriptor(uri, "r")?.let { return DocumentFd(it, null) }+            }+            return runCatching {+                val spool = File.createTempFile("pdf-open-", ".pdf", context.cacheDir)+                try {+                    val copied = context.contentResolver.openInputStream(uri)?.use { input ->+                        FileOutputStream(spool).use { out ->+                            val chunk = ByteArray(READ_CHUNK_BYTES)+                            while (true) {+                                val n = input.read(chunk)+                                if (n < 0) break+                                out.write(chunk, 0, n)+                            }+                        }+                        true+                    } ?: false+                    if (!copied) {+                        runCatching { spool.delete() }+                        return null+                    }+                    DocumentFd(+                        ParcelFileDescriptor.open(spool, ParcelFileDescriptor.MODE_READ_ONLY),+                        spool,+                    )+                } catch (t: Throwable) {+                    runCatching { spool.delete() }+                    throw t+                }             }.getOrNull()         } -        /** True if [bytes] begins like a real PDF (header in the first 1024 bytes). */-        private fun bytesLookLikePdf(bytes: ByteArray): Boolean =-            indexOf(bytes.copyOf(minOf(bytes.size, 1024)), "%PDF-".toByteArray(Charsets.US_ASCII)) >= 0-         /**-         * Open [uri] and classify the outcome from the same bytes: opened,-         * encrypted (password needed/rejected), or failed. This is the-         * viewer's open path — one bounded read per attempt.+         * Open [uri] and classify the outcome from that one descriptor open:+         * opened, encrypted (password needed/rejected), or failed. This is+         * the viewer's open path — one mmap'd open attempt, no Kotlin+         * whole-file read at any size.          */         suspend fun openOutcome(             context: Context,@@ -421,26 +421,29 @@ class SafePdfDocument private constructor(             password: String? = null,         ): OpenOutcome = withContext(Dispatchers.IO) {             if (!PdfNative.isAvailable) return@withContext OpenOutcome.Failed(notPdf = false)-            val bytes = readUriBytes(context, uri)+            val acquired = acquireDocumentFd(context, uri)                 ?: return@withContext OpenOutcome.Failed(notPdf = !looksLikePdf(context, uri))-            val handle = if (password == null) {-                PdfNative.openDocument(bytes)-            } else {-                PdfNative.openDocumentWithPassword(bytes, password)-            }-            if (handle != 0L) {-                return@withContext OpenOutcome.Opened(SafePdfDocument(handle, PdfNative.getPageCount(handle)))-            }-            if (PdfNative.pdfPasswordState(bytes) == 1) {-                return@withContext OpenOutcome.NeedsPassword(rejected = password != null)+            acquired.use { doc ->+                when (val result = PdfNative.openDocumentFd(doc.pfd, password)) {+                    FD_NEEDS_PASSWORD ->+                        OpenOutcome.NeedsPassword(rejected = password != null)+                    FD_NOT_PDF -> OpenOutcome.Failed(notPdf = true)+                    else ->+                        if (result > 0L) {+                            OpenOutcome.Opened(+                                SafePdfDocument(result, PdfNative.getPageCount(result)),+                            )+                        } else {+                            OpenOutcome.Failed(notPdf = false)+                        }+                }             }-            OpenOutcome.Failed(notPdf = !bytesLookLikePdf(bytes))         }          /**          * Open [uri] as a safe PDF, or return `null` when the native lib is-         * unavailable, the bytes can't be read, or parsing fails. Encrypted PDFs-         * are opened with [password] (empty by default). Runs off the main thread.+         * unavailable, the content can't be reached, or parsing fails.+         * Encrypted PDFs are opened with [password]. Runs off the main thread.          */         suspend fun open(context: Context, uri: Uri, password: String? = null): SafePdfDocument? =             (openOutcome(context, uri, password) as? OpenOutcome.Opened)?.document@@ -448,8 +451,9 @@ class SafePdfDocument private constructor(         /** Encryption state of [uri]: 0 none, 1 needs password, 2 unsupported. */         suspend fun passwordState(context: Context, uri: Uri): Int =             withContext(Dispatchers.IO) {-                val bytes = readUriBytes(context, uri) ?: return@withContext 0-                PdfNative.pdfPasswordState(bytes)+                if (!PdfNative.isAvailable) return@withContext 0+                val acquired = acquireDocumentFd(context, uri) ?: return@withContext 0+                acquired.use { PdfNative.pdfPasswordStateFd(it.pfd) }             }          /**
pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.ktindex 65170b812e..c023ec132d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt@@ -91,11 +91,14 @@ fun CutGlueScreen(onBack: () -> Unit) {         ActivityResultContracts.OpenDocument()     ) { uri: Uri? ->         if (uri != null) scope.launch {-            // Same bounded read as the viewer open: a huge source PDF is-            // refused instead of being loaded whole into the heap.-            val bytes = SafePdfDocument.readUriBytes(context, uri) ?: return@launch-            val added = doc.appendPdf(bytes)-            repeat(added) { pageKeys.add(nextKey++.toLong()) }+            // Same descriptor path as the viewer open: the appended file is+            // mmap'd by native, never materialised in the heap, so a huge+            // source PDF appends instead of being refused for its size.+            val acquired = SafePdfDocument.acquireDocumentFd(context, uri) ?: return@launch+            acquired.use {+                val added = doc.appendPdfFd(it.pfd)+                repeat(added) { pageKeys.add(nextKey++.toLong()) }+            }         }     } 
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.ktindex 2ea665c1d8..fd90d6b20d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt@@ -44,8 +44,8 @@ internal fun rememberSafePdfDocument(      val loadState by produceState<LoadState>(LoadState.Loading, uri, password) {         value = LoadState.Loading-        // One bounded read classifies opened / encrypted / failed; a failed-        // open no longer re-reads the whole file to ask about encryption.+        // One descriptor open classifies opened / encrypted / failed; a+        // failed open never re-reads the file to ask about encryption.         value = when (val outcome = SafePdfDocument.openOutcome(context, uri, password)) {             is SafePdfDocument.OpenOutcome.Opened -> {                 needsPassword = false
pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.ktindex 9a6ceea07c..0a95622d97 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt@@ -2,6 +2,7 @@ // (Java_com_vayunmathur_pdf_util_PdfNative_* in Rust jni_bindings) package com.vayunmathur.pdf.util +import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.NativeLoader  /**@@ -33,6 +34,27 @@ object PdfNative {     /** Encryption state of [data]: 0 none, 1 needs password, 2 unsupported (AES). */     external fun pdfPasswordState(data: ByteArray): Int +    /**+     * Open the document behind [pfd], decrypting with [password] when+     * non-null. Returns a handle (>0), 0 on plain failure, or a negative+     * classification: -1 needs password, -2 unsupported encryption, -3 not a+     * PDF. Ownership: the caller keeps [pfd] and must close it; native dups+     * the underlying descriptor on entry and closes that dup exactly once.+     */+    external fun openDocumentFd(pfd: ParcelFileDescriptor, password: String?): Long++    /**+     * Encryption state of the document behind [pfd] (same codes and same+     * descriptor-ownership rule as [openDocumentFd]).+     */+    external fun pdfPasswordStateFd(pfd: ParcelFileDescriptor): Int++    /**+     * Append the document behind [pfd] to [handle]; returns pages added.+     * Same descriptor-ownership rule as [openDocumentFd].+     */+    external fun appendPdfFd(handle: Long, pfd: ParcelFileDescriptor): Int+     /** Serialize [handle] encrypted with the given passwords (RC4-128), or null. */     external fun saveEncrypted(handle: Long, userPw: String, ownerPw: String): ByteArray? 
pdf/src/main/rust/Cargo.toml
diff --git a/pdf/src/main/rust/Cargo.toml b/pdf/src/main/rust/Cargo.tomlindex b6a21fa9ed..62346cc75c 100644--- a/pdf/src/main/rust/Cargo.toml+++ b/pdf/src/main/rust/Cargo.toml@@ -28,6 +28,7 @@ aes.workspace = true sha2 = { workspace = true, features = ["oid"] } indexmap.workspace = true getrandom.workspace = true+memmap2.workspace = true  # Signing (features preserved per no-feature-loss) # PDF signature *creation* removed as a feature – dropped rsa/cms/x509-cert/spki/const-oid
pdf/src/main/rust/src/decrypt.rs
diff --git a/pdf/src/main/rust/src/decrypt.rs b/pdf/src/main/rust/src/decrypt.rsindex 1eee134933..42895e3e09 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -9,11 +9,21 @@ type CryptFnFactory = Box<dyn Fn(ObjectId) -> CryptFn>; /// the empty password does not satisfy. Returns: 0 no, 1 needs password, 2 /// unsupported encryption (e.g. AES). pub(crate) fn pdf_password_state(bytes: &[u8]) -> i32 {+    pdf_password_state_capped(bytes, true)+}++/// As [`pdf_password_state`] with no size ceiling, for the descriptor+/// (mmap) path whose bytes were never materialised as a heap copy.+pub(crate) fn pdf_password_state_unbounded(bytes: &[u8]) -> i32 {+    pdf_password_state_capped(bytes, false)+}++fn pdf_password_state_capped(bytes: &[u8], capped: bool) -> i32 {     // The same size guard `open_document_pw` applies, for the same bytes: this probe     // runs FIRST in the UI flow, so without it a 1 GB file is fully parsed here and     // only then refused at open. Reporting "no password needed" matches what open     // will do with it.-    if bytes.len() > crate::registry::MAX_PDF_BYTES {+    if capped && bytes.len() > crate::registry::MAX_PDF_BYTES {         return 0;     }     // Must match open_document_pw's loader: using the strict Document::load_mem here made a
pdf/src/main/rust/src/fdopen.rs
diff --git a/pdf/src/main/rust/src/fdopen.rs b/pdf/src/main/rust/src/fdopen.rsnew file mode 100644index 0000000000..c2aa3cb1b9--- /dev/null+++ b/pdf/src/main/rust/src/fdopen.rs@@ -0,0 +1,164 @@+use crate::*;+use std::os::unix::io::FromRawFd;++/// Result codes of the descriptor open (see `PdfNative.openDocumentFd`).+/// A positive value is a document handle; zero is a plain failure; the+/// negative values carry the classification Kotlin needs to pick between the+/// password prompt and the viewer's error state, all from the one attempt.+pub(crate) const FD_OPEN_NEEDS_PASSWORD: i64 = -1;+pub(crate) const FD_OPEN_UNSUPPORTED: i64 = -2;+pub(crate) const FD_OPEN_NOT_PDF: i64 = -3;++/// True if `bytes` begins like a real PDF (header in the first 1024 bytes).+fn bytes_look_like_pdf(bytes: &[u8]) -> bool {+    let head = &bytes[..bytes.len().min(1024)];+    head.windows(5).any(|w| w == b"%PDF-")+}++/// Open `bytes` with `password`, classifying a failure in the same pass:+/// handle, [`FD_OPEN_NEEDS_PASSWORD`], [`FD_OPEN_UNSUPPORTED`],+/// [`FD_OPEN_NOT_PDF`], or 0. No size ceiling applies on this path — the+/// bytes are a memory map, not a materialised copy, so there is no heap+/// cliff for a cap to guard (the byte[] JNI path keeps its own).+pub(crate) fn open_from_bytes(bytes: &[u8], password: &[u8]) -> i64 {+    let handle = open_document_unbounded(bytes, password);+    if handle != 0 {+        return handle;+    }+    match pdf_password_state_unbounded(bytes) {+        1 => FD_OPEN_NEEDS_PASSWORD,+        2 => FD_OPEN_UNSUPPORTED,+        _ if !bytes_look_like_pdf(bytes) => FD_OPEN_NOT_PDF,+        _ => 0,+    }+}++/// Run `f` over the bytes behind the owned descriptor `fd`.+///+/// Ownership contract (the JNI boundary states it for Kotlin): a descriptor+/// `>= 0` handed here is owned by native from that moment and is closed+/// exactly once, on every outcome — success, refusal, or panic unwind —+/// because the `File` below is its sole owner and drops unconditionally.+/// A negative descriptor is not a descriptor at all: nothing is closed and+/// `None` comes back.+///+/// The map lives only for the `f` call. `Document` owns every object it+/// parses, so the registry never borrows the mapping and it is unmapped+/// (and the descriptor closed) before the caller regains control.+fn with_mapped_fd<R>(fd: std::os::unix::io::RawFd, f: impl FnOnce(&[u8]) -> R) -> Option<R> {+    if fd < 0 {+        return None;+    }+    // SAFETY: the JNI contract above makes this descriptor exclusively ours;+    // `File::from_raw_fd` is the standard way to take that ownership so the+    // close-exactly-once rule is the type system's, not a manual `close`.+    let file = unsafe { std::fs::File::from_raw_fd(fd) };+    let len = file.metadata().ok()?.len();+    if len == 0 {+        return Some(f(&[]));+    }+    // SAFETY: read-only map of a provider document that is not truncated+    // while this synchronous parse runs; the mapped range is the file's+    // current length and the map never outlives this call (see above).+    let mmap = unsafe { memmap2::Mmap::map(&file).ok()? };+    Some(f(&mmap))+}++/// `openDocumentFd` core: mmap the owned descriptor and open from it.+pub(crate) fn open_document_fd(fd: i32, password: &[u8]) -> i64 {+    with_mapped_fd(fd, |bytes| open_from_bytes(bytes, password)).unwrap_or(0)+}++/// `pdfPasswordStateFd` core: encryption state of the mapped bytes.+pub(crate) fn pdf_password_state_fd(fd: i32) -> i32 {+    with_mapped_fd(fd, pdf_password_state_unbounded).unwrap_or(0)+}++/// `appendPdfFd` core: append the mapped document behind a live handle.+pub(crate) fn append_pdf_fd(handle: i64, fd: i32) -> i32 {+    with_mapped_fd(fd, |bytes| append_pdf(handle, bytes)).unwrap_or(0)+}++#[cfg(test)]+mod tests {+    use super::*;+    use std::io::Write;+    use std::os::unix::io::IntoRawFd;++    fn minimal_pdf() -> Vec<u8> {+        let content = "BT /F1 24 Tf 100 700 Td (Hello) Tj ET";+        let objs = [+            "<< /Type /Catalog /Pages 2 0 R >>".to_string(),+            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),+            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R \+             /Resources << /Font << /F1 5 0 R >> >> >>"+                .to_string(),+            format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),+            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),+        ];+        let mut out = Vec::from(&b"%PDF-1.4\n"[..]);+        let mut offsets = Vec::new();+        for (i, body) in objs.iter().enumerate() {+            offsets.push(out.len());+            out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());+        }+        let xref = out.len();+        out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+        for off in &offsets {+            out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());+        }+        out.extend_from_slice(+            format!(+                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF",+                objs.len() + 1+            )+            .as_bytes(),+        );+        out+    }++    fn fd_for(bytes: &[u8], name: &str) -> i32 {+        let path = std::env::temp_dir().join(name);+        let mut file = std::fs::File::create(&path).expect("create temp pdf");+        file.write_all(bytes).expect("write temp pdf");+        drop(file);+        std::fs::File::open(&path)+            .expect("reopen temp pdf")+            .into_raw_fd()+    }++    fn fd_is_closed(fd: i32) -> bool {+        std::fs::read_link(format!("/proc/self/fd/{fd}")).is_err()+    }++    #[test]+    fn fd_open_opens_and_closes_exactly_once() {+        let fd = fd_for(&minimal_pdf(), "pdf-render-fd-open-test.pdf");+        let handle = open_document_fd(fd, &[]);+        assert!(handle > 0, "fd open must produce a handle");+        assert!(fd_is_closed(fd), "native must close the handed-off fd");+        assert_eq!(page_count(handle), 1);+        close_document(handle);+    }++    #[test]+    fn fd_open_classifies_garbage_as_not_pdf() {+        let fd = fd_for(b"hello, not a pdf", "pdf-render-fd-garbage-test.pdf");+        assert_eq!(open_document_fd(fd, &[]), FD_OPEN_NOT_PDF);+        assert!(fd_is_closed(fd));+    }++    #[test]+    fn negative_fd_is_refused_without_a_close() {+        assert_eq!(open_document_fd(-1, &[]), 0);+        assert_eq!(pdf_password_state_fd(-1), 0);+        assert_eq!(append_pdf_fd(0, -1), 0);+    }++    #[test]+    fn fd_password_state_of_plain_pdf_is_zero() {+        let fd = fd_for(&minimal_pdf(), "pdf-render-fd-state-test.pdf");+        assert_eq!(pdf_password_state_fd(fd), 0);+        assert!(fd_is_closed(fd));+    }+}
pdf/src/main/rust/src/jni_bindings.rs
diff --git a/pdf/src/main/rust/src/jni_bindings.rs b/pdf/src/main/rust/src/jni_bindings.rsindex 73d32b3a85..c267ebae46 100644--- a/pdf/src/main/rust/src/jni_bindings.rs+++ b/pdf/src/main/rust/src/jni_bindings.rs@@ -10,7 +10,9 @@ use std::panic::{catch_unwind, AssertUnwindSafe};  /// Maximum Java byte[] size we accept (200 MB) to prevent OOM DoS. /// Audit #7: unbounded convert_byte_array copy. An Intent with huge PDF could OOM native heap,-/// and registry then duplicates via Document::load_mem.+/// and registry then duplicates via Document::load_mem. This guards only the+/// byte[] entry points, whose input is already materialised in the Java heap;+/// the descriptor path (`openDocumentFd`) mmaps instead and has no cap. const MAX_JAVA_BYTE_ARRAY_BYTES: usize = 200 * 1024 * 1024; /// Drops the cached search index for `handle` on scope exit, so a document-mutating /// entry point cannot leave `ensure_index` serving text from before the edit.@@ -412,3 +414,4 @@ fn add_ink_inner<'local>( include!("jni_bindings_part1.rs"); include!("jni_bindings_part2.rs"); include!("jni_bindings_part3.rs");+include!("jni_bindings_part4.rs");
pdf/src/main/rust/src/jni_bindings_part4.rs
diff --git a/pdf/src/main/rust/src/jni_bindings_part4.rs b/pdf/src/main/rust/src/jni_bindings_part4.rsnew file mode 100644index 0000000000..c1a5ed2ec8--- /dev/null+++ b/pdf/src/main/rust/src/jni_bindings_part4.rs@@ -0,0 +1,134 @@++// ---------------------------------------------------------------------------+// Descriptor-based JNI entry points (#951). Kotlin passes its+// `ParcelFileDescriptor` and keeps ownership of (and closes) that original;+// native dups the descriptor on entry and the dup is owned by native and+// closed exactly once there (see `with_mapped_fd`).+// ---------------------------------------------------------------------------++/// Borrow the raw descriptor out of a `ParcelFileDescriptor` and dup it, so+/// the returned descriptor is owned solely by native while Kotlin keeps (and+/// closes) the original. `None` when the object carries no descriptor.+fn dup_pfd_fd<'local>(env: &mut Env<'local>, pfd: &jni::objects::JObject<'local>) -> Option<i32> {+    use std::os::unix::io::{FromRawFd, IntoRawFd};+    if pfd.is_null() {+        return None;+    }+    let raw = env+        .call_method(pfd, jni_str!("getFd"), jni::jni_sig!("()I"), &[])+        .ok()?+        .i()+        .ok()?;+    if raw < 0 {+        return None;+    }+    // SAFETY: `raw` stays owned by the Kotlin-side ParcelFileDescriptor,+    // which outlives this call; we only dup it and forget the borrow wrapper+    // so the original is never closed here. The dup is ours alone.+    let borrowed = unsafe { std::fs::File::from_raw_fd(raw) };+    let dup = borrowed.try_clone().ok()?;+    std::mem::forget(borrowed);+    Some(dup.into_raw_fd())+}++fn open_document_fd_inner<'local>(+    env: &mut Env<'local>,+    pfd: jni::objects::JObject<'local>,+    password: JString<'local>,+) -> jlong {+    let pw = if password.is_null() {+        String::new()+    } else {+        match jstr_safe(env, &password) {+            Ok(s) => s,+            Err(e) => {+                throw_iae(env, &e);+                return 0;+            }+        }+    };+    let Some(fd) = dup_pfd_fd(env, &pfd) else {+        return 0;+    };+    open_document_fd(fd, pw.as_bytes()) as jlong+}++/// `PdfNative.openDocumentFd(ParcelFileDescriptor, String) -> long`: handle+/// (>0), 0 on plain failure, or a negative `FD_OPEN_*` classification.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_openDocumentFd<'local>(+    mut env: EnvUnowned<'local>,+    _class: JClass<'local>,+    fd: jni::objects::JObject<'local>,+    password: JString<'local>,+) -> jlong {+    env.with_env(|env| -> jni::errors::Result<jlong> {+        match catch_unwind(AssertUnwindSafe(|| {+            open_document_fd_inner(&mut *env, fd, password)+        })) {+            Ok(v) => Ok(v),+            Err(_) => {+                env.exception_clear();+                let _ = env.throw_new(+                    jni_str!("java/lang/RuntimeException"),+                    jni_str!("Native panic in openDocumentFd"),+                );+                Ok(0)+            }+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++/// `PdfNative.pdfPasswordStateFd(ParcelFileDescriptor) -> int` (0 none, 1+/// needs pw, 2 unsupported).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_pdfPasswordStateFd<'local>(+    mut env: EnvUnowned<'local>,+    _class: JClass<'local>,+    fd: jni::objects::JObject<'local>,+) -> jint {+    env.with_env(|env| -> jni::errors::Result<jint> {+        match catch_unwind(AssertUnwindSafe(|| {+            dup_pfd_fd(&mut *env, &fd).map_or(0, pdf_password_state_fd)+        })) {+            Ok(v) => Ok(v),+            Err(_) => {+                env.exception_clear();+                let _ = env.throw_new(+                    jni_str!("java/lang/RuntimeException"),+                    jni_str!("Native panic in pdfPasswordStateFd"),+                );+                Ok(0)+            }+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++/// `PdfNative.appendPdfFd(long, ParcelFileDescriptor) -> int` (pages added).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_appendPdfFd<'local>(+    mut env: EnvUnowned<'local>,+    _class: JClass<'local>,+    handle: jlong,+    fd: jni::objects::JObject<'local>,+) -> jint {+    env.with_env(|env| -> jni::errors::Result<jint> {+        let _invalidate = InvalidateSearchIndex(handle);+        match catch_unwind(AssertUnwindSafe(|| {+            dup_pfd_fd(&mut *env, &fd).map_or(0, |owned| append_pdf_fd(handle, owned))+        })) {+            Ok(v) => Ok(v),+            Err(_) => {+                env.exception_clear();+                let _ = env.throw_new(+                    jni_str!("java/lang/RuntimeException"),+                    jni_str!("Native panic in appendPdfFd"),+                );+                Ok(0)+            }+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex 420a4c4c91..b1cc0ef39f 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -47,6 +47,8 @@ mod type3;  mod registry; pub(crate) use registry::*;+mod fdopen;+pub(crate) use fdopen::*; mod content; mod decrypt; pub(crate) use decrypt::*;
pdf/src/main/rust/src/registry.rs
diff --git a/pdf/src/main/rust/src/registry.rs b/pdf/src/main/rust/src/registry.rsindex baf0ea7066..7977783547 100644--- a/pdf/src/main/rust/src/registry.rs+++ b/pdf/src/main/rust/src/registry.rs@@ -15,7 +15,9 @@ use indexmap::IndexMap; //   Documented order: registry → index_cache.  const MAX_REG_DOCS: usize = 8;-/// Max PDF size accepted to prevent zip-bomb / OOM DoS (200 MB).+/// Max PDF size accepted on the byte[] entry points, to prevent zip-bomb /+/// OOM DoS from a materialised copy (200 MB). The descriptor (mmap) path+/// does not consult this: it materialises nothing. pub(crate) const MAX_PDF_BYTES: usize = 200 * 1024 * 1024;  /// Nesting-depth ceiling for the raw pre-scan (see [`nesting_exceeds`]).@@ -46,7 +48,6 @@ pub(crate) fn next_handle() -> i64 { /// supports RC4 and AES (V4/V5) standard security handlers. Returns 0 on parse /// failure, wrong password, or unsupported encryption. ///-/// Size guard: rejects inputs larger than 200 MB to prevent OOM DoS. /// Load `bytes` and, if encrypted, decrypt with `password`; None on any /// failure (bad password, unparseable, unsupported). ///@@ -80,15 +81,9 @@ pub(crate) fn open_decrypted(bytes: &[u8], password: &[u8]) -> Option<Document>     Some(doc) } -pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 {-    // Zip-bomb / OOM guard: reject absurdly large PDF before parsing.-    if bytes.len() > MAX_PDF_BYTES {-        return 0;-    }-    let doc = match open_decrypted(bytes, password) {-        Some(d) => d,-        None => return 0,-    };+/// Store `doc` under a fresh handle, evicting the least-recently-used+/// document when the registry is full. Returns the non-zero handle.+fn register_document(doc: Document) -> i64 {     let handle = next_handle();     // Lock ordering: registry first, then index_cache if eviction needed.     let mut map = registry()@@ -109,6 +104,29 @@ pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 {     handle } +pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 {+    // Zip-bomb / OOM guard: reject absurdly large PDF before parsing. This+    // guards the byte[] entry points, whose input already exists as a heap+    // copy; the descriptor path (fdopen) mmaps and enters below instead.+    if bytes.len() > MAX_PDF_BYTES {+        return 0;+    }+    match open_decrypted(bytes, password) {+        Some(d) => register_document(d),+        None => 0,+    }+}++/// Open with no size ceiling: the caller's bytes are a memory map of the+/// file (fdopen), so no materialised copy exists for a cap to protect.+/// Genuine parse failure is the only refusal, exactly as for small files.+pub(crate) fn open_document_unbounded(bytes: &[u8], password: &[u8]) -> i64 {+    match open_decrypted(bytes, password) {+        Some(d) => register_document(d),+        None => 0,+    }+}+ pub(crate) fn open_document(bytes: &[u8]) -> i64 {     // No password (empty, built at runtime — not a hard-coded credential).     open_document_pw(bytes, &Vec::<u8>::new())
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.ktindex 965a98bef0..fa51491287 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt@@ -3,9 +3,8 @@ package com.vayunmathur.pdf.platform import android.content.Context import android.net.Uri import androidx.test.core.app.ApplicationProvider-import java.io.ByteArrayInputStream+import com.vayunmathur.pdf.util.PdfNative import java.io.File-import java.io.InputStream import java.io.RandomAccessFile import kotlin.test.Test import kotlin.test.assertEquals@@ -20,36 +19,16 @@ import org.robolectric.annotation.GraphicsMode  /**  * Issue #951: opening a large PDF crashed the app. The viewer open path- * used to materialise the whole file with `readBytes()` (plus a second- * whole-file read on the failure path to probe encryption). Opening now- * goes through one chunked, capped read: oversized inputs fail with the- * viewer's error state instead of an out-of-memory kill, and nothing at- * open scales unboundedly with file size.+ * used to materialise the whole file in the Kotlin heap (a second capped+ * attempt then failed larger files on an error screen). Opening now hands+ * native a detached descriptor, which Rust mmaps: no whole-file copy exists+ * in Kotlin or across JNI, and file size alone never refuses an open.  */ @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) class SafePdfOpenBoundsTest {     private val ctx: Context get() = ApplicationProvider.getApplicationContext() -    /** Generates zero bytes on demand; counts how many were consumed. */-    private class GeneratingInputStream(private val total: Long) : InputStream() {-        var bytesRead: Long = 0-            private set--        override fun read(): Int {-            if (bytesRead >= total) return -1-            bytesRead++-            return 0-        }--        override fun read(b: ByteArray, off: Int, len: Int): Int {-            if (bytesRead >= total) return -1-            val n = minOf(len.toLong(), total - bytesRead).toInt()-            bytesRead += n-            return n-        }-    }-     private fun manyPagePdf(pages: Int): ByteArray {         val sb = StringBuilder("%PDF-1.4\n")         val offsets = mutableListOf<Int>()@@ -90,36 +69,55 @@ class SafePdfOpenBoundsTest {         return Uri.fromFile(f)     } -    @Test fun boundedReadRoundTripsContent() {-        for (size in listOf(0, 1, 65_535, 65_536, 65_537, 200_001)) {-            val data = ByteArray(size) { (it % 251).toByte() }-            val read = SafePdfDocument.readBoundedBytes(ByteArrayInputStream(data), maxBytes = 1_000_000)-            assertNotNull(read, "size $size")-            assertTrue(data.contentEquals(read), "size $size must round-trip byte-exact")-        }-    }--    @Test fun boundedReadAtExactCapSucceeds() {-        val cap = 100_000L-        val data = ByteArray(cap.toInt()) { 0x41 }-        val read = SafePdfDocument.readBoundedBytes(ByteArrayInputStream(data), maxBytes = cap)-        assertNotNull(read)-        assertEquals(cap, read.size.toLong())-    }--    @Test fun boundedReadOverCapReturnsNullAndStopsEarly() {-        // A 5 MB logical stream with a 100 KB cap: the reader must refuse-        // after at most one chunk past the cap, never consuming the stream.-        val stream = GeneratingInputStream(total = 5_000_000)-        val read = SafePdfDocument.readBoundedBytes(stream, maxBytes = 100_000)-        assertNull(read)-        assertTrue(-            stream.bytesRead <= 100_000 + 65_536,-            "reader consumed ${stream.bytesRead} bytes for a 100 KB cap",+    /**+     * A one-page PDF whose file is larger than the old 256 MiB refusal cap,+     * without materialising that many bytes: one unreferenced stream object+     * declares a huge length and the gap is a sparse hole (zeros on read).+     */+    private fun sparseLargePdfFile(): File {+        val content = "BT /F1 12 Tf 72 720 Td (Sparse) Tj ET"+        val objs = listOf(+            "<< /Type /Catalog /Pages 2 0 R >>",+            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " ++                "/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",+            "<< /Length ${content.length} >>\nstream\n$content\nendstream",+            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",         )+        val head = StringBuilder("%PDF-1.4\n")+        val offsets = mutableListOf<Long>()+        objs.forEachIndexed { i, body ->+            offsets.add(head.length.toLong())+            head.append("${i + 1} 0 obj\n$body\nendobj\n")+        }+        val hugeLen = 270_000_000L+        val obj6Offset = head.length.toLong()+        val streamHead = "6 0 obj\n<< /Length $hugeLen >>\nstream\n"+        val streamDataStart = obj6Offset + streamHead.length+        val tail = "\nendstream\nendobj\n"+        val xrefPos = streamDataStart + hugeLen + tail.length+        val xref = StringBuilder("xref\n0 7\n0000000000 65535 f \n")+        for (off in offsets + obj6Offset) {+            xref.append(off.toString().padStart(10, '0')).append(" 00000 n \n")+        }+        xref.append("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n$xrefPos\n%%EOF")++        val f = File(ctx.cacheDir, "bounds-sparse-huge.pdf")+        RandomAccessFile(f, "rw").use { raf ->+            raf.setLength(0)+            raf.write(head.toString().toByteArray(Charsets.US_ASCII))+            raf.write(streamHead.toByteArray(Charsets.US_ASCII))+            raf.seek(xrefPos)+            // Seeking past the stream data leaves a sparse hole; the xref+            // section itself is the only other real bytes in the file.+            raf.seek(streamDataStart + hugeLen)+            raf.write(tail.toByteArray(Charsets.US_ASCII))+            raf.write(xref.toString().toByteArray(Charsets.US_ASCII))+        }+        return f     } -    @Test fun openOutcomeClassifiesFromOneRead() { runBlocking {+    @Test fun openOutcomeClassifiesFromOneOpen() { runBlocking {         val garbage = SafePdfDocument.openOutcome(ctx, fileFor("hello".toByteArray(), "bounds-plain.pdf"))         assertTrue(garbage is SafePdfDocument.OpenOutcome.Failed)         assertTrue(garbage.notPdf)@@ -135,7 +133,31 @@ class SafePdfOpenBoundsTest {         opened.document.close()     } } -    @Test fun openManyPageBookThroughBoundedPath() { runBlocking {+    @Test fun encryptedOutcomeClassifiesFromOneOpen() { runBlocking {+        val srcHandle = PdfNative.openDocument(manyPagePdf(1))+        assertTrue(srcHandle != 0L)+        val encrypted = try {+            PdfNative.saveEncrypted(srcHandle, "userpw", "ownerpw")+        } finally {+            PdfNative.closeDocument(srcHandle)+        }+        assertNotNull(encrypted)+        val uri = fileFor(encrypted, "bounds-encrypted.pdf")++        val noPassword = SafePdfDocument.openOutcome(ctx, uri)+        assertTrue(noPassword is SafePdfDocument.OpenOutcome.NeedsPassword)+        assertFalse(noPassword.rejected)++        val wrong = SafePdfDocument.openOutcome(ctx, uri, "wrong")+        assertTrue(wrong is SafePdfDocument.OpenOutcome.NeedsPassword)+        assertTrue(wrong.rejected)++        val opened = SafePdfDocument.openOutcome(ctx, uri, "userpw")+        assertTrue(opened is SafePdfDocument.OpenOutcome.Opened)+        opened.document.close()+    } }++    @Test fun openManyPageBookThroughDescriptorPath() { runBlocking {         val pages = 600         val doc = SafePdfDocument.open(ctx, fileFor(manyPagePdf(pages), "bounds-book.pdf"))         assertNotNull(doc)@@ -150,14 +172,38 @@ class SafePdfOpenBoundsTest {         }     } } -    @Test fun oversizedFileFailsCleanlyInsteadOfLoading() { runBlocking {-        val f = File(ctx.cacheDir, "bounds-huge.pdf")-        RandomAccessFile(f, "rw").use { it.setLength(SafePdfDocument.MAX_PDF_BYTES + 1) }-        assertNull(SafePdfDocument.open(ctx, Uri.fromFile(f)))+    @Test fun sparseFileOverOldCapOpensThroughDescriptorPath() { runBlocking {+        val f = sparseLargePdfFile()+        assertTrue(+            f.length() > 256L * 1024 * 1024,+            "fixture must exceed the removed 256 MiB refusal cap: ${f.length()}",+        )         val outcome = SafePdfDocument.openOutcome(ctx, Uri.fromFile(f))-        assertTrue(outcome is SafePdfDocument.OpenOutcome.Failed)+        assertTrue(outcome is SafePdfDocument.OpenOutcome.Opened, "outcome=$outcome")+        try {+            assertEquals(1, outcome.document.pageCount)+            assertNotNull(outcome.document.renderPage(0))+        } finally {+            outcome.document.close()+        }     } } +    @Test fun viewerOpenPathHasNoWholeFileReadSeam() {+        // By construction: the capped whole-file reader that used to feed+        // the viewer open (and refuse oversize) no longer exists, so no+        // Kotlin code path can materialise the document or cap its size.+        val companion = SafePdfDocument.Companion::class.java+        assertFalse(+            companion.declaredFields.any { it.name == "MAX_PDF_BYTES" },+            "the 256 MiB refusal constant must be gone",+        )+        // Internal members carry a `$module` suffix in bytecode.+        val methods = companion.declaredMethods.map { it.name }+        assertFalse(methods.any { it.startsWith("readUriBytes") }, "whole-file URI read must be gone")+        assertFalse(methods.any { it.startsWith("readBoundedBytes") }, "capped whole-file read must be gone")+        assertTrue(methods.any { it.startsWith("acquireDocumentFd") }, "descriptor acquisition is the open seam")+    }+     @Test fun hugeEmbeddedImagePayloadIsSkippedNotDecoded() {         // Format 1 is the JPEG passthrough; a payload past the image budget         // is skipped before any bitmap allocation is attempted.