From 22243c312ebe4c94bf7c313b83132875f983be4b Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sun, 8 Nov 2026 12:39:54 +0000 Subject: [PATCH 1/3] Resolve file URIs through ContentResolver Firebase Storage's putFile(Uri) opens the file through ContentResolver.openFileDescriptor to learn its size and then reads it through openInputStream, and uses getType for the content type when the metadata has none. The ContentResolver shim was empty, so putFile(Uri) failed on the JVM with a NoSuchMethodError. ContentResolver now resolves file: URIs (and bare paths) to files, backed by a new ParcelFileDescriptor shim over a RandomAccessFile with the Android mode flags, and guesses the MIME type from the file name. Other schemes are reported as not found, as there are no content providers on the JVM. --- .../java/android/content/ContentResolver.java | 5 -- .../java/android/content/ContentResolver.kt | 48 ++++++++++ .../java/android/os/ParcelFileDescriptor.kt | 63 ++++++++++++++ src/test/kotlin/ContentResolverTest.kt | 87 +++++++++++++++++++ 4 files changed, 198 insertions(+), 5 deletions(-) delete mode 100644 src/main/java/android/content/ContentResolver.java create mode 100644 src/main/java/android/content/ContentResolver.kt create mode 100644 src/main/java/android/os/ParcelFileDescriptor.kt create mode 100644 src/test/kotlin/ContentResolverTest.kt diff --git a/src/main/java/android/content/ContentResolver.java b/src/main/java/android/content/ContentResolver.java deleted file mode 100644 index aee556b..0000000 --- a/src/main/java/android/content/ContentResolver.java +++ /dev/null @@ -1,5 +0,0 @@ -package android.content; - -public class ContentResolver { - -} diff --git a/src/main/java/android/content/ContentResolver.kt b/src/main/java/android/content/ContentResolver.kt new file mode 100644 index 0000000..d3f350f --- /dev/null +++ b/src/main/java/android/content/ContentResolver.kt @@ -0,0 +1,48 @@ +package android.content + +import android.net.Uri +import android.os.ParcelFileDescriptor +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.net.URLConnection + +/** + * Resolves content URIs on the JVM, where there are no content providers: only `file:` URIs (and URIs with no scheme, + * taken as paths) name anything. Firebase Storage's `putFile(Uri)` reads the uploaded file through this. + */ +open class ContentResolver { + + /** The file descriptor for [uri] opened with [mode] (`"r"`, `"w"`, `"wt"`, `"wa"`, `"rw"` or `"rwt"`). */ + @Throws(FileNotFoundException::class) + open fun openFileDescriptor(uri: Uri, mode: String): ParcelFileDescriptor? = + ParcelFileDescriptor.open(fileFor(uri), ParcelFileDescriptor.parseMode(mode)) + + @Throws(FileNotFoundException::class) + open fun openInputStream(uri: Uri): InputStream? = FileInputStream(fileFor(uri)) + + @Throws(FileNotFoundException::class) + open fun openOutputStream(uri: Uri): OutputStream? = openOutputStream(uri, "w") + + /** An output stream on [uri] opened with [mode] (`"w"`, `"wt"`, `"wa"`, `"rw"` or `"rwt"`). */ + @Throws(FileNotFoundException::class) + open fun openOutputStream(uri: Uri, mode: String): OutputStream? = + FileOutputStream(fileFor(uri), ParcelFileDescriptor.parseMode(mode) and ParcelFileDescriptor.MODE_APPEND != 0) + + /** The MIME type guessed from the file name, or null when there is no guess. */ + open fun getType(uri: Uri): String? = uri.lastPathSegment?.let(URLConnection::guessContentTypeFromName) + + private fun fileFor(uri: Uri): File = when (uri.scheme) { + null, SCHEME_FILE -> File(uri.path ?: throw FileNotFoundException("No path in $uri")) + else -> throw FileNotFoundException("Cannot open ${uri.scheme}: URIs on the JVM: $uri") + } + + companion object { + const val SCHEME_CONTENT = "content" + const val SCHEME_ANDROID_RESOURCE = "android.resource" + const val SCHEME_FILE = "file" + } +} diff --git a/src/main/java/android/os/ParcelFileDescriptor.kt b/src/main/java/android/os/ParcelFileDescriptor.kt new file mode 100644 index 0000000..739df1d --- /dev/null +++ b/src/main/java/android/os/ParcelFileDescriptor.kt @@ -0,0 +1,63 @@ +package android.os + +import java.io.Closeable +import java.io.File +import java.io.FileDescriptor +import java.io.FileNotFoundException +import java.io.IOException +import java.io.RandomAccessFile + +/** + * A file descriptor on the JVM. There is no Parcel to carry it across processes, so it simply holds the + * [RandomAccessFile] opened on the file; Firebase Storage opens one to learn the size of a file it uploads. + */ +class ParcelFileDescriptor private constructor(private val file: RandomAccessFile) : Closeable { + + val fileDescriptor: FileDescriptor + get() = file.fd + + /** The size of the file in bytes, or -1 when it cannot be determined. */ + val statSize: Long + get() = try { + file.length() + } catch (e: IOException) { + -1 + } + + @Throws(IOException::class) + override fun close() = file.close() + + companion object { + const val MODE_WORLD_READABLE = 0x00000001 + const val MODE_WORLD_WRITEABLE = 0x00000002 + const val MODE_READ_ONLY = 0x10000000 + const val MODE_WRITE_ONLY = 0x20000000 + const val MODE_READ_WRITE = 0x30000000 + const val MODE_CREATE = 0x08000000 + const val MODE_TRUNCATE = 0x04000000 + const val MODE_APPEND = 0x02000000 + + /** Opens [file] with the `MODE_*` flags in [mode], failing like Android when it is missing and may not be created. */ + @JvmStatic + @Throws(FileNotFoundException::class) + fun open(file: File, mode: Int): ParcelFileDescriptor { + val writable = mode and MODE_WRITE_ONLY != 0 + if (!file.exists() && (!writable || mode and MODE_CREATE == 0)) throw FileNotFoundException(file.path) + val opened = RandomAccessFile(file, if (writable) "rw" else "r") + if (writable && mode and MODE_TRUNCATE != 0) opened.setLength(0) + if (writable && mode and MODE_APPEND != 0) opened.seek(opened.length()) + return ParcelFileDescriptor(opened) + } + + /** The `MODE_*` flags for a mode string of `ContentResolver.openFileDescriptor`, as Android parses it. */ + @JvmStatic + fun parseMode(mode: String): Int = when (mode) { + "r" -> MODE_READ_ONLY + "w", "wt" -> MODE_WRITE_ONLY or MODE_CREATE or MODE_TRUNCATE + "wa" -> MODE_WRITE_ONLY or MODE_CREATE or MODE_APPEND + "rw" -> MODE_READ_WRITE or MODE_CREATE + "rwt" -> MODE_READ_WRITE or MODE_CREATE or MODE_TRUNCATE + else -> throw IllegalArgumentException("Bad mode: $mode") + } + } +} diff --git a/src/test/kotlin/ContentResolverTest.kt b/src/test/kotlin/ContentResolverTest.kt new file mode 100644 index 0000000..2e8eb8c --- /dev/null +++ b/src/test/kotlin/ContentResolverTest.kt @@ -0,0 +1,87 @@ +/* + * Tests for the android.content.ContentResolver shim, through which Firebase Storage reads the file behind a + * putFile(Uri) upload: the file's size via a ParcelFileDescriptor, its content type and its bytes. + */ +import android.app.Application +import android.net.Uri +import android.os.ParcelFileDescriptor +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.FileNotFoundException + +class ContentResolverTest { + + @get:Rule + val folder = TemporaryFolder() + + private val resolver = Application().contentResolver + + private fun file(name: String, content: String): File = File(folder.root, name).apply { writeText(content) } + + @Test + fun `file descriptor reports the size of a file uri`() { + val file = file("upload.txt", "thirteen byte") + resolver.openFileDescriptor(Uri.parse(file.toURI().toString()), "r")!!.use { descriptor -> + assertEquals(13, descriptor.statSize) + } + } + + @Test + fun `file descriptor accepts a triple slash file uri and a bare path`() { + val file = file("upload.txt", "content") + resolver.openFileDescriptor(Uri.parse("file://${file.absolutePath}"), "r")!!.use { assertEquals(7, it.statSize) } + resolver.openFileDescriptor(Uri.parse(file.absolutePath), "r")!!.use { assertEquals(7, it.statSize) } + } + + @Test + fun `input stream reads the file`() { + val file = file("upload.bin", "bytes") + val read = resolver.openInputStream(Uri.parse(file.toURI().toString()))!!.use { it.readBytes() } + assertArrayEquals("bytes".toByteArray(), read) + } + + @Test + fun `output stream writes and appends`() { + val file = File(folder.root, "download.txt") + val uri = Uri.parse(file.toURI().toString()) + resolver.openOutputStream(uri)!!.use { it.write("one".toByteArray()) } + resolver.openOutputStream(uri, "wa")!!.use { it.write("two".toByteArray()) } + assertEquals("onetwo", file.readText()) + resolver.openOutputStream(uri, "wt")!!.use { it.write("three".toByteArray()) } + assertEquals("three", file.readText()) + } + + @Test + fun `type is guessed from the file name`() { + assertEquals("text/plain", resolver.getType(Uri.parse("file:///tmp/notes.txt"))) + assertEquals("image/png", resolver.getType(Uri.parse("file:///tmp/photo.png"))) + assertNull(resolver.getType(Uri.parse("file:///tmp/blob"))) + } + + @Test + fun `missing files and other schemes are not found`() { + assertThrows(FileNotFoundException::class.java) { + resolver.openFileDescriptor(Uri.parse(File(folder.root, "missing.txt").toURI().toString()), "r") + } + assertThrows(FileNotFoundException::class.java) { + resolver.openInputStream(Uri.parse("content://media/external/images/1")) + } + } + + @Test + fun `write modes create truncate and append`() { + val file = File(folder.root, "modes.txt") + assertThrows(FileNotFoundException::class.java) { ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) } + ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("w")).use { assertEquals(0, it.statSize) } + file.writeText("longer content") + ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa")).use { assertEquals(14, it.statSize) } + ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wt")).use { assertEquals(0, it.statSize) } + assertThrows(IllegalArgumentException::class.java) { ParcelFileDescriptor.parseMode("x") } + } +} From 55f7ef80b5b027aadc9b32f32de6498d2dd78d23 Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sun, 8 Nov 2026 13:27:10 +0000 Subject: [PATCH 2/3] Give ParcelFileDescriptor the access its mode asks for Read-only descriptors are backed by a FileInputStream, write-only ones by a FileOutputStream that truncates or appends (so concurrent "wa" descriptors interleave at the end of the file), and read-write ones by a RandomAccessFile that no longer truncates for "rw". openOutputStream rejects read-only modes and writes in place for "rw". adoptFd is declared and unsupported, matching the SQLite shim's reference. --- .../java/android/content/ContentResolver.kt | 23 ++++++++-- .../java/android/os/ParcelFileDescriptor.kt | 43 +++++++++++++------ src/test/kotlin/ContentResolverTest.kt | 42 ++++++++++++++++++ 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/src/main/java/android/content/ContentResolver.kt b/src/main/java/android/content/ContentResolver.kt index d3f350f..ff73c44 100644 --- a/src/main/java/android/content/ContentResolver.kt +++ b/src/main/java/android/content/ContentResolver.kt @@ -5,10 +5,11 @@ import android.os.ParcelFileDescriptor import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException -import java.io.FileOutputStream import java.io.InputStream import java.io.OutputStream import java.net.URLConnection +import java.nio.file.Files +import java.nio.file.StandardOpenOption /** * Resolves content URIs on the JVM, where there are no content providers: only `file:` URIs (and URIs with no scheme, @@ -27,10 +28,24 @@ open class ContentResolver { @Throws(FileNotFoundException::class) open fun openOutputStream(uri: Uri): OutputStream? = openOutputStream(uri, "w") - /** An output stream on [uri] opened with [mode] (`"w"`, `"wt"`, `"wa"`, `"rw"` or `"rwt"`). */ + /** + * An output stream on [uri] opened with [mode]: `"w"` and `"wt"` truncate, `"wa"` appends, `"rw"` writes in place + * from the start and `"rwt"` truncates; `"r"` cannot open an output stream. + */ @Throws(FileNotFoundException::class) - open fun openOutputStream(uri: Uri, mode: String): OutputStream? = - FileOutputStream(fileFor(uri), ParcelFileDescriptor.parseMode(mode) and ParcelFileDescriptor.MODE_APPEND != 0) + open fun openOutputStream(uri: Uri, mode: String): OutputStream? { + val flags = ParcelFileDescriptor.parseMode(mode) + require(flags and ParcelFileDescriptor.MODE_WRITE_ONLY != 0) { "Mode '$mode' cannot open an output stream" } + val file = fileFor(uri) + if (!file.exists() && flags and ParcelFileDescriptor.MODE_CREATE == 0) throw FileNotFoundException(file.path) + val options = buildList { + add(StandardOpenOption.WRITE) + if (flags and ParcelFileDescriptor.MODE_CREATE != 0) add(StandardOpenOption.CREATE) + if (flags and ParcelFileDescriptor.MODE_TRUNCATE != 0) add(StandardOpenOption.TRUNCATE_EXISTING) + if (flags and ParcelFileDescriptor.MODE_APPEND != 0) add(StandardOpenOption.APPEND) + } + return Files.newOutputStream(file.toPath(), *options.toTypedArray()) + } /** The MIME type guessed from the file name, or null when there is no guess. */ open fun getType(uri: Uri): String? = uri.lastPathSegment?.let(URLConnection::guessContentTypeFromName) diff --git a/src/main/java/android/os/ParcelFileDescriptor.kt b/src/main/java/android/os/ParcelFileDescriptor.kt index 739df1d..8230096 100644 --- a/src/main/java/android/os/ParcelFileDescriptor.kt +++ b/src/main/java/android/os/ParcelFileDescriptor.kt @@ -3,29 +3,34 @@ package android.os import java.io.Closeable import java.io.File import java.io.FileDescriptor +import java.io.FileInputStream import java.io.FileNotFoundException +import java.io.FileOutputStream import java.io.IOException import java.io.RandomAccessFile /** - * A file descriptor on the JVM. There is no Parcel to carry it across processes, so it simply holds the - * [RandomAccessFile] opened on the file; Firebase Storage opens one to learn the size of a file it uploads. + * A file descriptor on the JVM. There is no Parcel to carry it across processes, so it simply holds the stream opened + * on the file, with the access the `MODE_*` flags ask for: a [FileInputStream] for read-only, a [FileOutputStream] for + * write-only (appending through the descriptor when `MODE_APPEND` is set) and a [RandomAccessFile] for read-write. + * Firebase Storage opens one to learn the size of a file it uploads. */ -class ParcelFileDescriptor private constructor(private val file: RandomAccessFile) : Closeable { - - val fileDescriptor: FileDescriptor - get() = file.fd +class ParcelFileDescriptor private constructor( + private val stream: Closeable, + val fileDescriptor: FileDescriptor, + private val size: () -> Long, +) : Closeable { /** The size of the file in bytes, or -1 when it cannot be determined. */ val statSize: Long get() = try { - file.length() + size() } catch (e: IOException) { -1 } @Throws(IOException::class) - override fun close() = file.close() + override fun close() = stream.close() companion object { const val MODE_WORLD_READABLE = 0x00000001 @@ -41,12 +46,22 @@ class ParcelFileDescriptor private constructor(private val file: RandomAccessFil @JvmStatic @Throws(FileNotFoundException::class) fun open(file: File, mode: Int): ParcelFileDescriptor { + val readable = mode and MODE_READ_ONLY != 0 val writable = mode and MODE_WRITE_ONLY != 0 + require(readable || writable) { "Bad mode: $mode" } if (!file.exists() && (!writable || mode and MODE_CREATE == 0)) throw FileNotFoundException(file.path) - val opened = RandomAccessFile(file, if (writable) "rw" else "r") - if (writable && mode and MODE_TRUNCATE != 0) opened.setLength(0) - if (writable && mode and MODE_APPEND != 0) opened.seek(opened.length()) - return ParcelFileDescriptor(opened) + val truncate = mode and MODE_TRUNCATE != 0 + val append = mode and MODE_APPEND != 0 + return when { + !writable -> FileInputStream(file).let { ParcelFileDescriptor(it, it.fd) { it.channel.size() } } + // The output stream truncates unless it appends, which is what the write-only modes ("w", "wt", "wa") ask for. + !readable && (truncate || append) -> FileOutputStream(file, append).let { ParcelFileDescriptor(it, it.fd) { it.channel.size() } } + else -> RandomAccessFile(file, "rw").let { + if (truncate) it.setLength(0) + if (append) it.seek(it.length()) + ParcelFileDescriptor(it, it.fd) { it.length() } + } + } } /** The `MODE_*` flags for a mode string of `ContentResolver.openFileDescriptor`, as Android parses it. */ @@ -59,5 +74,9 @@ class ParcelFileDescriptor private constructor(private val file: RandomAccessFil "rwt" -> MODE_READ_WRITE or MODE_CREATE or MODE_TRUNCATE else -> throw IllegalArgumentException("Bad mode: $mode") } + + /** Unsupported: a raw descriptor number cannot be adopted on the JVM. SQLite's blob descriptors are not implemented. */ + @JvmStatic + fun adoptFd(fd: Int): ParcelFileDescriptor = throw UnsupportedOperationException("Adopting a raw file descriptor ($fd) is not supported on the JVM") } } diff --git a/src/test/kotlin/ContentResolverTest.kt b/src/test/kotlin/ContentResolverTest.kt index 2e8eb8c..2170729 100644 --- a/src/test/kotlin/ContentResolverTest.kt +++ b/src/test/kotlin/ContentResolverTest.kt @@ -13,6 +13,7 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.io.FileOutputStream import java.io.FileNotFoundException class ContentResolverTest { @@ -57,6 +58,23 @@ class ContentResolverTest { assertEquals("three", file.readText()) } + @Test + fun `read-write output stream overwrites in place without truncating`() { + val file = file("inplace.txt", "abcdef") + val uri = Uri.parse(file.toURI().toString()) + resolver.openOutputStream(uri, "rw")!!.use { it.write("X".toByteArray()) } + assertEquals("Xbcdef", file.readText()) + resolver.openOutputStream(uri, "rwt")!!.use { it.write("Y".toByteArray()) } + assertEquals("Y", file.readText()) + } + + @Test + fun `read-only mode cannot open an output stream`() { + val file = file("readonly.txt", "keep") + assertThrows(IllegalArgumentException::class.java) { resolver.openOutputStream(Uri.parse(file.toURI().toString()), "r") } + assertEquals("keep", file.readText()) + } + @Test fun `type is guessed from the file name`() { assertEquals("text/plain", resolver.getType(Uri.parse("file:///tmp/notes.txt"))) @@ -81,7 +99,31 @@ class ContentResolverTest { ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("w")).use { assertEquals(0, it.statSize) } file.writeText("longer content") ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa")).use { assertEquals(14, it.statSize) } + ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("rw")).use { assertEquals(14, it.statSize) } + assertEquals("longer content", file.readText()) ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wt")).use { assertEquals(0, it.statSize) } assertThrows(IllegalArgumentException::class.java) { ParcelFileDescriptor.parseMode("x") } } + + @Test + fun `read-only descriptor does not write and appending descriptors interleave`() { + val file = file("append.txt", "start") + ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("r")).use { descriptor -> + assertThrows(java.io.IOException::class.java) { FileOutputStream(descriptor.fileDescriptor).write(1) } + } + assertEquals("start", file.readText()) + val first = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa")) + val second = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa")) + FileOutputStream(first.fileDescriptor).write("-one".toByteArray()) + FileOutputStream(second.fileDescriptor).write("-two".toByteArray()) + FileOutputStream(first.fileDescriptor).write("-three".toByteArray()) + first.close() + second.close() + assertEquals("start-one-two-three", file.readText()) + } + + @Test + fun `adopting a raw descriptor is unsupported`() { + assertThrows(UnsupportedOperationException::class.java) { ParcelFileDescriptor.adoptFd(3) } + } } From 658b7201ed365e77efa190416ceded528b94bd31 Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Mon, 9 Nov 2026 04:28:34 +0000 Subject: [PATCH 3/3] Fix ktlint findings in the ContentResolver change --- src/main/java/android/os/ParcelFileDescriptor.kt | 2 +- src/test/kotlin/ContentResolverTest.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/android/os/ParcelFileDescriptor.kt b/src/main/java/android/os/ParcelFileDescriptor.kt index 8230096..2bad019 100644 --- a/src/main/java/android/os/ParcelFileDescriptor.kt +++ b/src/main/java/android/os/ParcelFileDescriptor.kt @@ -18,7 +18,7 @@ import java.io.RandomAccessFile class ParcelFileDescriptor private constructor( private val stream: Closeable, val fileDescriptor: FileDescriptor, - private val size: () -> Long, + private val size: () -> Long ) : Closeable { /** The size of the file in bytes, or -1 when it cannot be determined. */ diff --git a/src/test/kotlin/ContentResolverTest.kt b/src/test/kotlin/ContentResolverTest.kt index 2170729..be41fc2 100644 --- a/src/test/kotlin/ContentResolverTest.kt +++ b/src/test/kotlin/ContentResolverTest.kt @@ -13,8 +13,8 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File -import java.io.FileOutputStream import java.io.FileNotFoundException +import java.io.FileOutputStream class ContentResolverTest {