diff --git a/composite-builds/build-deps/java-compiler/src/main/java/com/itsaky/androidide/zipfs2/listing/JarListing.java b/composite-builds/build-deps/java-compiler/src/main/java/com/itsaky/androidide/zipfs2/listing/JarListing.java index 8210436360..0cda822df3 100644 --- a/composite-builds/build-deps/java-compiler/src/main/java/com/itsaky/androidide/zipfs2/listing/JarListing.java +++ b/composite-builds/build-deps/java-compiler/src/main/java/com/itsaky/androidide/zipfs2/listing/JarListing.java @@ -631,20 +631,30 @@ private int find(byte[] key, int off, int len) { return lookup(table, names, nameOffsets, key, off, len); } - /* Creates an entry for key[0..len), plus any missing ancestors, and links it to its parent. */ + /* + * Creates an entry for key[0..len), plus any missing ancestors, and links each to its parent. + * Iterative because one entry name can hold tens of thousands of segments. The entry and its + * missing ancestors get consecutive indices, deepest first, so the links are made by walking + * those indices back from the shallowest. + */ private int create(byte[] key, int len) { - int i = append(key, 0, len); - int slash = len - 1; - while (key[slash] != '/') { - slash--; - } - int parent = slash == 0 ? 0 : find(key, 0, slash); - if (parent < 0) { - parent = create(key, slash); + final int first = count; + int end = len; + int parent; + do { + append(key, 0, end); + end--; + while (key[end] != '/') { + end--; + } + parent = end == 0 ? 0 : find(key, 0, end); + } while (parent < 0); + for (int i = count - 1; i >= first; i--) { + nextSiblings[i] = firstChildren[parent]; + firstChildren[parent] = i; + parent = i; } - nextSiblings[i] = firstChildren[parent]; - firstChildren[parent] = i; - return i; + return first; } private int append(byte[] src, int off, int len) { diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt index 9c509048c2..0a65051557 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DeclarationsProvider.kt @@ -124,11 +124,16 @@ internal class DeclarationProvider( override val hasSpecificCallablePackageNamesComputation = false override val hasSpecificClassifierPackageNamesComputation = false - @OptIn(ResolutionSideKtFileAccess::class) - override fun ktFilesForPackage(fqName: FqName): Sequence = - index - .sourceFilesForPackage(fqName) - .asSequence() - .filter { it in scope } - .mapNotNull { index.getKtFile(it) } + override fun ktFilesForPackage(fqName: FqName): Sequence = index.ktFilesInPackage(fqName, scope) } + +/** The Kotlin files in [scope] that the file index records under [packageFqName]. */ +@OptIn(ResolutionSideKtFileAccess::class) +internal fun KtSymbolIndex.ktFilesInPackage( + packageFqName: FqName, + scope: GlobalSearchScope, +): Sequence = + sourceFilesForPackage(packageFqName) + .asSequence() + .filter { it in scope } + .mapNotNull { getKtFile(it) } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt index bd69c5758c..2c3348490c 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProvider.kt @@ -16,6 +16,7 @@ import org.jetbrains.kotlin.cli.jvm.index.JavaRoot import org.jetbrains.kotlin.com.intellij.mock.MockProject import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope +import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.fir.declarations.FirClass import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider import org.jetbrains.kotlin.fir.symbols.SymbolInternals @@ -24,6 +25,8 @@ import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.jetbrains.kotlin.psi.KtTypeAlias @@ -40,9 +43,6 @@ internal class DirectInheritorsProvider : private lateinit var modules: List private lateinit var project: Project - private val classesBySupertypeName = mutableMapOf>() - private val inheritableTypeAliasesByAliasedName = mutableMapOf>() - override fun setupWith( project: MockProject, index: KtSymbolIndex, @@ -60,16 +60,16 @@ internal class DirectInheritorsProvider : scope: GlobalSearchScope, includeLocalInheritors: Boolean, ): Iterable { - computeIndex() + val inheritors = computeIndex() val classId = ktClass.getClassId() ?: return emptyList() val baseModule = KotlinProjectStructureProvider.getModule(project, ktClass, useSiteModule = null) val baseFirClass = classId.toFirSymbol(baseModule)?.fir as? FirClass ?: return emptyList() val baseClassNames = mutableSetOf(classId.shortClassName) - calculateAliases(classId.shortClassName, baseClassNames) + calculateAliases(inheritors.inheritableTypeAliasesByAliasedName, classId.shortClassName, baseClassNames) - val possibleInheritors = baseClassNames.flatMap { classesBySupertypeName[it].orEmpty() } + val possibleInheritors = baseClassNames.flatMap { inheritors.classesBySupertypeName[it].orEmpty() } if (possibleInheritors.isEmpty()) { return emptyList() } @@ -77,11 +77,47 @@ internal class DirectInheritorsProvider : return possibleInheritors.filter { isValidInheritor(it, baseFirClass, scope, includeLocalInheritors) } } - // Let's say this operation is not frequently called, if we discover it's not the case we should cache it + /* + * Reads only the files of [ktClass]'s package. The sealed inheritors search calls this, and the + * whole-project walk of getDirectKotlinInheritors parsed every source file on each call: ~18 s of + * the first completion after a cold open on a phone. + */ + @OptIn(SymbolInternals::class) + override fun getSamePackageDirectKotlinInheritors( + ktClass: KtClass, + scope: GlobalSearchScope, + includeLocalInheritors: Boolean, + ): Iterable { + val classId = ktClass.getClassId() ?: return emptyList() + val baseModule = KotlinProjectStructureProvider.getModule(project, ktClass, useSiteModule = null) + val baseFirClass = classId.toFirSymbol(baseModule)?.fir as? FirClass ?: return emptyList() + + /* + * Every class with a supertype is a candidate: FIR's subclass check expands type aliases, so + * an inheritor written against an alias declared in another package is still found. + */ + return index + .ktFilesInPackage(classId.packageFqName, scope) + .flatMap { it.classesOrObjects(includeLocalInheritors) } + .filter { it.superTypeListEntries.isNotEmpty() } + .filter { isValidInheritor(it, baseFirClass, scope, includeLocalInheritors) } + .toList() + } + + /* + * Built per call and dropped on return: each KtClassOrObject pins its file's whole PSI tree, so a + * long-lived copy keeps every source file's tree in the heap. + */ + private class InheritorsIndex { + val classesBySupertypeName = mutableMapOf>() + val inheritableTypeAliasesByAliasedName = mutableMapOf>() + } + @OptIn(ResolutionSideKtFileAccess::class) - private fun computeIndex() { - classesBySupertypeName.clear() - inheritableTypeAliasesByAliasedName.clear() + private fun computeIndex(): InheritorsIndex { + val result = InheritorsIndex() + val classesBySupertypeName = result.classesBySupertypeName + val inheritableTypeAliasesByAliasedName = result.inheritableTypeAliasesByAliasedName modules .asFlatSequence() @@ -114,17 +150,19 @@ internal class DirectInheritorsProvider : }, ) } + return result } private fun calculateAliases( + aliasesByAliasedName: Map>, aliasedName: Name, aliases: MutableSet, ) { - inheritableTypeAliasesByAliasedName[aliasedName].orEmpty().forEach { alias -> + aliasesByAliasedName[aliasedName].orEmpty().forEach { alias -> val aliasName = alias.nameAsSafeName val isNewAliasName = aliases.add(aliasName) if (isNewAliasName) { - calculateAliases(aliasName, aliases) + calculateAliases(aliasesByAliasedName, aliasName, aliases) } } } @@ -186,3 +224,14 @@ private fun findInheritableSimpleNames(typeElement: KtTypeElement): List } } } + +private fun KtFile.classesOrObjects(includeLocal: Boolean): List = + if (includeLocal) { + PsiTreeUtil.collectElementsOfType(this, KtClassOrObject::class.java).toList() + } else { + declarations.nonLocalClassesOrObjects() + } + +// Descends through class bodies only, so lazily parsed function bodies stay unparsed. +private fun List.nonLocalClassesOrObjects(): List = + filterIsInstance().flatMap { listOf(it) + it.declarations.nonLocalClassesOrObjects() } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt index 7a304e0d93..418cc9929d 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarHandler.kt @@ -88,9 +88,21 @@ internal class ListingJarHandler( val size = listing.size(index) if (size > MAX_ENTRY_SIZE) throw ZipException("$jarPath!${listing.name(index)} is too large: $size bytes") return when (val method = listing.method(index)) { - METHOD_STORED -> readCompressed(index, extra = 0) - METHOD_DEFLATED -> inflate(readCompressed(index, extra = 1), size.toInt(), index) - else -> throw ZipException("$jarPath!${listing.name(index)} has unsupported method $method") + METHOD_STORED -> { + readCompressed(index, extra = 0) + } + + METHOD_DEFLATED -> { + // The output array is sized from metadata, so refuse a size no deflate stream of this length can produce. + if (size > (listing.compressedSize(index) + 1) * MAX_DEFLATE_RATIO) { + throw ZipException("$jarPath!${listing.name(index)}: $size bytes cannot inflate from ${listing.compressedSize(index)}") + } + inflate(readCompressed(index, extra = 1), size.toInt(), index) + } + + else -> { + throw ZipException("$jarPath!${listing.name(index)} has unsupported method $method") + } } } @@ -127,6 +139,10 @@ internal class ListingJarHandler( ): ByteArray { val compressedSize = listing.compressedSize(index) if (compressedSize > MAX_ENTRY_SIZE) throw ZipException("$jarPath!${listing.name(index)} is too large: $compressedSize bytes") + // Checked before allocating, so a corrupt central directory cannot claim more heap than the file holds. + if (listing.localHeaderOffset(index) + LOC_HEADER_SIZE + compressedSize > snapshot.size()) { + throw ZipException("$jarPath!${listing.name(index)}: $compressedSize bytes run past the end of the JAR") + } val data = ByteArray(compressedSize.toInt() + extra) val header = ByteArray(LOC_HEADER_SIZE) synchronized(jarLock) { @@ -208,6 +224,9 @@ internal class ListingJarHandler( const val ROOT = 0 const val NANOS_PER_MILLI = 1_000_000L const val MAX_ENTRY_SIZE = Int.MAX_VALUE - 16L + + // Deflate's upper bound: a 258-byte match costs at least 2 bits (1-bit length and distance codes). + const val MAX_DEFLATE_RATIO = 1032L const val METHOD_STORED = 0 const val METHOD_DEFLATED = 8 const val LOC_SIGNATURE = 0x04034b50L diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt new file mode 100644 index 0000000000..4b72aee508 --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/services/DirectInheritorsProviderTest.kt @@ -0,0 +1,82 @@ +package com.itsaky.androidide.lsp.kotlin.compiler.services + +import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest +import org.jetbrains.kotlin.analysis.api.platform.declarations.KotlinDirectInheritorsProvider +import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProvider +import org.jetbrains.kotlin.com.intellij.psi.impl.source.PsiFileImpl +import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtFile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DirectInheritorsProviderTest : KtLspTest() { + @Test + fun `same-package search finds inheritors declared in other files of the base class's package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + createSourceFile("p/A.kt", "package p\nclass A : Base()") + createSourceFile("p/Outer.kt", "package p\nclass Outer { class B : Base() }") + createSourceFile("p/Unrelated.kt", "package p\nclass Unrelated : Any()") + + assertEquals(listOf("p.A", "p.Outer.B"), samePackageInheritorsOf(base, "Base")) + } + + @Test + fun `same-package search finds inheritors that extend the base class through a type alias from another package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + createSourceFile("q/Alias.kt", "package q\ntypealias Aliased = p.Base") + createSourceFile("p/ViaAlias.kt", "package p\nimport q.Aliased\nclass ViaAlias : Aliased()") + + assertEquals(listOf("p.ViaAlias"), samePackageInheritorsOf(base, "Base")) + } + + @Test + fun `same-package search does not load files outside the base class's package`() { + val base = createSourceFile("p/Base.kt", "package p\nsealed class Base") + // Not registered with the file index, so nothing but a whole-module walk can reach it. + val otherPackage = env.createFile("src", "q/Other.kt", "package q\nclass Other : Any()") as PsiFileImpl + assertNull(otherPackage.treeElement) + + samePackageInheritorsOf(base, "Base") + + assertNull(otherPackage.treeElement) + } + + @Test + fun `full search still finds inheritors in other packages`() { + val base = createSourceFile("p/Base.kt", "package p\nopen class Base") + createSourceFile("p/A.kt", "package p\nclass A : Base()") + createSourceFile("q/B.kt", "package q\nclass B : p.Base()") + + val all = inheritorsOf(base, "Base") { ktClass, scope -> getDirectKotlinInheritors(ktClass, scope, false) } + + assertEquals(listOf("p.A", "q.B"), all) + assertEquals(listOf("p.A"), samePackageInheritorsOf(base, "Base")) + } + + private fun samePackageInheritorsOf( + file: KtFile, + className: String, + ): List = + inheritorsOf(file, className) { ktClass, scope -> + getSamePackageDirectKotlinInheritors(ktClass, scope, false) + } + + private fun inheritorsOf( + file: KtFile, + className: String, + search: KotlinDirectInheritorsProvider.(KtClass, GlobalSearchScope) -> Iterable, + ): List { + val ktClass = file.declarations.filterIsInstance().single { it.name == className } + return analyzeMaybeDanglingForTest(file) { + val scope = KotlinProjectStructureProvider.getModule(env.project, ktClass, useSiteModule = null).contentScope + KotlinDirectInheritorsProvider + .getInstance(env.project) + .search(ktClass, scope) + .map { it.fqName!!.asString() } + .sorted() + } + } +} diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt index 06d9eaf418..913b9a2d74 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/vfs/ListingJarFileSystemTest.kt @@ -15,6 +15,7 @@ import java.nio.file.StandardCopyOption import java.nio.file.attribute.FileTime import java.util.zip.CRC32 import java.util.zip.ZipEntry +import java.util.zip.ZipException import java.util.zip.ZipFile import java.util.zip.ZipOutputStream @@ -173,6 +174,24 @@ class ListingJarFileSystemTest : KtLspTest() { assertThat(failure).isInstanceOf(IOException::class.java) } + @Test + fun `a compressed size past the end of the jar fails before allocating it`() { + val jar = writeCorrupt("p/A.class" to "a", cenOffset = CEN_COMPRESSED_SIZE, value = HUGE_SIZE) + + val failure = runCatching { find(jar, "p/A.class")!!.contentsToByteArray() }.exceptionOrNull() + + assertThat(failure).isInstanceOf(ZipException::class.java) + } + + @Test + fun `an uncompressed size deflate cannot reach fails before allocating it`() { + val jar = writeCorrupt("p/A.class" to "a", cenOffset = CEN_SIZE, value = HUGE_SIZE) + + val failure = runCatching { find(jar, "p/A.class")!!.contentsToByteArray() }.exceptionOrNull() + + assertThat(failure).isInstanceOf(ZipException::class.java) + } + @Test fun `a first read after a rename replaced the jar fails instead of using old offsets`() { val jar = writeJar("a.jar", "p/A.class" to "old") @@ -289,6 +308,30 @@ class ListingJarFileSystemTest : KtLspTest() { return jar } + /** Writes a one-entry JAR whose central directory field at [cenOffset] is overwritten with [value]. */ + private fun writeCorrupt( + entry: Pair, + cenOffset: Int, + value: Long, + ): Path { + val bytes = zipBytes(entry) + val cen = (bytes.size - 4 downTo 0).first { u32(bytes, it) == CEN_SIGNATURE } + for (k in 0 until 4) { + bytes[cen + cenOffset + k] = (value ushr (8 * k)).toByte() + } + val jar = + lspTestRule.tempDir.root + .toPath() + .resolve("corrupt-size.jar") + Files.write(jar, bytes) + return jar + } + + private fun u32( + bytes: ByteArray, + at: Int, + ): Long = (0 until 4).fold(0L) { acc, k -> acc or ((bytes[at + k].toLong() and 0xFF) shl (8 * k)) } + private fun renameOver( jar: Path, vararg entries: Pair, @@ -322,3 +365,9 @@ class ListingJarFileSystemTest : KtLspTest() { } private const val LOC_HEADER_SIZE = 30 +private const val CEN_SIGNATURE = 0x02014b50L +private const val CEN_COMPRESSED_SIZE = 20 +private const val CEN_SIZE = 24 + +// Below the 0xFFFFFFFF zip64 marker, and far beyond the 1 GB test heap. +private const val HUGE_SIZE = 0x7FFF_0000L diff --git a/subprojects/javac-services/src/test/java/com/itsaky/androidide/javac/services/fs/JarListingTest.kt b/subprojects/javac-services/src/test/java/com/itsaky/androidide/javac/services/fs/JarListingTest.kt index 7ae0110a7a..9a15d38656 100644 --- a/subprojects/javac-services/src/test/java/com/itsaky/androidide/javac/services/fs/JarListingTest.kt +++ b/subprojects/javac-services/src/test/java/com/itsaky/androidide/javac/services/fs/JarListingTest.kt @@ -171,6 +171,36 @@ class JarListingTest { assertThat(chain).containsExactly("/x/y/z", "/x/y", "/x", "/").inOrder() } + @Test + fun `an entry nested deeper than the stack allows still gets every ancestor`() { + val depth = 8_000 + val name = "a/".repeat(depth) + "C.class" + val jar = zip { add(name) } + + var listing: JarListing? = null + var failure: Throwable? = null + // A small fixed stack makes a per-segment recursion overflow regardless of the runner's -Xss. + val reader = + Thread(null, { + try { + listing = JarListing.read(jar.toPath()) + } catch (t: Throwable) { + failure = t + } + }, "deep-jar-reader", 256L * 1024) + reader.start() + reader.join() + + assertThat(failure).isNull() + var i = listing!!.find("/$name") + var ancestors = 0 + while (listing!!.parent(i) != -1) { + i = listing!!.parent(i) + ancestors++ + } + assertThat(ancestors).isEqualTo(depth + 1) + } + @Test fun `root is index 0 and has no parent`() { val listing = JarListing.read(fixture().toPath()) diff --git a/subprojects/kotlin-analysis-api/build.gradle.kts b/subprojects/kotlin-analysis-api/build.gradle.kts index 0cc7d37563..36e9ef66f3 100644 --- a/subprojects/kotlin-analysis-api/build.gradle.kts +++ b/subprojects/kotlin-analysis-api/build.gradle.kts @@ -12,7 +12,7 @@ android { val ktAndroidRepo = "https://github.com/appdevforall/kotlin-android" val ktAndroidVersion = "2.3.255" -val ktAndroidTag = "v$ktAndroidVersion-b359891" +val ktAndroidTag = "v$ktAndroidVersion-b006e8c" val ktAndroidJarName = "analysis-api-standalone-embeddable-for-ide-$ktAndroidVersion-SNAPSHOT.jar" externalAssets { @@ -21,7 +21,7 @@ externalAssets { source = AssetSource.External( url = uri("$ktAndroidRepo/releases/download/$ktAndroidTag/$ktAndroidJarName"), - sha256Checksum = "3a3c0f6cb8bbcd6547a809c32e07b3735a42afcf1efad45c416885f847a628a7", + sha256Checksum = "0793c08f666157aa091055a498f9c231a42ced31ad5a019c9875cf814e719bbb", ) } } diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReader.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReader.kt index c452e3d26a..dbb0a9218e 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReader.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReader.kt @@ -23,6 +23,7 @@ import com.itsaky.androidide.javac.services.fs.CachingJarFileSystemProvider import org.slf4j.LoggerFactory import java.io.File import java.io.IOException +import java.nio.file.FileSystemNotFoundException import java.nio.file.FileVisitResult import java.nio.file.FileVisitResult.CONTINUE import java.nio.file.Files @@ -74,6 +75,10 @@ class JarFsClasspathReader : IClasspathReader { } catch (e: IOException) { log.warn("Skipping JAR that could not be read while indexing classpath: {}", path, e) _unreadableJars.add(path.toFile()) + } catch (e: FileSystemNotFoundException) { + // The provider reports a JAR that is gone by the time it opens it this way, not as an IOException. + log.warn("Skipping JAR that disappeared while indexing classpath: {}", path, e) + _unreadableJars.add(path.toFile()) } } return builder.build() diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReaderCorruptJarTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReaderCorruptJarTest.kt index c6869fd623..67072b0243 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReaderCorruptJarTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/classpath/JarFsClasspathReaderCorruptJarTest.kt @@ -102,6 +102,25 @@ class JarFsClasspathReaderCorruptJarTest { assertThat(classes.size).isGreaterThan(100) } + @Test + fun jarWhoseFileSystemIsNotFoundIsSkippedWithoutAbortingIndexing() { + // link/../found.jar exists for the OS (link -> real/sub, so link/.. is real) but not after the + // provider's lexical normalize, which drops "link/..": the same split a JAR deleted between + // the exists check and the open produces, without the timing. + val real = File(tmpDir, "real/sub").apply { mkdirs() }.parentFile + validJar.copyTo(File(real, "found.jar")) + val link = File(tmpDir, "link") + Files.createSymbolicLink(link.toPath(), File(real, "sub").toPath()) + val vanishing = File(link, "../found.jar") + assertThat(vanishing.exists()).isTrue() + + val reader = JarFsClasspathReader() + val classes = reader.listClasses(listOf(vanishing, validJar)) + + assertThat(classes.any { it.name == "android.content.Context" }).isTrue() + assertThat(reader.unreadableJars).containsExactly(vanishing) + } + /** * The reader must EXPOSE the skipped JARs (not just log them) so the caller can name the offending * dependency to the user and offer a recovery path (re-sync) instead of silently dropping symbols.