From 4cb3a894837ab00f95cac83b66f5d3db5c7cd78f Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 7 Nov 2026 11:16:08 -0500 Subject: [PATCH] fix: library scan and download cancel crash on Android 10 (#2204) * fix: library scan and download cancel crash on Android 10 The storage scan read StorageVolume.getDirectory() for every volume to build its key, but that method only exists from Android 11, so on Android 10 the steam-library-scan thread died with NoSuchMethodError. The directory is now read once behind the existing Android 11 check and reused for both the key and the candidate path; older versions fall back to the uuid, description and /storage scan as before. Cancelling a download closes the response stream on a background thread. The platform okhttp can throw IllegalStateException ("Unbalanced enter/exit") from close() while a read is still in flight, which was uncaught and killed the app. That close now ignores IllegalStateException as well as IOException; other failures still surface. Fixes #2200 * test: wait for the cancel task to finish instead of polling its thread state The cancel-close tests decided the close task was done from the worker's thread state, which can read WAITING while the pool is still cleaning up after a thrown exception. A close failure that escapes ends its worker thread, and Java runs the uncaught handler before the thread ends, so the surfacing test now joins that thread. The suppression test hands the cancel executor more work until it runs on the same thread, which only happens once the close task has returned without throwing. * test: watch the close task finish instead of probing which worker runs next A cached pool can start a second worker, so a probe task may never land on the thread that ran the close. The suppression test now waits until the pool has no task running and that thread is back to waiting for work, a state a worker that is exiting after a thrown exception never enters. --- .../droiddeck/launcher/core/Downloader.java | 2 +- .../droiddeck/launcher/files/StorageRoots.kt | 7 +- .../launcher/core/DownloaderCancelTest.kt | 77 +++++++++++++++++++ .../launcher/files/StorageRootsVolumeTest.kt | 55 +++++++++++++ 4 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/core/DownloaderCancelTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/files/StorageRootsVolumeTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java index 19cec5acbe..9bd86c5719 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java +++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java @@ -58,7 +58,7 @@ public final class Downloader { private static void closeAsync(InputStream active) { CANCEL_EXECUTOR.execute(() -> { - try { active.close(); } catch (IOException ignored) { } + try { active.close(); } catch (IOException | IllegalStateException ignored) { } }); } diff --git a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt index b19a2e9874..825c2e24c6 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt @@ -90,7 +90,8 @@ object StorageRoots { .filter { present(it.state) } .forEachIndexed { index, volume -> val uuid = volume.uuid?.takeIf { it.isNotBlank() } - val dirName = volume.directory?.name?.takeIf { it.isNotBlank() } + val directory = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) volume.directory else null + val dirName = directory?.name?.takeIf { it.isNotBlank() } val descSlug = volume.getDescription(context)?.trim() ?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) } ?.replace(Regex("[^A-Za-z0-9._-]+"), "-") @@ -98,9 +99,7 @@ object StorageRoots { entry.removable = !volume.isPrimary && volume.isRemovable if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - volume.directory?.let { entry.candidates += it } - } + directory?.let { entry.candidates += it } val name = uuid ?: dirName if (name != null) { entry.candidates += File("/storage/$name") diff --git a/app/src/test/java/com/droiddeck/launcher/core/DownloaderCancelTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DownloaderCancelTest.kt new file mode 100644 index 0000000000..8d49cdeb00 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/DownloaderCancelTest.kt @@ -0,0 +1,77 @@ +package com.droiddeck.launcher.core + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.InputStream +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit + +class DownloaderCancelTest { + private val previousHandler = Thread.getDefaultUncaughtExceptionHandler() + private val uncaught = CopyOnWriteArrayList() + + @After fun tearDown() { + Thread.setDefaultUncaughtExceptionHandler(previousHandler) + } + + private val cancelExecutor: ExecutorService + get() = Downloader::class.java.getDeclaredField("CANCEL_EXECUTOR") + .apply { isAccessible = true } + .get(null) as ExecutorService + + private fun cancelWhileClosingThrows(failure: RuntimeException): Thread { + Thread.setDefaultUncaughtExceptionHandler { _, error -> uncaught += error } + val closed = CountDownLatch(1) + var closer: Thread? = null + val stream = object : InputStream() { + override fun read(): Int = -1 + override fun close() { + closer = Thread.currentThread() + closed.countDown() + throw failure + } + } + val cancellation = Downloader.Cancellation() + Downloader.Cancellation::class.java.getDeclaredMethod("attach", InputStream::class.java) + .apply { isAccessible = true } + .invoke(cancellation, stream) + + cancellation.cancel() + + assertTrue(closed.await(5, TimeUnit.SECONDS)) + return closer!! + } + + private fun survivesItsTask(closer: Thread): Boolean { + val pool = cancelExecutor as ThreadPoolExecutor + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (System.nanoTime() < deadline) { + if (!closer.isAlive) return false + if (pool.activeCount == 0 && closer.state == Thread.State.TIMED_WAITING) return true + Thread.sleep(5) + } + error("the cancel thread neither ended nor went back to waiting for work") + } + + @Test fun unbalancedTimeoutOnCancelDoesNotCrash() { + val closer = cancelWhileClosingThrows(IllegalStateException("Unbalanced enter/exit")) + + assertTrue(survivesItsTask(closer)) + assertEquals(emptyList(), uncaught.toList()) + } + + @Test fun otherCloseFailuresStillSurface() { + val failure = UnsupportedOperationException("close") + val closer = cancelWhileClosingThrows(failure) + + closer.join(TimeUnit.SECONDS.toMillis(5)) + assertFalse(closer.isAlive) + assertEquals(listOf(failure), uncaught.toList()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/files/StorageRootsVolumeTest.kt b/app/src/test/java/com/droiddeck/launcher/files/StorageRootsVolumeTest.kt new file mode 100644 index 0000000000..b7d9cf520c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/StorageRootsVolumeTest.kt @@ -0,0 +1,55 @@ +package com.droiddeck.launcher.files + +import android.os.Environment +import android.os.Process +import android.os.storage.StorageManager +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.StorageVolumeBuilder +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class StorageRootsVolumeTest { + @get:Rule val temporary = TemporaryFolder() + + private fun addUsbVolume(): File { + val mount = temporary.newFolder("usbstick") + val context = RuntimeEnvironment.getApplication() + val volume = StorageVolumeBuilder("public:8,1", mount, "USB drive", Process.myUserHandle(), Environment.MEDIA_MOUNTED) + .setIsPrimary(false) + .setIsEmulated(false) + .setIsRemovable(true) + .build() + shadowOf(context.getSystemService(StorageManager::class.java)).addStorageVolume(volume) + return mount + } + + @Config(sdk = [29]) + @Test fun volumesWithoutDirectoryApiAreListedOnAndroid10() { + addUsbVolume() + + val usb = StorageRoots.list(RuntimeEnvironment.getApplication()).single { it.label == "USB drive" } + + assertTrue(usb.removable) + } + + @Config(sdk = [30]) + @Test fun volumeDirectoryIsStillUsedOnAndroid11() { + val mount = addUsbVolume() + + val usb = StorageRoots.list(RuntimeEnvironment.getApplication()).single { it.label == "USB drive" } + + assertTrue(usb.removable) + assertTrue(usb.readable) + assertEquals(mount.absoluteFile, usb.dir.absoluteFile) + } +}