diff --git a/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt b/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt index 83f35c74a0..869ab0081f 100644 --- a/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt @@ -21,9 +21,12 @@ import com.itsaky.androidide.models.Position import com.itsaky.androidide.models.Range import com.itsaky.androidide.viewmodel.DebuggerConnectionState import com.itsaky.androidide.viewmodel.DebuggerViewModel +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch @@ -34,308 +37,383 @@ import org.greenrobot.eventbus.ThreadMode import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.CopyOnWriteArraySet +import java.util.concurrent.atomic.AtomicReference /** * @author Akash Yadav */ class IDEDebugClientImpl( - private val viewModel: DebuggerViewModel, -) : IDebugClient, IDebugEventHandler, EventReceiver { - - private val logger = LoggerFactory.getLogger(IDEDebugClientImpl::class.java) - - @OptIn(DelicateCoroutinesApi::class) - private val clientContext = newFixedThreadPoolContext(4, "IDEDebugClient") - private val clientScope = CoroutineScope(clientContext + SupervisorJob()) - private val clients = CopyOnWriteArraySet() - val breakpoints = BreakpointHandler() - - companion object { - @JvmStatic - fun getInstance() = Lookup.getDefault().lookup(IDEDebugClientImpl::class.java) - - @JvmStatic - fun requireInstance() = checkNotNull(getInstance()) { - "Cannot lookup IDEDebugClientImpl" - } - } - - val connectionStateFlow: StateFlow - get() = viewModel.connectionState - - var connectionState: DebuggerConnectionState - get() = viewModel.connectionState.value - private set(value) { - logger.debug("move to connection state: {}", value) - viewModel.setConnectionState(value) - } - - val debugeePackage: String - get() = viewModel.debugeePackage - - internal val requireClient: RemoteClient - get() = checkNotNull(clientOrNull) - - internal val clientOrNull: RemoteClient? - get() = clients.firstOrNull() - - /** - * Returns true if the client is connected. - * - * @return `true` if the client is connected, `false` otherwise. - */ - fun isVmConnected() = connectionState >= DebuggerConnectionState.ATTACHED - - /** - * Returns true if the client is connected and suspended. - * - * The VM may or may not be able to view/alter its state. Check [connectionState] - * to get the actual state. - * - * @return `true` if the client is connected and suspended, `false` otherwise. - */ - fun isVmSuspended() = connectionState >= DebuggerConnectionState.SUSPENDED - - fun suspendVm() = withClient("suspend vm") { client -> - if (!client.capabilities.suspensionSupport) { - logger.error("Remote client does not support suspending") - return@withClient - } - - if (isVmSuspended()) { - logger.warn("Ignoring attempt to suspend VM when it is already suspended") - return@withClient - } - - logger.debug("suspending client: {}", client.name) - clientScope.launch { - if (client.adapter.suspendClient(client)) { - connectionState = DebuggerConnectionState.SUSPENDED - updateThreadInfo(client) - } - } - } - - fun resumeVm() = withClient("resume vm") { client -> - if (!client.capabilities.suspensionSupport) { - logger.error("Remote client does not support resuming") - return@withClient - } - - if (!isVmSuspended()) { - logger.warn("Ignoring attempt to resume VM when it is not suspended") - return@withClient - } - - logger.debug("resuming client: {}", client.name) - clientScope.launch { - if (client.adapter.resumeClient(client)) { - connectionState = DebuggerConnectionState.ATTACHED - updateThreadInfo(client) - } - } - } - - fun killVm() = withClient("kill vm") { client -> - if (!client.capabilities.killSupport) { - logger.error("Remote client does not support killing debug application") - return@withClient - } - - logger.debug("killing client: {}", client.name) - clientScope.launch { client.adapter.killClient(client) } - } - - fun stepOver() = doStep(type = StepType.Over) - fun stepInto() = doStep(type = StepType.Into) - fun stepOut() = doStep(type = StepType.Out) - - private inline fun withClient(action: String, block: (RemoteClient) -> Unit) { - clientOrNull?.also(block) - ?: logger.error("Cannot perform $action action. Not connected to a remote client.") - } - - private fun doStep( - type: StepType, - countFilter: Int = 1 - ) = withClient("step $type") { client -> - if (!client.capabilities.stepSupport) { - logger.error("Remote client does not support stepping") - return@withClient - } - - clientScope.launch { - val params = StepRequestParams( - remoteClient = client, - type = type, - countFilter = countFilter - ) - - val response = client.adapter.step(params) - if (response.result != StepResult.Success) { - logger.error("Failed to perform step action, result={}", response.result) - } - } - } - - init { - register() - breakpoints.begin { breakpoints -> - - // if we're already connected to a client, update the client as well - clientOrNull?.also { client -> - if (!client.capabilities.breakpointSupport) { - logger.error("Remote client does not support breakpoints") - return@also - } - - clientScope.launch { - clientOrNull?.also { client -> - val response = client.adapter.setBreakpoints( - BreakpointRequest( - remoteClient = client, - breakpoints = breakpoints - ) - ) - - logger.debug("breakpoint result: {}", response.results) - } ?: logger.info("client ${client.name} disconnected while updating breakpoints") - } - } ?: logger.info("deferring breakpoint update, no clients connected") - } - } - - @SuppressLint("ImplicitSamInstance") - @Suppress("UNUSED") - @Subscribe(threadMode = ThreadMode.ASYNC) - fun onContentChange(event: DocumentChangeEvent) { - clientScope.launch { breakpoints.change(event) } - } - - fun toggleBreakpoint(file: File, line: Int) { - clientScope.launch { breakpoints.toggle(file, line) } - } - - override fun onBreakpointHit(event: BreakpointHitEvent) { - logger.debug("onBreakpointHit: {}", event) - - clientScope.launch { - connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT - updateThreadInfo(event.remoteClient, event.threadId) - - openLocation(event) - } - } - - override fun onStep(event: StepEvent) { - logger.debug("onStep: {}", event) - - clientScope.launch { - updateThreadInfo(event.remoteClient, event.threadId) - connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT - - openLocation(event) - } - } - - override fun onAttach(client: RemoteClient) { - logger.debug("onAttach: client={}", client) - - check(client !in clients) { - "Already attached to client" - } - - clients += client - connectionState = DebuggerConnectionState.ATTACHED - breakpoints.unhighlightHighlightedLocation() - - clientScope.launch { - updateThreadInfo(client) - - val breakpoints = breakpoints.allBreakpoints - client.adapter.setBreakpoints( - BreakpointRequest( - remoteClient = client, - breakpoints = breakpoints - ) - ) - } - } - - override fun onDisconnect(client: RemoteClient) { - logger.debug("onDisconnect: client={}", client) - breakpoints.unhighlightHighlightedLocation() - clients -= client - connectionState = DebuggerConnectionState.DETACHED - clientScope.launch { updateThreadInfo(client) } - } - - suspend fun updateThreadInfo( - client: RemoteClient, - selectedThreadId: String? = null, - ) { - val adapter = client.adapter - var selectedThreadIndex = -1 - val threads = when (connectionState) { - DebuggerConnectionState.DETACHED, - DebuggerConnectionState.ATTACHED -> emptyList() - - DebuggerConnectionState.SUSPENDED, - DebuggerConnectionState.AWAITING_BREAKPOINT -> { - val threadResponse = adapter.allThreads( - ThreadListRequestParams( - remoteClient = client - ) - ) - - val threads = threadResponse.threads - if (threads.isEmpty()) { - logger.error("Failed to get info about active threads in VM: {}", client.name) - } else if (selectedThreadId != null) { - selectedThreadIndex = threads.indexOfFirst { - it.descriptor().id == selectedThreadId - } - } - - threads - } - } - - if (threads.isNotEmpty() && selectedThreadIndex < 0) { - selectedThreadIndex = 0 - } - - viewModel.setThreads(threads, selectedThreadIndex) - } - - private suspend fun openLocation(event: LocatableEvent) = openLocation(event.location) - - private suspend fun openLocation(location: Location) { - val file = location.source.path - val position = Position(location.line, 0) - - if (!IDELanguageClientImpl.isInitialized()) { - logger.error("Cannot open {}:{} because language client is not initialized", file, position.line) - return - } - - val activity = IDELanguageClientImpl.getInstance().activity - - if (activity == null) { - logger.error("Cannot open {}:{} because activity is null", file, position.line) - return - } - - breakpoints.highlightLocation(file, position.line) - - withContext(Dispatchers.Main.immediate) { - activity.openFileAndSelect( - file = File(file), - selection = Range( - start = position, - end = position - ) - ) - } - } -} \ No newline at end of file + private val viewModel: DebuggerViewModel, +) : IDebugClient, + IDebugEventHandler, + EventReceiver { + private val logger = LoggerFactory.getLogger(IDEDebugClientImpl::class.java) + + @OptIn(DelicateCoroutinesApi::class) + private val clientContext = newFixedThreadPoolContext(4, "IDEDebugClient") + private val clientScope = CoroutineScope(clientContext + SupervisorJob()) + private val clients = CopyOnWriteArraySet() + val breakpoints = BreakpointHandler() + private val threadInfoJob = AtomicReference(null) + + companion object { + @JvmStatic + fun getInstance() = Lookup.getDefault().lookup(IDEDebugClientImpl::class.java) + + @JvmStatic + fun requireInstance() = + checkNotNull(getInstance()) { + "Cannot lookup IDEDebugClientImpl" + } + } + + val connectionStateFlow: StateFlow + get() = viewModel.connectionState + + var connectionState: DebuggerConnectionState + get() = viewModel.connectionState.value + private set(value) { + logger.debug("move to connection state: {}", value) + viewModel.setConnectionState(value) + } + + val debugeePackage: String + get() = viewModel.debugeePackage + + internal val requireClient: RemoteClient + get() = checkNotNull(clientOrNull) + + internal val clientOrNull: RemoteClient? + get() = clients.firstOrNull() + + /** + * Returns true if the client is connected. + * + * @return `true` if the client is connected, `false` otherwise. + */ + fun isVmConnected() = connectionState >= DebuggerConnectionState.ATTACHED + + /** + * Returns true if the client is connected and suspended. + * + * The VM may or may not be able to view/alter its state. Check [connectionState] + * to get the actual state. + * + * @return `true` if the client is connected and suspended, `false` otherwise. + */ + fun isVmSuspended() = connectionState >= DebuggerConnectionState.SUSPENDED + + fun suspendVm() = + withClient("suspend vm") { client -> + if (!client.capabilities.suspensionSupport) { + logger.error("Remote client does not support suspending") + return@withClient + } + + if (isVmSuspended()) { + logger.warn("Ignoring attempt to suspend VM when it is already suspended") + return@withClient + } + + logger.debug("suspending client: {}", client.name) + clientScope.launch { + if (client.adapter.suspendClient(client)) { + connectionState = DebuggerConnectionState.SUSPENDED + launchUpdateThreadInfo(client) + } + } + } + + fun resumeVm() = + withClient("resume vm") { client -> + if (!client.capabilities.suspensionSupport) { + logger.error("Remote client does not support resuming") + return@withClient + } + + if (!isVmSuspended()) { + logger.warn("Ignoring attempt to resume VM when it is not suspended") + return@withClient + } + + logger.debug("resuming client: {}", client.name) + // Mark running before resuming: a breakpoint hit as soon as the VM resumes + // must not be overwritten by this call completing afterwards. + val previousState = connectionState + connectionState = DebuggerConnectionState.ATTACHED + breakpoints.unhighlightHighlightedLocation() + launchUpdateThreadInfo(client) + clientScope.launch { + val resumed = + try { + client.adapter.resumeClient(client) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.error("Failed to resume client", e) + false + } + if (!resumed && connectionState == DebuggerConnectionState.ATTACHED) { + connectionState = previousState + launchUpdateThreadInfo(client) + } + } + } + + fun killVm() = + withClient("kill vm") { client -> + if (!client.capabilities.killSupport) { + logger.error("Remote client does not support killing debug application") + return@withClient + } + + logger.debug("killing client: {}", client.name) + clientScope.launch { client.adapter.killClient(client) } + } + + fun stepOver() = doStep(type = StepType.Over) + + fun stepInto() = doStep(type = StepType.Into) + + fun stepOut() = doStep(type = StepType.Out) + + private inline fun withClient( + action: String, + block: (RemoteClient) -> Unit, + ) { + clientOrNull?.also(block) + ?: logger.error("Cannot perform $action action. Not connected to a remote client.") + } + + private fun doStep( + type: StepType, + countFilter: Int = 1, + ) = withClient("step $type") { client -> + if (!client.capabilities.stepSupport) { + logger.error("Remote client does not support stepping") + return@withClient + } + + cancelThreadInfoJob() + val previousState = connectionState + connectionState = DebuggerConnectionState.ATTACHED + breakpoints.unhighlightHighlightedLocation() + + clientScope.launch { + val params = + StepRequestParams( + remoteClient = client, + type = type, + countFilter = countFilter, + ) + + val result = + try { + client.adapter.step(params).result + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.error("Failed to perform step action", e) + null + } + if (result != StepResult.Success) { + logger.error("Failed to perform step action, result={}", result) + // VM did not move: undo the optimistic ATTACHED unless a stop event already replaced it. + if (connectionState == DebuggerConnectionState.ATTACHED) { + connectionState = previousState + launchUpdateThreadInfo(client) + } + } + } + } + + init { + register() + breakpoints.begin { breakpoints -> + + // if we're already connected to a client, update the client as well + clientOrNull?.also { client -> + if (!client.capabilities.breakpointSupport) { + logger.error("Remote client does not support breakpoints") + return@also + } + + clientScope.launch { + clientOrNull?.also { client -> + val response = + client.adapter.setBreakpoints( + BreakpointRequest( + remoteClient = client, + breakpoints = breakpoints, + ), + ) + + logger.debug("breakpoint result: {}", response.results) + } ?: logger.info("client ${client.name} disconnected while updating breakpoints") + } + } ?: logger.info("deferring breakpoint update, no clients connected") + } + } + + @SuppressLint("ImplicitSamInstance") + @Suppress("UNUSED") + @Subscribe(threadMode = ThreadMode.ASYNC) + fun onContentChange(event: DocumentChangeEvent) { + clientScope.launch { breakpoints.change(event) } + } + + fun toggleBreakpoint( + file: File, + line: Int, + ) { + clientScope.launch { breakpoints.toggle(file, line) } + } + + override fun onBreakpointHit(event: BreakpointHitEvent) { + logger.debug("onBreakpointHit: {}", event) + + connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT + launchUpdateThreadInfo(event.remoteClient, event.threadId) { openLocation(event) } + } + + override fun onStep(event: StepEvent) { + logger.debug("onStep: {}", event) + + connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT + launchUpdateThreadInfo(event.remoteClient, event.threadId) { openLocation(event) } + } + + override fun onAttach(client: RemoteClient) { + logger.debug("onAttach: client={}", client) + + check(client !in clients) { + "Already attached to client" + } + + clients += client + connectionState = DebuggerConnectionState.ATTACHED + breakpoints.unhighlightHighlightedLocation() + launchUpdateThreadInfo(client) + + clientScope.launch { + val breakpoints = breakpoints.allBreakpoints + client.adapter.setBreakpoints( + BreakpointRequest( + remoteClient = client, + breakpoints = breakpoints, + ), + ) + } + } + + override fun onDisconnect(client: RemoteClient) { + logger.debug("onDisconnect: client={}", client) + breakpoints.unhighlightHighlightedLocation() + clients -= client + connectionState = DebuggerConnectionState.DETACHED + launchUpdateThreadInfo(client) + } + + private fun launchUpdateThreadInfo( + client: RemoteClient, + selectedThreadId: String? = null, + then: suspend () -> Unit = {}, + ) { + // Swap before starting so the previous job is cancelled before the new one runs. + val job = + clientScope.launch(start = CoroutineStart.LAZY) { + updateThreadInfo(client, selectedThreadId) + then() + } + threadInfoJob.getAndSet(job)?.cancel() + job.start() + } + + private fun cancelThreadInfoJob() { + threadInfoJob.getAndSet(null)?.cancel() + } + + suspend fun updateThreadInfo( + client: RemoteClient, + selectedThreadId: String? = null, + ) { + val adapter = client.adapter + var selectedThreadIndex = -1 + val threads = + when (connectionState) { + DebuggerConnectionState.DETACHED, + DebuggerConnectionState.ATTACHED, + -> { + emptyList() + } + + DebuggerConnectionState.SUSPENDED, + DebuggerConnectionState.AWAITING_BREAKPOINT, + -> { + val threadResponse = + adapter.allThreads( + ThreadListRequestParams( + remoteClient = client, + ), + ) + + val threads = threadResponse.threads + if (threads.isEmpty()) { + logger.error("Failed to get info about active threads in VM: {}", client.name) + } else if (selectedThreadId != null) { + selectedThreadIndex = + threads.indexOfFirst { + it.descriptor().id == selectedThreadId + } + } + + threads + } + } + + if (threads.isNotEmpty() && selectedThreadIndex < 0) { + selectedThreadIndex = 0 + } + + viewModel.setThreads(threads, selectedThreadIndex) + } + + private suspend fun openLocation(event: LocatableEvent) = openLocation(event.location) + + private suspend fun openLocation(location: Location) { + val file = location.source.path + val position = Position(location.line, 0) + + val targetFile = File(file) + if (!targetFile.isFile) { + logger.debug("Skipping openLocation for non-existent source file: {}", file) + breakpoints.unhighlightHighlightedLocation() + return + } + + if (!IDELanguageClientImpl.isInitialized()) { + logger.error("Cannot open {}:{} because language client is not initialized", file, position.line) + return + } + + val activity = IDELanguageClientImpl.getInstance().activity + + if (activity == null) { + logger.error("Cannot open {}:{} because activity is null", file, position.line) + return + } + + breakpoints.highlightLocation(file, position.line) + + withContext(Dispatchers.Main.immediate) { + activity.openFileAndSelect( + file = targetFile, + selection = + Range( + start = position, + end = position, + ), + ) + } + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt index 1865fa14c0..4aded1db23 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/JavaDebugAdapter.kt @@ -274,6 +274,7 @@ internal class JavaDebugAdapter : doSuspensionIfEnabled(client) { vm -> try { logger.debug("resuming client: {}", client.name) + vm.evalContext.cancelAllPending() vm.vm.resume() true } catch (e: Throwable) { @@ -474,6 +475,7 @@ internal class JavaDebugAdapter : ) req.enable() + vm.evalContext.cancelPendingForThread(suspendedThread.thread) suspendedThread.thread.resume() vm.threadState.invalidateAll() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt index d41194ae28..3d26056dd4 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/LspThreadInfo.kt @@ -14,6 +14,9 @@ import com.itsaky.androidide.lsp.java.debug.utils.kotlinDisplayName import com.itsaky.androidide.lsp.java.debug.utils.kotlinLambdaScopes import com.itsaky.androidide.lsp.java.debug.utils.lineNumberInKotlin import com.itsaky.androidide.lsp.java.debug.utils.sourceNameInKotlinOrNull +import com.sun.jdi.AbsentInformationException +import com.sun.jdi.IncompatibleThreadStateException +import com.sun.jdi.InvalidStackFrameException import com.sun.jdi.Location import com.sun.jdi.Method import com.sun.jdi.ObjectCollectedException @@ -78,8 +81,11 @@ class JavaStackFrame( this.thisObject() }.getOrElse { e -> when (e) { - is VMDisconnectedException -> { - logger.warn("VM disconnected while fetching 'this' object.", e) + is VMDisconnectedException, + is InvalidStackFrameException, + is IncompatibleThreadStateException, + -> { + logger.warn("Frame or VM unavailable while fetching 'this' object: {}", e.message) return@evaluate emptyList() } @@ -128,6 +134,8 @@ class JavaStackFrame( ) } catch (e: VMDisconnectedException) { throw e + } catch (e: InvalidStackFrameException) { + throw e } catch (err: Throwable) { logger.error( "Failed to create variable wrapper for {}", @@ -142,6 +150,11 @@ class JavaStackFrame( } catch (e: VMDisconnectedException) { logger.warn("VM disconnected while reading local variables. Aborting.") return@evaluate emptyList() + } catch (e: InvalidStackFrameException) { + logger.warn("Frame invalidated while reading local variables: {}", e.message) + return@evaluate emptyList() + } catch (e: AbsentInformationException) { + logger.debug("No local variable information available for {}", location) } catch (e: Throwable) { logger.error("Error reading local variables", e) } @@ -188,7 +201,6 @@ class JavaStackFrame( internal class LspThreadInfo( val thread: ThreadInfo, - val frames: List = thread.frames(), ) : LspThreadInfo { companion object { private val logger = LoggerFactory.getLogger(LspThreadInfo::class.java) @@ -198,14 +210,20 @@ internal class LspThreadInfo( override suspend fun descriptor(): ThreadDescriptor = withContext(Dispatchers.IO) { - val thread = thread.thread - val group = thread.threadGroup() + val jdiThread = thread.thread + val id = runCatching { jdiThread.uniqueID().toString() }.getOrDefault("") + val name = runCatching { jdiThread.name() }.getOrDefault("") + val group = runCatching { jdiThread.threadGroup()?.name() }.getOrNull() ?: "" + val state = + runCatching { + threadStateOf(jdiThread.status()) + }.getOrDefault(LspThreadState.UNKNOWN) ThreadDescriptor( - id = thread.uniqueID().toString(), - name = thread.name(), - group = group.name(), - state = threadStateOf(thread.status()), + id = id, + name = name, + group = group, + state = state, ) } @@ -213,11 +231,32 @@ internal class LspThreadInfo( if (!::cachedFrames.isInitialized) { cachedFrames = JavaDebugAdapter.requireInstance().evalContext().evaluate(thread.thread) { - frames.map { frame -> - JavaStackFrame( - thread = thread.thread, - frame = frame, - ) + thread.frames().mapNotNull { frame -> + try { + JavaStackFrame( + thread = thread.thread, + frame = frame, + ) + } catch (e: Exception) { + when (e) { + is InvalidStackFrameException, + is IncompatibleThreadStateException, + is VMDisconnectedException, + -> { + throw e + } + + is ObjectCollectedException -> { + logger.warn("Skipping collected stack frame in thread {}", thread.thread.name()) + null + } + + else -> { + logger.error("Failed to materialize stack frame", e) + null + } + } + } } } ?: emptyList() } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt index 8566db64f6..296a73556b 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/Variables.kt @@ -259,15 +259,15 @@ internal class ThisVariable( value = ref, ) { @Suppress("UNCHECKED_CAST") - override suspend fun value(): ValueT { + override suspend fun value(): ValueT? { if (this.value == null) { return LspValue.UNDEFINED as ValueT } val evalContext = JavaDebugAdapter.requireInstance().evalContext() return evalContext.evaluate(thread) { - toLspValue(thread, value) - }!! as ValueT + toLspValue(thread, value) as ValueT + } } override suspend fun jdiValue(): Value? = value @@ -322,15 +322,15 @@ internal class JavaFieldVariable( override suspend fun isMutable(): Boolean = !field.isFinal && super.isMutable() @Suppress("UNCHECKED_CAST") - override suspend fun value(): ValueT { + override suspend fun value(): ValueT? { if (this.value == null) { return LspValue.UNDEFINED as ValueT } val evalContext = JavaDebugAdapter.requireInstance().evalContext() return evalContext.evaluate(thread) { - toLspValue(thread, value) - }!! as ValueT + toLspValue(thread, value) as ValueT + } } override suspend fun setValue(value: String): Boolean { diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/EvaluationContext.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/EvaluationContext.kt index e5dc67e9a3..bdc7306ff3 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/EvaluationContext.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/EvaluationContext.kt @@ -1,6 +1,10 @@ package com.itsaky.androidide.lsp.java.debug.utils +import com.sun.jdi.IncompatibleThreadStateException +import com.sun.jdi.InvalidStackFrameException +import com.sun.jdi.ObjectCollectedException import com.sun.jdi.ThreadReference +import com.sun.jdi.VMDisconnectedException import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope @@ -16,137 +20,207 @@ import java.util.concurrent.atomic.AtomicLong internal typealias Evaluator = suspend () -> R private sealed interface EvaluationMessage { - data class EvaluateRequest( - val thread: ThreadReference, - val evaluator: Evaluator, - val deferred: CompletableDeferred, - val id: Long = Companion.id.getAndIncrement() - ) : EvaluationMessage { - companion object { - private val id = AtomicLong(0) - } - } - - data object Shutdown : EvaluationMessage + data class EvaluateRequest( + val thread: ThreadReference, + val evaluator: Evaluator, + val deferred: CompletableDeferred, + val id: Long = Companion.id.getAndIncrement(), + ) : EvaluationMessage { + companion object { + private val id = AtomicLong(0) + } + } + + data class CancelPending( + val thread: ThreadReference? = null, + ) : EvaluationMessage + + data object Shutdown : EvaluationMessage } class EvaluationContext : AutoCloseable { - companion object { - private val logger = LoggerFactory.getLogger(EvaluationContext::class.java) - } - - override fun close() { - evaluationActor.trySend(EvaluationMessage.Shutdown) - evaluationActor.close() - } - - private val sequentialDispatcher = Dispatchers.IO.limitedParallelism(1) - - - @OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class) - private val evaluationActor = CoroutineScope(sequentialDispatcher).actor( - capacity = Channel.UNLIMITED - ) { - val threadBatches = - mutableMapOf>>() - - for (message in channel) { - when (message) { - is EvaluationMessage.EvaluateRequest<*> -> { - threadBatches.getOrPut(message.thread) { mutableListOf() }.add(message) - delay(10) // Small delay to allow batching - - if (channel.isEmpty) { - try { - processBatches(threadBatches) - } catch (e: Throwable) { - logger.error("Failed to process evaluator batches", e) - } - } - } - - is EvaluationMessage.Shutdown -> { - cancelPendingRequests(threadBatches) - break - } - } - } - } - - suspend fun evaluate( - thread: ThreadReference, - evaluator: Evaluator - ): R? { - val deferred = CompletableDeferred() - val request = EvaluationMessage.EvaluateRequest(thread, evaluator, deferred) - - evaluationActor.send(request) - return deferred.await() - } - - private suspend fun processBatches(threadBatches: MutableMap>>) { - threadBatches.forEach { (thread, requests) -> - if (requests.isNotEmpty()) { - processBatchForThread(thread, requests) - requests.clear() - } - } - } - - private suspend fun processBatchForThread( - thread: ThreadReference, - requests: List> - ) { - val threadName = thread.name() - logger.debug( - "Processing batch of {} requests for thread {}", - requests.size, - threadName - ) - - // Ensure thread is still suspended - if (!thread.isSuspended) { - logger.warn("Thread $threadName is not suspended, failing batch for thread {}", threadName) - val exception = IllegalStateException("Thread $threadName is not suspended") - requests.forEach { request -> - request.deferred.completeExceptionally(exception) - } - return - } - - // Process each request sequentially - requests.forEach { request -> - try { - @Suppress("UNCHECKED_CAST") - val typedRequest = request as EvaluationMessage.EvaluateRequest - val result = typedRequest.evaluator() - typedRequest.deferred.complete(result) - } catch (e: Exception) { - logger.error("Failed to execute evaluation for thread {}", threadName, e) - request.deferred.completeExceptionally(e) - } - } - } - - private fun cancelPendingRequests( - threadBatches: MutableMap>> - ) { - logger.debug("Cancelling pending evaluation requests") - val cancellationException = CancellationException("EvaluationContext is shutting down") - threadBatches.values.forEach { requests -> - requests.forEach { request -> - request.deferred.cancel(cancellationException) - } - } - - val totalCancelled = threadBatches.values.sumOf { it.size } - if (totalCancelled > 0) { - logger.debug( - "Cancelled {} pending evaluation requests due to shutdown", - totalCancelled - ) - } - - threadBatches.clear() - } -} \ No newline at end of file + companion object { + private val logger = LoggerFactory.getLogger(EvaluationContext::class.java) + } + + override fun close() { + evaluationActor.trySend(EvaluationMessage.Shutdown) + evaluationActor.close() + } + + fun cancelPendingForThread(thread: ThreadReference) { + evaluationActor.trySend(EvaluationMessage.CancelPending(thread)) + } + + fun cancelAllPending() { + evaluationActor.trySend(EvaluationMessage.CancelPending(null)) + } + + private val sequentialDispatcher = Dispatchers.IO.limitedParallelism(1) + + @OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class) + private val evaluationActor = + CoroutineScope(sequentialDispatcher).actor( + capacity = Channel.UNLIMITED, + ) { + val threadBatches = + mutableMapOf>>() + + for (message in channel) { + when (message) { + is EvaluationMessage.EvaluateRequest<*> -> { + threadBatches.getOrPut(message.thread) { mutableListOf() }.add(message) + delay(10) // Small delay to allow batching + + if (channel.isEmpty) { + processBatches(threadBatches) + } + } + + is EvaluationMessage.CancelPending -> { + dropPendingRequests(threadBatches, message.thread) + // Other threads' batches may have been deferred behind this message. + if (channel.isEmpty) { + processBatches(threadBatches) + } + } + + is EvaluationMessage.Shutdown -> { + cancelPendingRequests(threadBatches) + break + } + } + } + } + + suspend fun evaluate( + thread: ThreadReference, + evaluator: Evaluator, + ): R? { + val deferred = CompletableDeferred() + val request = EvaluationMessage.EvaluateRequest(thread, evaluator, deferred) + + val sendResult = evaluationActor.trySend(request) + if (sendResult.isFailure) { + return null + } + return deferred.await() + } + + private suspend fun processBatches(threadBatches: MutableMap>>) { + try { + threadBatches.forEach { (thread, requests) -> + if (requests.isNotEmpty()) { + processBatchForThread(thread, requests) + requests.clear() + } + } + } catch (e: CancellationException) { + threadBatches.values.forEach { requests -> + requests.forEach { it.deferred.complete(null) } + requests.clear() + } + throw e + } catch (e: Throwable) { + logger.error("Failed to process evaluator batches", e) + } + } + + private suspend fun processBatchForThread( + thread: ThreadReference, + requests: List>, + ) { + val threadName = runCatching { thread.name() }.getOrDefault("") + logger.debug( + "Processing batch of {} requests for thread {}", + requests.size, + threadName, + ) + + // Ensure thread is still suspended + val isSuspended = runCatching { thread.isSuspended }.getOrDefault(false) + if (!isSuspended) { + logger.warn("Thread {} is not suspended, skipping batch of {} requests", threadName, requests.size) + requests.forEach { request -> + request.deferred.complete(null) + } + return + } + + // Process each request sequentially + requests.forEach { request -> + if (!runCatching { thread.isSuspended }.getOrDefault(false)) { + logger.warn("Thread {} resumed during batch, skipping remaining request", threadName) + request.deferred.complete(null) + return@forEach + } + + try { + @Suppress("UNCHECKED_CAST") + val typedRequest = request as EvaluationMessage.EvaluateRequest + val result = typedRequest.evaluator() + typedRequest.deferred.complete(result) + } catch (e: CancellationException) { + request.deferred.cancel(e) + throw e + } catch (e: Exception) { + when (e) { + is InvalidStackFrameException, + is IncompatibleThreadStateException, + is ObjectCollectedException, + is VMDisconnectedException, + -> { + logger.warn("Skipping stale evaluation for thread {}: {}", threadName, e.message) + } + + else -> { + logger.error("Failed to execute evaluation for thread {}", threadName, e) + } + } + request.deferred.complete(null) + } + } + } + + private fun dropPendingRequests( + threadBatches: MutableMap>>, + targetThread: ThreadReference?, + ) { + if (targetThread != null) { + val requests = threadBatches.remove(targetThread) ?: return + if (requests.isNotEmpty()) { + logger.debug("Dropping {} pending evaluation requests for resumed thread", requests.size) + requests.forEach { it.deferred.complete(null) } + } + } else { + val totalDropped = threadBatches.values.sumOf { it.size } + if (totalDropped > 0) { + logger.debug("Dropping {} pending evaluation requests across all threads", totalDropped) + } + threadBatches.values.forEach { requests -> + requests.forEach { it.deferred.complete(null) } + } + threadBatches.clear() + } + } + + private fun cancelPendingRequests(threadBatches: MutableMap>>) { + logger.debug("Cancelling pending evaluation requests") + val cancellationException = CancellationException("EvaluationContext is shutting down") + threadBatches.values.forEach { requests -> + requests.forEach { request -> + request.deferred.cancel(cancellationException) + } + } + + val totalCancelled = threadBatches.values.sumOf { it.size } + if (totalCancelled > 0) { + logger.debug( + "Cancelled {} pending evaluation requests due to shutdown", + totalCancelled, + ) + } + + threadBatches.clear() + } +} diff --git a/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/EvaluationContextTest.kt b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/EvaluationContextTest.kt new file mode 100644 index 0000000000..0d3590bf7f --- /dev/null +++ b/lsp/java/src/test/java/com/itsaky/androidide/lsp/java/debug/EvaluationContextTest.kt @@ -0,0 +1,283 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.debug + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.java.debug.utils.EvaluationContext +import com.sun.jdi.IncompatibleThreadStateException +import com.sun.jdi.InvalidStackFrameException +import com.sun.jdi.ObjectCollectedException +import com.sun.jdi.ThreadReference +import com.sun.jdi.VMDisconnectedException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.junit.After +import org.junit.Before +import org.junit.Test +import java.lang.reflect.InvocationHandler +import java.lang.reflect.Method +import java.lang.reflect.Proxy + +class EvaluationContextTest { + private lateinit var context: EvaluationContext + + @Before + fun setUp() { + context = EvaluationContext() + } + + @After + fun tearDown() { + context.close() + } + + private fun fakeThread( + isSuspended: Boolean, + name: String = "test-thread", + ): ThreadReference { + val handler = + object : InvocationHandler { + override fun invoke( + proxy: Any, + method: Method, + args: Array?, + ): Any? = + when (method.name) { + "isSuspended" -> isSuspended + "name" -> name + "equals" -> args?.getOrNull(0) === proxy + "hashCode" -> System.identityHashCode(proxy) + "toString" -> "FakeThreadReference($name)" + else -> null + } + } + return Proxy.newProxyInstance( + ThreadReference::class.java.classLoader, + arrayOf(ThreadReference::class.java), + handler, + ) as ThreadReference + } + + @Test + fun `evaluate returns result when thread is suspended`() = + runBlocking { + val thread = fakeThread(isSuspended = true, name = "suspended-thread") + + val result = context.evaluate(thread) { "computed-value" } + + assertThat(result).isEqualTo("computed-value") + } + + @Test + fun `evaluate returns null when thread is not suspended`() = + runBlocking { + val thread = fakeThread(isSuspended = false, name = "resumed-thread") + + val result = context.evaluate(thread) { "should-never-run" } + + assertThat(result).isNull() + } + + @Test + fun `evaluate returns null on InvalidStackFrameException`() = + runBlocking { + val thread = fakeThread(isSuspended = true) + + val result = + context.evaluate(thread) { + throw InvalidStackFrameException("Thread has been resumed") + } + + assertThat(result).isNull() + } + + @Test + fun `evaluate returns null on IncompatibleThreadStateException`() = + runBlocking { + val thread = fakeThread(isSuspended = true) + + val result = + context.evaluate(thread) { + throw IncompatibleThreadStateException() + } + + assertThat(result).isNull() + } + + @Test + fun `evaluate returns null on ObjectCollectedException`() = + runBlocking { + val thread = fakeThread(isSuspended = true) + + val result = + context.evaluate(thread) { + throw ObjectCollectedException() + } + + assertThat(result).isNull() + } + + @Test + fun `evaluate returns null on VMDisconnectedException`() = + runBlocking { + val thread = fakeThread(isSuspended = true) + + val result = + context.evaluate(thread) { + throw VMDisconnectedException() + } + + assertThat(result).isNull() + } + + @Test + fun `cancelPendingForThread drops queued requests with null`() = + runBlocking { + val thread = fakeThread(isSuspended = true, name = "cancel-thread") + + val deferred = + async(Dispatchers.Unconfined) { + context.evaluate(thread) { + "should-be-dropped" + } + } + + context.cancelPendingForThread(thread) + + assertThat(deferred.await()).isNull() + } + + @Test + fun `cancelAllPending drops queued requests across threads with null`() = + runBlocking { + val thread1 = fakeThread(isSuspended = true, name = "thread-1") + val thread2 = fakeThread(isSuspended = true, name = "thread-2") + + val first = + async(Dispatchers.Unconfined) { + context.evaluate(thread1) { + "thread-1-val" + } + } + val second = + async(Dispatchers.Unconfined) { + context.evaluate(thread2) { + "thread-2-val" + } + } + + context.cancelAllPending() + + assertThat(first.await()).isNull() + assertThat(second.await()).isNull() + } + + @Test + fun `cancelPendingForThread does not strand batches of other threads`() = + runBlocking { + val other = fakeThread(isSuspended = true, name = "other-thread") + val stepped = fakeThread(isSuspended = true, name = "stepped-thread") + + val pending = + async(Dispatchers.Unconfined) { + context.evaluate(other) { "other-val" } + } + + // Lands in the channel during the batching delay for `other`. + context.cancelPendingForThread(stepped) + + val result = withTimeout(2_000) { pending.await() } + assertThat(result).isEqualTo("other-val") + } + + @Test + fun `subsequent evaluations in a batch return null when thread resumes during batch`() = + runBlocking { + var isSuspended = true + val handler = + object : InvocationHandler { + override fun invoke( + proxy: Any, + method: Method, + args: Array?, + ): Any? = + when (method.name) { + "isSuspended" -> isSuspended + "name" -> "dynamic-thread" + "equals" -> args?.getOrNull(0) === proxy + "hashCode" -> System.identityHashCode(proxy) + "toString" -> "FakeThreadReference(dynamic-thread)" + else -> null + } + } + val thread = + Proxy.newProxyInstance( + ThreadReference::class.java.classLoader, + arrayOf(ThreadReference::class.java), + handler, + ) as ThreadReference + + val first = + async { + context.evaluate(thread) { + isSuspended = false + "first" + } + } + val second = + async { + context.evaluate(thread) { + "second" + } + } + + assertThat(first.await()).isEqualTo("first") + assertThat(second.await()).isNull() + } + + @Test + fun `processBatches completes remaining batches with null on CancellationException`() = + runBlocking { + val thread1 = fakeThread(isSuspended = true, name = "thread-1") + val thread2 = fakeThread(isSuspended = true, name = "thread-2") + + val cancelled = + async(Dispatchers.Unconfined) { + context.evaluate(thread1) { + throw CancellationException("evaluator cancelled") + } + } + val sibling = + async(Dispatchers.Unconfined) { + context.evaluate(thread2) { + "sibling-val" + } + } + + try { + cancelled.await() + } catch (_: CancellationException) { + } + + val siblingResult = withTimeout(2_000) { sibling.await() } + assertThat(siblingResult).isNull() + } +}