fix(session): Handle invalid filenames when trimming page cache

Walk files with NIO and skip unreadable entries. Keep page-cache trimming from interrupting session startup.
This commit is contained in:
kalac2232 authored and GitHub committed 2026-12-05 23:34:33 -05:00
1 parent cad55fc2b9
commit 2ab642bf4e
2 files changed
+65 -2

No files matched your search

@@ -2,10 +2,16 @@ package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
internal const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
@@ -37,7 +43,7 @@ internal object PageCacheTrim {
if (mem != null && shouldTrim(mem, baseline)) {
val now = System.currentTimeMillis()
if (now - scanned > RESCAN_MS) {
files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() }
files = roots().flatMap { root -> bigFiles(root) }
scanned = now
}
val began = System.nanoTime()
@@ -56,6 +62,34 @@ internal object PageCacheTrim {
}, "page-cache-trim").apply { isDaemon = true }.start()
}
// java.io's directory listing hands raw entry names to JNI NewStringUTF, which aborts the
// process on names that are not valid UTF-8; NIO decodes them with replacement instead.
// Without FOLLOW_LINKS, symlinked directories are never descended into, like the old onEnter,
// except that a starting directory that is itself a link has to be resolved first; a link
// whose target has vanished yields an empty result instead of an error.
internal fun bigFiles(root: File): List<File> {
val out = ArrayList<File>()
val start = root.toPath()
val real = if (Files.isSymbolicLink(start)) {
try {
start.toRealPath()
} catch (_: IOException) {
return out
}
} else start
Files.walkFileTree(real, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (attrs.isRegularFile && attrs.size() >= MIN_FILE_BYTES) out.add(file.toFile())
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, error: IOException): FileVisitResult = FileVisitResult.CONTINUE
override fun postVisitDirectory(dir: Path, error: IOException?): FileVisitResult = FileVisitResult.CONTINUE
})
return out
}
private fun drop(file: File) {
PageCacheNative.fadviseDontNeed(file.path)
}