diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 80760880e..2cfc76717 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1649,7 +1649,7 @@ pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "jvm-inspect", - "1.1.0", + "1.1.1", include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"), ) } @@ -1745,7 +1745,7 @@ mod usages_bundle_tests { std::fs::write(dir.path().join(name), b"old").unwrap(); } let jar = super::jvm_inspect_bundle(dir.path()).unwrap(); - assert_eq!(jar, dir.path().join("jvm-inspect-1.1.0.jar")); + assert_eq!(jar, dir.path().join("jvm-inspect-1.1.1.jar")); assert_eq!(std::fs::read(&jar).unwrap(), include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar")); assert!(!dir.path().join("jvm-inspect-0.9.0.jar").exists()); assert_eq!(std::fs::read(dir.path().join("java-usages-1.7.0.jar")).unwrap(), b"old"); diff --git a/java/jvm-inspect/MANIFEST.MF b/java/jvm-inspect/MANIFEST.MF index 8475f27ec..40d85ff1b 100644 --- a/java/jvm-inspect/MANIFEST.MF +++ b/java/jvm-inspect/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA JVM inspect Bundle-SymbolicName: ai.openidea.jvminspect;singleton:=true -Bundle-Version: 1.1.0 +Bundle-Version: 1.1.1 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.core.runtime, org.eclipse.equinox.common,org.eclipse.jdt.debug,org.eclipse.core.resources diff --git a/java/jvm-inspect/README.md b/java/jvm-inspect/README.md index 6baed033d..688edd60f 100644 --- a/java/jvm-inspect/README.md +++ b/java/jvm-inspect/README.md @@ -123,6 +123,13 @@ ordinary `executeCommand` error. invoke go on (ide-dap does that unseen while the trace runs). The outcome is forced into the frame before it is pinned, so the pending return keeps it reachable; should it be collected before that, the program gets the cancel exception and the trace fails. +- An exception the terminal threw (the cancel exception of `abort` included) ends the client's + `stepOut` in the program's catch. Nothing catching it, the thread would die with no stop left to + `collect` in, so before parking the bundle adds an uncaught-exception request on the thread, + suspending it: the step-out ends at that throw instead, as a java-debug `exception` stop, and a + resume lets the exception end the thread as it would have. Skipped when an enabled request of + java-debug's already reports uncaught throws of that type (one stop, not two). `collect` deletes it; + after `collect` a release no longer resumes the parked event, since that stop keeps the parked frames. - `wait` returns as soon as the trace leaves `running`, or after `ms`, at most 30 000. While the terminal runs it also checks every 500 ms whether the VM began to shut down (`jdk.internal.misc.VM.initLevel`): `System.exit` in a lambda makes the VM wait forever to report @@ -204,7 +211,7 @@ Java 21. The recorder is compiled by the `javac` on `PATH` with `--release 8`, s run Java 8. Build twice and compare: two builds of the checked-in jar gave ``` -22980a16bd8e303d67ed2e04d76d8974f2d3981120c26e6d9afa47ba361b1503 openidea-jvm-inspect.jar +4ab30723afe1254b991d9457ea66271109f397a17b238870572283aad73338ad openidea-jvm-inspect.jar ``` Change `Bundle-Version` whenever the jar changes: OSGi caches bundles by version. diff --git a/java/jvm-inspect/openidea-jvm-inspect.jar b/java/jvm-inspect/openidea-jvm-inspect.jar index f67c5e2aa..f2614c6b1 100644 Binary files a/java/jvm-inspect/openidea-jvm-inspect.jar and b/java/jvm-inspect/openidea-jvm-inspect.jar differ diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java index 60cd077a9..4bf0ed2f3 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java @@ -31,6 +31,8 @@ import com.sun.jdi.event.MethodExitEvent; import com.sun.jdi.event.VMDeathEvent; import com.sun.jdi.event.VMDisconnectEvent; import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.EventRequestManager; +import com.sun.jdi.request.ExceptionRequest; import com.sun.jdi.request.MethodEntryRequest; import com.sun.jdi.request.MethodExitRequest; import com.sun.jdi.request.StepRequest; @@ -170,6 +172,10 @@ final class RealRunTrace { private Value echoValue; private EventSet parked; private Method terminalMethod; + /** Stops the thread at a throw of the terminal's that nothing catches; see {@link #watchUncaught}. */ + private volatile EventRequest uncaught; + /** {@code collect} ran, so the client's step-out ended in a stop of its own; see {@link #dispose}. */ + private volatile boolean steppedOut; private RealRunTrace(long id, VirtualMachine vm, ThreadReference thread, RealRunPlan plan, int budget, long generation) { this.id = id; @@ -514,6 +520,8 @@ final class RealRunTrace { } if (outcome instanceof ObjectReference object) keep(pinned(object)); restoreSilencers(); + // Before the state moves: the client steps out as soon as it sees the trace parked. + if (kind.equals("threw")) watchUncaught((ObjectReference) outcome); boolean hold; synchronized (stateLock) { terminalKind = kind; @@ -532,10 +540,61 @@ final class RealRunTrace { if (hold) { parked = set; terminalMethod = method; + } else { + deleteUncaught(); } return hold; } + /** + * Worker, before the trace parks on a terminal that threw. The client's step-out ends in the + * program's catch, but an exception nothing catches ends the thread, with no stop left to read the + * records in. This request stops the thread at that throw instead: java-debug reports every + * exception event as a stop. Not when an enabled request of java-debug's already stops there, + * since the throw would then be reported twice. + */ + private void watchUncaught(ObjectReference exception) { + try { + EventRequestManager manager = vm.eventRequestManager(); + ReferenceType type = exception.referenceType(); + for (ExceptionRequest r : manager.exceptionRequests()) { + if (r.isEnabled() && r.notifyUncaught() && r.getProperty(Silencer.OWN_PROPERTY) == null && covers(r.exception(), type)) { + return; + } + } + ExceptionRequest r = manager.createExceptionRequest(null, false, true); + r.addThreadFilter(thread); + r.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); + r.putProperty(Silencer.OWN_PROPERTY, id); + r.enable(); + uncaught = r; + } catch (VMDisconnectedException e) { + // nothing left to stop + } catch (RuntimeException e) { + errors.add("watching for an uncaught throw: " + e); + } + } + + private static boolean covers(ReferenceType declared, ReferenceType type) { + for (ReferenceType t = type; t != null; t = t instanceof ClassType c ? c.superclass() : null) { + if (declared == null || t.equals(declared)) return true; + } + return false; + } + + private void deleteUncaught() { + EventRequest r = uncaught; + if (r == null) return; + uncaught = null; + try { + vm.eventRequestManager().deleteEventRequest(r); + } catch (VMDisconnectedException e) { + // it went with the VM + } catch (RuntimeException e) { + errors.add("deleting the uncaught-throw request: " + e); + } + } + /** * Worker, right before the terminal's invoke. JDWP holds an interrupt or stop of a thread that is * handling an event until that event's handler exits, and an invoke runs inside the handler of the @@ -758,9 +817,11 @@ final class RealRunTrace { /** Worker: everything the trace holds, a parked thread the client never stepped out included. */ private void dispose() { if (parked != null) { - if (stillParked()) resume(parked); + // A stop at an uncaught throw of the terminal's keeps the parked frames: resuming would end it behind java-debug. + if (!steppedOut && stillParked()) resume(parked); parked = null; } + deleteUncaught(); teardown(); for (ObjectReference o : pinned) { try { @@ -996,6 +1057,8 @@ final class RealRunTrace { if (generation <= this.generation) { throw new Failure("stale", "collect needs a stop after the trace's, not generation " + generation); } + steppedOut = true; + deleteUncaught(); handles.begin(generation); ToLongFunction handle = o -> { long objectId = o.uniqueID(); diff --git a/java/jvm-inspect/tests/stream.py b/java/jvm-inspect/tests/stream.py index e17727589..c27802ab3 100644 --- a/java/jvm-inspect/tests/stream.py +++ b/java/jvm-inspect/tests/stream.py @@ -100,6 +100,9 @@ public class Real { case "inl": inLambda(); break; case "abort": abort(); break; case "twice": abortAfterTrace(); break; + case "U": uncaught(true); break; + case "Ux": uncaught(false); break; + case "Ua": abortUncaught(); break; case "exit": exit(); break; case "mid": mid(); break; case "fn": functionAndData(); break; @@ -244,6 +247,23 @@ public class Real { } } + /** Keeps the VM alive once main has died of an exception. */ + static void keeper() { + new Thread(() -> LockSupport.parkNanos(60_000_000_000L), "keeper").start(); + } + + static void uncaught(boolean keep) { + if (keep) keeper(); + List u = nums.stream().map(x -> 10 / (x - 4)).collect(Collectors.toList()); // @U + System.out.println("U " + u); + } + + static void abortUncaught() { + keeper(); + long never = Stream.iterate(1L, x -> x + 1).filter(x -> x < 0).count(); // @Ua + System.out.println("UA none " + never); + } + static void exit() { List e = nums.stream().filter(x -> { // @exit if (x == 8) System.exit(3); @@ -1025,6 +1045,77 @@ def real_run_abort_after_a_trace(): dbg.end() +def uncaught_stop(dbg, name, trace, exception): + """After a terminal that threw what the program does not catch: the step-out ends in one stop at that + throw, the records can be read there, and Resume lets the exception end the thread. False when no + stop came.""" + try: + stop = step_out(dbg, 15) + except (TimeoutError, AssertionError) as e: + check(f'{name}: the uncaught throw stops the traced thread', False, repr(e)) + return False + check(f'{name}: the uncaught throw stops the traced thread', stop.get('reason') == 'exception', stop) + check(f'{name}: one stop for the throw', no_stop(dbg, 2)) + c = ok(stream('collect', dbg, traceId=trace)) + t = c['terminal'] + check(f'{name}: the terminal threw {exception}', t['kind'] == 'threw' and t['exception'].get('typeName') == exception, t) + check(f'{name}: release keeps the stop', 'ok' in stream('release', dbg, traceId=trace) and top(dbg) is not None) + resume(dbg) + out = output_line(dbg, 'Exception in thread "main" ' + exception) + check(f'{name}: the exception ends the thread as without the trace', out is not None, ''.join(dbg.dap.output)[-300:]) + check(f'{name}: no stop after Resume', no_stop(dbg, 2)) + return c + + +@case +def real_run_uncaught_throw(): + # `U` keeps the VM alive with another thread; `Ux` exits with main. + for name in ('U', 'Ux'): + dbg = real(name, 'U') + try: + trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',)) + check(f'{name}: parked after the lambda threw', state['state'] == 'parked', state) + c = uncaught_stop(dbg, name, trace, 'java.lang.ArithmeticException') + if c: + collected_ok(name, c, records=['0=5', '1=10', '0=3', '1=-10', '0=8', '1=2', '0=1', '1=-3', '0=4']) + finally: + dbg.end() + + +@case +def real_run_uncaught_throw_user_filter(): + # java-debug's own uncaught-exception request is on: the throw must stop once, not once per request. + dbg = real('U') + try: + dbg.dap.request('setExceptionBreakpoints', {'filters': ['uncaught']}) + trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',)) + check('U-filter: parked after the lambda threw', state['state'] == 'parked', state) + uncaught_stop(dbg, 'U-filter', trace, 'java.lang.ArithmeticException') + finally: + dbg.end() + + +@case +def real_run_uncaught_abort(): + dbg = real('Ua') + try: + trace = ok(arm(dbg, at='Ua', root=spec('iterate', 2), steps=(spec('filter', 1),), terminal=spec('count'), + class_filters=('java.util.stream.*',), step_kinds=('sync',)))['traceId'] + resume(dbg) + first = ok(stream('wait', dbg, traceId=trace, ms=500)) + check('Ua: the endless terminal is running', first['state'] == 'running', first) + r = ok(stream('abort', dbg, traceId=trace, timeout=30)) + check('Ua: interrupted or stopped', r.get('state') in ('interrupted', 'stopped'), r) + state = wait_until_done(dbg, trace, 20) + check('Ua: parked after the cancel', state['state'] == 'parked', state) + if state['state'] == 'parked': + c = uncaught_stop(dbg, 'Ua', trace, 'java.lang.RuntimeException') + if c: + check('Ua: the records up to the abort', len(c['records']) > 0, len(c['records'])) + finally: + dbg.end() + + def next_breakpoint_stops(dbg, name, what): """After a trace that ended without parking: the user's breakpoints are back on.""" try: