mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
feat(debugger): Java exception breakpoints for a chosen class (#4954)
The Breakpoints dialog gains Java Exception Breakpoints on a chosen class (subclasses included): Caught and/or Uncaught, optionally limited by class filters on the throwing code. java-debug's Caught/Uncaught filters stay as the Any exception row. java-debug has no per-class exception requests, so the jvm-inspect bundle (1.2.0) makes the JDI exception requests itself; ide-dap arms them before configurationDone (a throw on main's first line stops) and again after each setExceptionBreakpoints, which drops them. Condition and catch-class filters show disabled with the reason. The bundle jar was rebuilt from source and matches the checked-in one byte for byte. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com>
This commit is contained in:
@@ -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.1
|
||||
Bundle-Version: 1.2.0
|
||||
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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
An OSGi bundle loaded into JDT LS next to microsoft java-debug. While a Java debug session is
|
||||
suspended, it lists the instances of a class, the fields of an object and the objects that refer to
|
||||
it, and counts the instances of every loaded class; it also traces a stream chain while the program
|
||||
runs it. It works on java-debug's own JDI connection to the debuggee, so no second debugger connects
|
||||
runs it, and stops on the exceptions of a chosen class. It works on java-debug's own JDI connection to the debuggee, so no second debugger connects
|
||||
to the JVM.
|
||||
|
||||
## Commands
|
||||
@@ -159,6 +159,33 @@ waiting behind the command time out too. These two commands raise it to at least
|
||||
when done, put back the old value unless something else changed it meanwhile (java-debug applies its
|
||||
timeout setting to every VM when it changes).
|
||||
|
||||
## Exception breakpoints
|
||||
|
||||
`openidea.jvm.exceptions.set` takes `target` first, then `{breakpoints: [{id, className, caught,
|
||||
uncaught, enabled, classFilters, classExclusionFilters}]}`, and replaces the VM's whole list. `ok`
|
||||
is `[{id, state}]` in the same order, `state` being `armed`, `pending` (the class is not loaded yet),
|
||||
`disabled` (off, or neither `caught` nor `uncaught`) or `deferred`. A missing `id` or `className` is
|
||||
an `executeCommand` error; a VM whose session java-debug did not register gives `noSession`.
|
||||
|
||||
- Each breakpoint is a JDI exception request on every loaded class of that name, subclasses
|
||||
included, plus a class-prepare request that arms classes loaded later or by another class loader.
|
||||
java-debug turns every exception event into a stop, whoever made the request, so the stop, the
|
||||
stack and `exceptionInfo` are java-debug's own.
|
||||
- `classFilters` / `classExclusionFilters` are JDI class patterns (`com.acme.*`, `*Test`) matched
|
||||
against the class whose code throws.
|
||||
- java-debug deletes every exception request when it handles `setExceptionBreakpoints`. Send the
|
||||
list again after each one, and before `configurationDone` to stop on a throw in `main`'s first line.
|
||||
- One throw matched by two requests gives two stops. A request leaves out the caught or uncaught
|
||||
throws that java-debug's enabled all-exception filters report, or an enabled breakpoint without
|
||||
class filters on a superclass, or on the same class when that one comes earlier in the list or this
|
||||
one has filters. Two breakpoints that both have class filters can still both stop on one throw.
|
||||
- No conditions and no catch-location filters: java-debug stops on every exception event it gets,
|
||||
and an event-hub subscriber cannot keep it from stopping.
|
||||
- While a stream trace silences the VM's breakpoints, a new list is `deferred` and applied when the
|
||||
trace ends, as is a class prepared meanwhile. Its requests are silenced and restored with the
|
||||
rest; a trace that ends at an uncaught throw watches the throw itself only when no java-debug
|
||||
request, nor a breakpoint without class filters, already stops there.
|
||||
|
||||
## Internals it depends on
|
||||
|
||||
java-debug is not pinned: the app installs the latest vscode-java-debug. The bundle reaches the VMs
|
||||
@@ -211,7 +238,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
|
||||
|
||||
```
|
||||
4ab30723afe1254b991d9457ea66271109f397a17b238870572283aad73338ad openidea-jvm-inspect.jar
|
||||
5278f1d38325551c5d4ab50b5140551f91c3bf5b9db536aeb276713578e0fd49 openidea-jvm-inspect.jar
|
||||
```
|
||||
|
||||
Change `Bundle-Version` whenever the jar changes: OSGi caches bundles by version.
|
||||
@@ -243,3 +270,13 @@ PATH=/path/to/jdk25/bin:$PATH \
|
||||
OPENIDEA_TEST_JAVA=/path/to/jdk11/bin/java:/path/to/jdk21/bin/java \
|
||||
python3 -I tests/stream.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-0.53.2.jar --bundle x.jar
|
||||
```
|
||||
|
||||
`tests/exceptions.py` checks `openidea.jvm.exceptions.set` on the `java` on `PATH`: a throw in
|
||||
`main`'s first line in a launch and in an attach, a class loaded late, class filters, the re-arm
|
||||
after `setExceptionBreakpoints`, no double stop with java-debug's filters or a superclass breakpoint,
|
||||
and a hot swap of the throwing class. It takes `--bundle` too:
|
||||
|
||||
```sh
|
||||
PATH=/path/to/jdk25/bin:$PATH \
|
||||
python3 -I tests/exceptions.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-0.53.2.jar
|
||||
```
|
||||
|
||||
Binary file not shown.
@@ -16,5 +16,8 @@
|
||||
<command id="openidea.jvm.stream.collect"/>
|
||||
<command id="openidea.jvm.stream.release"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.jvminspect.ExceptionCommand">
|
||||
<command id="openidea.jvm.exceptions.set"/>
|
||||
</delegateCommandHandler>
|
||||
</extension>
|
||||
</plugin>
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package ai.openidea.jvminspect;
|
||||
|
||||
import ai.openidea.jvminspect.InspectCommand.Failure;
|
||||
import com.sun.jdi.ClassType;
|
||||
import com.sun.jdi.ReferenceType;
|
||||
import com.sun.jdi.VMDisconnectedException;
|
||||
import com.sun.jdi.VirtualMachine;
|
||||
import com.sun.jdi.event.ClassPrepareEvent;
|
||||
import com.sun.jdi.event.Event;
|
||||
import com.sun.jdi.request.ClassPrepareRequest;
|
||||
import com.sun.jdi.request.EventRequest;
|
||||
import com.sun.jdi.request.EventRequestManager;
|
||||
import com.sun.jdi.request.ExceptionRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Exception breakpoints on a chosen class, one list per VM, as exception requests of the bundle's own.
|
||||
* java-debug turns every exception event into a stop, whoever made its request. It also deletes every
|
||||
* exception request whenever it sets its own filters, so the client sends the list again after each
|
||||
* {@code setExceptionBreakpoints}. Two requests that match one throw give two stops, so a request
|
||||
* leaves out what an enabled java-debug filter or a breakpoint on a superclass already reports.
|
||||
*/
|
||||
final class ExceptionBreakpoints {
|
||||
/** Marks the bundle's requests; the value is the {@link Spec}. Not {@link Silencer#OWN_PROPERTY}: a trace silences these. */
|
||||
static final String PROPERTY = "oi.exc";
|
||||
private static final Map<VirtualMachine, ExceptionBreakpoints> VMS = new IdentityHashMap<>();
|
||||
|
||||
record Spec(String id, String className, boolean caught, boolean uncaught, boolean enabled, List<String> classFilters,
|
||||
List<String> classExclusionFilters) {
|
||||
/** From the Gson JSON of {@code executeCommand}. */
|
||||
static Spec of(Object json) {
|
||||
Map<?, ?> m = (Map<?, ?>) json;
|
||||
return new Spec(text(m, "id"), text(m, "className"), Boolean.TRUE.equals(m.get("caught")), Boolean.TRUE.equals(m.get("uncaught")),
|
||||
!Boolean.FALSE.equals(m.get("enabled")), patterns(m.get("classFilters")), patterns(m.get("classExclusionFilters")));
|
||||
}
|
||||
|
||||
boolean hasClassFilters() {
|
||||
return !classFilters.isEmpty() || !classExclusionFilters.isEmpty();
|
||||
}
|
||||
|
||||
private static String text(Map<?, ?> m, String key) {
|
||||
if (!(m.get(key) instanceof String s) || s.isBlank()) throw new IllegalArgumentException("missing " + key);
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static List<String> patterns(Object json) {
|
||||
if (!(json instanceof List<?> list)) return List.of();
|
||||
return list.stream().filter(String.class::isInstance).map(s -> ((String) s).trim()).filter(s -> !s.isEmpty()).toList();
|
||||
}
|
||||
}
|
||||
|
||||
record Flags(boolean caught, boolean uncaught) {
|
||||
boolean none() {
|
||||
return !caught && !uncaught;
|
||||
}
|
||||
}
|
||||
|
||||
private final VirtualMachine vm;
|
||||
private JavaDebugSessions.Subscription subscription;
|
||||
private List<Spec> specs = List.of();
|
||||
/** The list to apply once the VM's stream trace no longer silences its breakpoints. */
|
||||
private List<Spec> deferred;
|
||||
private boolean javaDebugCaught;
|
||||
private boolean javaDebugUncaught;
|
||||
|
||||
private ExceptionBreakpoints(VirtualMachine vm) {
|
||||
this.vm = vm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the VM's list. Under the inspect commands' lock, which a stream trace's {@code arm} holds
|
||||
* too: a request made while a trace silences breakpoints would be on inside the trace.
|
||||
*
|
||||
* @return per breakpoint {@code {id, state}}: {@code armed}, {@code pending} (class not loaded yet),
|
||||
* {@code disabled} or {@code deferred} (applied when the VM's stream trace ends)
|
||||
*/
|
||||
static List<Map<String, Object>> set(VirtualMachine vm, List<Spec> specs) throws Failure, ConnectedVms.Unsupported {
|
||||
synchronized (InspectCommand.handlesFor(vm)) {
|
||||
ExceptionBreakpoints state;
|
||||
synchronized (VMS) {
|
||||
state = VMS.computeIfAbsent(vm, ExceptionBreakpoints::new);
|
||||
}
|
||||
return state.replace(specs);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the lists of VMs java-debug no longer has; their requests went with the VM. */
|
||||
static void forgetGone(Set<VirtualMachine> live) {
|
||||
List<ExceptionBreakpoints> gone = new ArrayList<>();
|
||||
synchronized (VMS) {
|
||||
VMS.entrySet().removeIf(e -> !live.contains(e.getKey()) && gone.add(e.getValue()));
|
||||
}
|
||||
for (ExceptionBreakpoints state : gone) state.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* After a stream trace switched the breakpoints back on: applies a list deferred meanwhile, before
|
||||
* the trace decides whether it must watch an uncaught throw itself. Without the inspect commands'
|
||||
* lock, which one of them can hold for seconds while the caller is java-debug's event thread or
|
||||
* the trace's worker; the trace has stopped silencing, so no arm can be silencing meanwhile.
|
||||
*/
|
||||
static void traceEnded(VirtualMachine vm) {
|
||||
ExceptionBreakpoints state;
|
||||
synchronized (VMS) {
|
||||
state = VMS.get(vm);
|
||||
}
|
||||
if (state != null) state.applyDeferred();
|
||||
}
|
||||
|
||||
/** Whether {@code r} reports every throw of its type, for a trace deciding if it must watch one itself. */
|
||||
static boolean coversWholeType(EventRequest r) {
|
||||
return !(r.getProperty(PROPERTY) instanceof Spec spec) || !spec.hasClassFilters();
|
||||
}
|
||||
|
||||
/**
|
||||
* What a request for {@code spec} on a type with the superclasses {@code supers} must still report:
|
||||
* not what java-debug's own all-exception filters report, nor what an enabled breakpoint without
|
||||
* class filters reports already: one on a superclass, or on the same class when it comes earlier or
|
||||
* {@code spec} has filters. Two breakpoints with class filters can still both report one throw.
|
||||
*/
|
||||
static Flags uncovered(Spec spec, List<String> supers, boolean javaDebugCaught, boolean javaDebugUncaught, List<Spec> all) {
|
||||
boolean caught = spec.caught() && !javaDebugCaught;
|
||||
boolean uncaught = spec.uncaught() && !javaDebugUncaught;
|
||||
boolean earlier = true;
|
||||
for (Spec other : all) {
|
||||
if (other == spec) {
|
||||
earlier = false;
|
||||
continue;
|
||||
}
|
||||
if (!other.enabled() || other.hasClassFilters()) continue;
|
||||
boolean twin = other.className().equals(spec.className()) && (earlier || spec.hasClassFilters());
|
||||
if (twin || supers.contains(other.className())) {
|
||||
caught &= !other.caught();
|
||||
uncaught &= !other.uncaught();
|
||||
}
|
||||
}
|
||||
return new Flags(caught, uncaught);
|
||||
}
|
||||
|
||||
private synchronized List<Map<String, Object>> replace(List<Spec> next) throws Failure, ConnectedVms.Unsupported {
|
||||
subscribe();
|
||||
if (StreamCommand.silencing(vm)) {
|
||||
deferred = next;
|
||||
return states(next, "deferred");
|
||||
}
|
||||
deferred = null;
|
||||
return apply(next);
|
||||
}
|
||||
|
||||
private synchronized void applyDeferred() {
|
||||
List<Spec> next = deferred;
|
||||
if (next == null || StreamCommand.silencing(vm)) return;
|
||||
deferred = null;
|
||||
try {
|
||||
apply(next);
|
||||
} catch (VMDisconnectedException e) {
|
||||
// nothing left to arm
|
||||
}
|
||||
}
|
||||
|
||||
private void subscribe() throws Failure, ConnectedVms.Unsupported {
|
||||
if (subscription != null) return;
|
||||
JavaDebugSessions.Hub hub = JavaDebugSessions.of(vm)
|
||||
.orElseThrow(() -> new Failure("noSession", "java-debug registered no session for this VM (hotCodeReplace is never?)"));
|
||||
subscription = hub.subscribe(this::onEvent, e -> {
|
||||
// A failing listener only costs later class loads their requests.
|
||||
});
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> apply(List<Spec> next) {
|
||||
EventRequestManager erm = vm.eventRequestManager();
|
||||
List<EventRequest> own = new ArrayList<>();
|
||||
for (EventRequest r : erm.exceptionRequests()) if (r.getProperty(PROPERTY) != null) own.add(r);
|
||||
for (EventRequest r : erm.classPrepareRequests()) if (r.getProperty(PROPERTY) != null) own.add(r);
|
||||
erm.deleteEventRequests(own);
|
||||
specs = next;
|
||||
javaDebugCaught = false;
|
||||
javaDebugUncaught = false;
|
||||
for (ExceptionRequest r : erm.exceptionRequests()) {
|
||||
if (r.isEnabled() && r.exception() == null && r.getProperty(Silencer.OWN_PROPERTY) == null) {
|
||||
javaDebugCaught |= r.notifyCaught();
|
||||
javaDebugUncaught |= r.notifyUncaught();
|
||||
}
|
||||
}
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Spec spec : next) {
|
||||
if (!spec.enabled() || (!spec.caught() && !spec.uncaught())) {
|
||||
out.add(state(spec, "disabled"));
|
||||
continue;
|
||||
}
|
||||
// A class loaded later, or by another class loader, gets its request when it is prepared.
|
||||
ClassPrepareRequest prepare = erm.createClassPrepareRequest();
|
||||
prepare.addClassFilter(spec.className());
|
||||
prepare.putProperty(PROPERTY, spec);
|
||||
prepare.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
|
||||
prepare.enable();
|
||||
List<ReferenceType> loaded = vm.classesByName(spec.className());
|
||||
for (ReferenceType type : loaded) arm(spec, type);
|
||||
out.add(state(spec, loaded.isEmpty() ? "pending" : "armed"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private void arm(Spec spec, ReferenceType type) {
|
||||
Flags flags = uncovered(spec, superclasses(type), javaDebugCaught, javaDebugUncaught, specs);
|
||||
if (flags.none()) return;
|
||||
ExceptionRequest r = vm.eventRequestManager().createExceptionRequest(type, flags.caught(), flags.uncaught());
|
||||
for (String pattern : spec.classFilters()) r.addClassFilter(pattern);
|
||||
for (String pattern : spec.classExclusionFilters()) r.addClassExclusionFilter(pattern);
|
||||
r.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
|
||||
r.putProperty(PROPERTY, spec);
|
||||
r.enable();
|
||||
}
|
||||
|
||||
/** java-debug's event thread: the class-loading thread waits until this returns. */
|
||||
private synchronized void onEvent(JavaDebugSessions.HubEvent e) throws IllegalAccessException {
|
||||
Event event = e.event();
|
||||
if (!(event instanceof ClassPrepareEvent prepared) || !(event.request() instanceof ClassPrepareRequest request)) return;
|
||||
if (!(request.getProperty(PROPERTY) instanceof Spec spec) || !specs.contains(spec)) return;
|
||||
// A request made now would be on inside the trace: the whole list is applied again after it.
|
||||
if (StreamCommand.silencing(vm)) {
|
||||
if (deferred == null) deferred = specs;
|
||||
return;
|
||||
}
|
||||
arm(spec, prepared.referenceType());
|
||||
}
|
||||
|
||||
private static List<String> superclasses(ReferenceType type) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (ClassType t = type instanceof ClassType c ? c.superclass() : null; t != null; t = t.superclass()) out.add(t.name());
|
||||
return out;
|
||||
}
|
||||
|
||||
private synchronized void close() {
|
||||
if (subscription != null) subscription.close();
|
||||
subscription = null;
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> states(List<Spec> specs, String state) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Spec spec : specs) out.add(state(spec, spec.enabled() ? state : "disabled"));
|
||||
return Collections.unmodifiableList(out);
|
||||
}
|
||||
|
||||
private static Map<String, Object> state(Spec spec, String state) {
|
||||
return Values.json("id", spec.id(), "state", state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package ai.openidea.jvminspect;
|
||||
|
||||
import ai.openidea.jvminspect.InspectCommand.Failure;
|
||||
import ai.openidea.jvminspect.VmSelector.Target;
|
||||
import ai.openidea.jvminspect.VmSelector.VmInfo;
|
||||
import com.sun.jdi.VMDisconnectedException;
|
||||
import com.sun.jdi.VirtualMachine;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
|
||||
/**
|
||||
* {@code openidea.jvm.exceptions.set [target, {breakpoints}]}: the VM's exception breakpoints on a
|
||||
* chosen class (see {@link ExceptionBreakpoints}). Replies have the shape of {@link InspectCommand}'s.
|
||||
*/
|
||||
public final class ExceptionCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) {
|
||||
try {
|
||||
List<VmInfo> vms = InspectCommand.connected();
|
||||
Set<VirtualMachine> live = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
for (VmInfo v : vms) live.add(v.vm());
|
||||
ExceptionBreakpoints.forgetGone(live);
|
||||
VirtualMachine vm = InspectCommand.select(vms, Target.of(arguments.get(0)));
|
||||
List<ExceptionBreakpoints.Spec> specs = new ArrayList<>();
|
||||
Object list = ((Map<?, ?>) arguments.get(1)).get("breakpoints");
|
||||
if (list instanceof List<?> items) {
|
||||
for (Object item : items) specs.add(ExceptionBreakpoints.Spec.of(item));
|
||||
}
|
||||
return InspectCommand.ok(ExceptionBreakpoints.set(vm, specs));
|
||||
} catch (Failure e) {
|
||||
return InspectCommand.error(e.code, e.getMessage());
|
||||
} catch (ConnectedVms.Unsupported e) {
|
||||
return InspectCommand.error("unsupported", e.getMessage());
|
||||
} catch (org.eclipse.jdi.TimeoutException e) {
|
||||
return InspectCommand.error("timedOut", String.valueOf(e.getMessage()));
|
||||
} catch (VMDisconnectedException e) {
|
||||
return InspectCommand.error("vmNotFound", "the VM disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -550,15 +550,16 @@ final class RealRunTrace {
|
||||
* 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.
|
||||
* exception event as a stop. Not when an enabled request of java-debug's, or an exception breakpoint
|
||||
* without class filters, 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)) {
|
||||
if (r.isEnabled() && r.notifyUncaught() && r.getProperty(Silencer.OWN_PROPERTY) == null && covers(r.exception(), type)
|
||||
&& ExceptionBreakpoints.coversWholeType(r)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -789,6 +790,17 @@ final class RealRunTrace {
|
||||
}
|
||||
}
|
||||
}
|
||||
ExceptionBreakpoints.traceEnded(vm);
|
||||
}
|
||||
|
||||
/** Some of the user's breakpoints are switched off for the trace. */
|
||||
boolean silencing() {
|
||||
synchronized (silenceLock) {
|
||||
for (Silencer s : silencers) {
|
||||
if (s.size() > 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -150,6 +150,15 @@ public final class StreamCommand implements IDelegateCommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** The VM's trace has the user's breakpoints switched off. */
|
||||
static boolean silencing(VirtualMachine vm) {
|
||||
RealRunTrace trace;
|
||||
synchronized (TRACES) {
|
||||
trace = TRACES.get(vm);
|
||||
}
|
||||
return trace != null && trace.silencing();
|
||||
}
|
||||
|
||||
private static RealRunTrace trace(VirtualMachine vm, Map<?, ?> args) throws Failure {
|
||||
long id = number(args, "traceId").longValue();
|
||||
synchronized (TRACES) {
|
||||
|
||||
@@ -45,6 +45,9 @@ public final class SelfTest {
|
||||
sessions_found_by_vm();
|
||||
sessions_missing_field_is_unsupported();
|
||||
hub_listener_parks_and_failures_are_swallowed();
|
||||
exception_spec_parsed_from_gson_json();
|
||||
exception_flags_leave_out_what_another_request_reports();
|
||||
exception_request_with_class_filters_covers_no_whole_type();
|
||||
}
|
||||
|
||||
/** Stands in for java-debug's provider: its manager has no {@code connectedVMs}. */
|
||||
@@ -353,6 +356,70 @@ public final class SelfTest {
|
||||
pass("plan_parsed_from_gson_json");
|
||||
}
|
||||
|
||||
static void exception_spec_parsed_from_gson_json() {
|
||||
Map<String, Object> json = new LinkedHashMap<>();
|
||||
json.put("id", "b1");
|
||||
json.put("className", "java.lang.IllegalStateException");
|
||||
json.put("caught", true);
|
||||
json.put("uncaught", false);
|
||||
json.put("enabled", true);
|
||||
json.put("classFilters", List.of("com.acme.*"));
|
||||
ExceptionBreakpoints.Spec spec = ExceptionBreakpoints.Spec.of(json);
|
||||
check(spec.id().equals("b1") && spec.className().equals("java.lang.IllegalStateException"), "id and class: " + spec);
|
||||
check(spec.caught() && !spec.uncaught() && spec.enabled(), "flags: " + spec);
|
||||
check(spec.classFilters().equals(List.of("com.acme.*")) && spec.classExclusionFilters().isEmpty(), "filters: " + spec);
|
||||
check(spec.hasClassFilters(), "a spec with an include pattern has class filters");
|
||||
json.remove("className");
|
||||
try {
|
||||
ExceptionBreakpoints.Spec.of(json);
|
||||
throw new AssertionError("a spec without a class must be rejected");
|
||||
} catch (IllegalArgumentException e) {
|
||||
check(e.getMessage().contains("className"), "detail names the member: " + e.getMessage());
|
||||
}
|
||||
pass("exception_spec_parsed_from_gson_json");
|
||||
}
|
||||
|
||||
static void exception_flags_leave_out_what_another_request_reports() {
|
||||
ExceptionBreakpoints.Spec ise = spec("ise", "java.lang.IllegalStateException", true, true, true, List.of());
|
||||
List<String> iseSupers = List.of("java.lang.RuntimeException", "java.lang.Exception", "java.lang.Throwable", "java.lang.Object");
|
||||
ExceptionBreakpoints.Flags all = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(ise));
|
||||
check(all.caught() && all.uncaught(), "nothing else reports it: both flags stay: " + all);
|
||||
ExceptionBreakpoints.Flags anyCaught = ExceptionBreakpoints.uncovered(ise, iseSupers, true, false, List.of(ise));
|
||||
check(!anyCaught.caught() && anyCaught.uncaught(), "java-debug's caught filter reports every caught throw: " + anyCaught);
|
||||
check(ExceptionBreakpoints.uncovered(ise, iseSupers, true, true, List.of(ise)).none(), "both java-debug filters: no request");
|
||||
ExceptionBreakpoints.Spec runtime = spec("rte", "java.lang.RuntimeException", true, false, true, List.of());
|
||||
ExceptionBreakpoints.Flags bySuper = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(runtime, ise));
|
||||
check(!bySuper.caught() && bySuper.uncaught(), "a breakpoint on a superclass reports the caught throws: " + bySuper);
|
||||
ExceptionBreakpoints.Spec filtered = spec("f", "java.lang.RuntimeException", true, true, true, List.of("com.acme.*"));
|
||||
ExceptionBreakpoints.Spec off = spec("off", "java.lang.RuntimeException", true, true, false, List.of());
|
||||
ExceptionBreakpoints.Flags narrow = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(filtered, off, ise));
|
||||
check(narrow.caught() && narrow.uncaught(), "a filtered or disabled superclass breakpoint covers nothing: " + narrow);
|
||||
ExceptionBreakpoints.Spec twin = spec("twin", "java.lang.IllegalStateException", true, true, true, List.of());
|
||||
check(ExceptionBreakpoints.uncovered(twin, iseSupers, false, false, List.of(ise, twin)).none(), "the later of two equal breakpoints adds nothing");
|
||||
ExceptionBreakpoints.Flags first = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(ise, twin));
|
||||
check(first.caught() && first.uncaught(), "the earlier of two equal breakpoints keeps its flags: " + first);
|
||||
ExceptionBreakpoints.Spec filteredIse = spec("fi", "java.lang.IllegalStateException", true, true, true, List.of("com.acme.*"));
|
||||
check(ExceptionBreakpoints.uncovered(filteredIse, iseSupers, false, false, List.of(filteredIse, twin)).none(),
|
||||
"an unfiltered breakpoint on the same class covers a filtered one before it");
|
||||
pass("exception_flags_leave_out_what_another_request_reports");
|
||||
}
|
||||
|
||||
static void exception_request_with_class_filters_covers_no_whole_type() {
|
||||
EventRequest plain = request(ExceptionRequest.class, true, false);
|
||||
plain.putProperty(ExceptionBreakpoints.PROPERTY, spec("a", "java.lang.RuntimeException", true, true, true, List.of()));
|
||||
EventRequest filtered = request(ExceptionRequest.class, true, false);
|
||||
filtered.putProperty(ExceptionBreakpoints.PROPERTY, spec("b", "java.lang.RuntimeException", true, true, true, List.of("com.acme.*")));
|
||||
EventRequest javaDebugs = request(ExceptionRequest.class, true, false);
|
||||
check(ExceptionBreakpoints.coversWholeType(plain), "an exception breakpoint without filters covers its type");
|
||||
check(!ExceptionBreakpoints.coversWholeType(filtered), "one with class filters may miss a throw");
|
||||
check(ExceptionBreakpoints.coversWholeType(javaDebugs), "java-debug's own requests have no filters the app sets");
|
||||
pass("exception_request_with_class_filters_covers_no_whole_type");
|
||||
}
|
||||
|
||||
private static ExceptionBreakpoints.Spec spec(String id, String type, boolean caught, boolean uncaught, boolean enabled, List<String> include) {
|
||||
return new ExceptionBreakpoints.Spec(id, type, caught, uncaught, enabled, include, List.of());
|
||||
}
|
||||
|
||||
static void sessions_found_by_vm() throws Exception {
|
||||
Object vmA = new Object();
|
||||
Object vmB = new Object();
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Drive the exception breakpoint command inside a real JDT LS with java-debug.
|
||||
|
||||
Usage: python3 -I exceptions.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-<v>.jar \
|
||||
[--bundle /path/to/openidea-jvm-inspect.jar]
|
||||
|
||||
JDT LS and the debuggees run on the `java` on PATH (JDK 25 for 1.63.0). The breakpoints are set the
|
||||
way ide-dap sets them: after `initialized`, `setExceptionBreakpoints`, then this command, then
|
||||
`configurationDone`, and the command again after every later `setExceptionBreakpoints`. Prints
|
||||
OK/FAIL per check.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
sys.path.append(str(pathlib.Path(__file__).resolve().parent))
|
||||
sys.dont_write_bytecode = True # no __pycache__ in the source tree
|
||||
from jdtls_harness import check, debug_session, finish, free_port, kill, report, start_jdtls, stop_jdtls, wait_ready # noqa: E402
|
||||
|
||||
COMMAND = 'openidea.jvm.exceptions.set'
|
||||
# `// @name` names a line for `line('name')`.
|
||||
PROGRAM = '''public class Exc {
|
||||
static class Lazy { static void boom() { throw new Boom("lazy"); } } // @boom
|
||||
static class Boom extends RuntimeException { Boom(String m) { super("boom: " + m); } } // @message
|
||||
public static void main(String[] a) throws Exception {
|
||||
try { throw new IllegalStateException("first line"); } catch (IllegalStateException e) { } // @first
|
||||
try { Integer.parseInt("x"); } catch (NumberFormatException e) { }
|
||||
try { Lazy.boom(); } catch (Boom e) { }
|
||||
try { Lazy.boom(); } catch (Boom e) { }
|
||||
try { Filtered.run(); } catch (UnsupportedOperationException e) { }
|
||||
try { throw new IllegalStateException("second"); } catch (IllegalStateException e) { } // @second
|
||||
try { Filtered.run(); } catch (UnsupportedOperationException e) { }
|
||||
try { throw new IllegalStateException("third"); } catch (IllegalStateException e) { } // @third
|
||||
throw new IllegalArgumentException("uncaught"); // @uncaught
|
||||
}
|
||||
}
|
||||
class Filtered { static void run() { throw new UnsupportedOperationException("filtered"); } } // @filtered
|
||||
'''
|
||||
|
||||
args = sys.argv[1:]
|
||||
bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-jvm-inspect.jar'
|
||||
if '--bundle' in args:
|
||||
i = args.index('--bundle')
|
||||
bundle = pathlib.Path(args[i + 1]).resolve()
|
||||
del args[i:i + 2]
|
||||
home, java_debug = (pathlib.Path(a).resolve() for a in args[:2])
|
||||
# resolved: on macOS the temp dir is under the /var symlink, and JDT LS matches canonical URIs
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-jvm-exceptions-')).resolve()
|
||||
project = work / 'project'
|
||||
(project / 'src').mkdir(parents=True)
|
||||
source = project / 'src' / 'Exc.java'
|
||||
source.write_text(PROGRAM)
|
||||
classes = work / 'classes'
|
||||
subprocess.run(['javac', '-g', '-d', str(classes), str(source)], check=True)
|
||||
jdtls = lsp = None
|
||||
jvms, launched = [], []
|
||||
|
||||
|
||||
def line(name):
|
||||
return next(i for i, t in enumerate(PROGRAM.splitlines(), 1) if t.rstrip().endswith('// @' + name))
|
||||
|
||||
|
||||
def bp(id, class_name, caught=True, uncaught=True, enabled=True, include=(), exclude=()):
|
||||
return {'id': id, 'className': class_name, 'caught': caught, 'uncaught': uncaught, 'enabled': enabled,
|
||||
'classFilters': list(include), 'classExclusionFilters': list(exclude)}
|
||||
|
||||
|
||||
def arm(target, *breakpoints):
|
||||
reply = lsp.command(COMMAND, target, {'breakpoints': list(breakpoints)})
|
||||
if 'ok' not in reply:
|
||||
raise AssertionError(f'{COMMAND}: {reply}')
|
||||
return {s['id']: s['state'] for s in reply['ok']}
|
||||
|
||||
|
||||
def stop(d, what, timeout=30):
|
||||
e = d.wait_event(lambda e: e['event'] in ('stopped', 'terminated'), timeout, what)
|
||||
if e['event'] == 'terminated':
|
||||
raise AssertionError(f'{what}: the debuggee terminated')
|
||||
thread = e['body']['threadId']
|
||||
frames = d.request('stackTrace', {'threadId': thread})['body']['stackFrames']
|
||||
top = frames[0] if frames else {}
|
||||
info = d.request('exceptionInfo', {'threadId': thread}).get('body', {})
|
||||
return e['body'], thread, top, info
|
||||
|
||||
|
||||
def no_more_stops(d, seconds=2.0):
|
||||
try:
|
||||
d.wait_event(lambda e: e['event'] == 'stopped', seconds, 'stopped')
|
||||
return False
|
||||
except TimeoutError:
|
||||
return True
|
||||
|
||||
|
||||
def expect(d, name, reason_line, exception, what):
|
||||
"""The next stop is a java-debug exception stop at `reason_line` for `exception`, and the only one."""
|
||||
body, thread, top, info = stop(d, what)
|
||||
check(f'{name}: {exception} stops at line {reason_line}',
|
||||
body['reason'] == 'exception' and top['line'] == reason_line and info['exceptionId'] == exception,
|
||||
(body, top.get('name'), top.get('line'), info))
|
||||
check(f'{name}: one stopped event', no_more_stops(d))
|
||||
return thread, info
|
||||
|
||||
|
||||
def configure(d, target, *breakpoints, filters=()):
|
||||
d.wait_event(lambda e: e['event'] == 'initialized', 60, 'initialized')
|
||||
d.request('setExceptionBreakpoints', {'filters': list(filters)})
|
||||
states = arm(target, *breakpoints)
|
||||
d.request('configurationDone')
|
||||
return states
|
||||
|
||||
|
||||
def launch_case(project_name, classpaths):
|
||||
d = debug_session(lsp, 'openidea-jvm-exceptions')
|
||||
d.start('launch', {'mainClass': 'Exc', 'projectName': project_name, 'modulePaths': [], 'classPaths': classpaths,
|
||||
'cwd': str(project), 'console': 'internalConsole', 'shortenCommandLine': 'none'})
|
||||
pid = d.wait_event(lambda e: e['event'] == 'processid', 60, 'processid')['body']['processId']
|
||||
launched.append(pid)
|
||||
target = {'pid': pid, 'host': None, 'port': None, 'generation': 0}
|
||||
exc_filter = 'Exc'
|
||||
states = configure(d, target,
|
||||
bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]),
|
||||
bp('nfe', 'java.lang.NumberFormatException', enabled=False),
|
||||
bp('boom', 'Exc$Boom'),
|
||||
bp('uoe', 'java.lang.UnsupportedOperationException', exclude=['Filtered']),
|
||||
bp('iae', 'java.lang.IllegalArgumentException', caught=False))
|
||||
print(' states before configurationDone:', json.dumps(states), flush=True)
|
||||
# The JDK may have loaded a java.lang class before main; Exc$Boom is loaded by `Lazy.boom()` only.
|
||||
check('launch: states before the program runs', states['nfe'] == 'disabled' and states['boom'] == 'pending'
|
||||
and all(states[k] in ('pending', 'armed') for k in ('ise', 'uoe', 'iae')), states)
|
||||
thread, _ = expect(d, 'launch start-up', line('first'), 'java.lang.IllegalStateException', 'first line')
|
||||
|
||||
# java-debug re-applying its filters deletes every exception request; the client arms again.
|
||||
d.request('setExceptionBreakpoints', {'filters': []})
|
||||
states = arm(target, bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]),
|
||||
bp('nfe', 'java.lang.NumberFormatException', enabled=False), bp('boom', 'Exc$Boom'),
|
||||
bp('uoe', 'java.lang.UnsupportedOperationException', exclude=['Filtered']),
|
||||
bp('iae', 'java.lang.IllegalArgumentException', caught=False))
|
||||
check('launch: re-armed after setExceptionBreakpoints', states['ise'] == 'armed' and states['boom'] == 'pending', states)
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch lazily loaded', line('boom'), 'Exc$Boom', 'boom')
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch loaded class, second throw', line('boom'), 'Exc$Boom', 'boom again')
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch class filter', line('second'), 'java.lang.IllegalStateException', 'second (UOE excluded in Filtered)')
|
||||
|
||||
# A breakpoint on the superclass and the ISE one both report the caught `third`: one stop.
|
||||
rte = bp('rte', 'java.lang.RuntimeException', uncaught=False)
|
||||
states = arm(target, bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]), rte)
|
||||
check('launch: superclass breakpoint armed', states == {'ise': 'armed', 'rte': 'armed'}, states)
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch superclass', line('filtered'), 'java.lang.UnsupportedOperationException', 'UOE by RuntimeException')
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch overlapping own breakpoints', line('third'), 'java.lang.IllegalStateException', 'third')
|
||||
|
||||
# java-debug's own "Uncaught Exceptions" and the IAE breakpoint both report the last throw: one stop.
|
||||
d.request('setExceptionBreakpoints', {'filters': ['uncaught']})
|
||||
states = arm(target, bp('iae', 'java.lang.IllegalArgumentException', caught=False))
|
||||
check('launch: covered by java-debug filter is still armed', states == {'iae': 'armed'}, states)
|
||||
d.request('continue', {'threadId': thread})
|
||||
thread, _ = expect(d, 'launch overlapping java-debug filter', line('uncaught'), 'java.lang.IllegalArgumentException', 'uncaught')
|
||||
d.request('continue', {'threadId': thread})
|
||||
d.wait_event(lambda e: e['event'] in ('terminated', 'exited'), 30, 'end')
|
||||
d.request('disconnect', {'terminateDebuggee': True}, 20)
|
||||
|
||||
|
||||
def hot_swap_case(project_name, classpaths):
|
||||
"""Hot swap of the exception class itself while its request is on it. Last: it edits the source."""
|
||||
d = debug_session(lsp, 'openidea-jvm-exceptions')
|
||||
d.start('launch', {'mainClass': 'Exc', 'projectName': project_name, 'modulePaths': [], 'classPaths': classpaths,
|
||||
'cwd': str(project), 'console': 'internalConsole', 'shortenCommandLine': 'none'})
|
||||
pid = d.wait_event(lambda e: e['event'] == 'processid', 60, 'processid')['body']['processId']
|
||||
launched.append(pid)
|
||||
target = {'pid': pid, 'host': None, 'port': None, 'generation': 0}
|
||||
configure(d, target, bp('boom', 'Exc$Boom'))
|
||||
thread, _ = expect(d, 'hot swap: before', line('boom'), 'Exc$Boom', 'boom')
|
||||
text = PROGRAM.replace('"boom: "', '"BOOM: "')
|
||||
lsp.notify('textDocument/didChange', {'textDocument': {'uri': source.as_uri(), 'version': 2},
|
||||
'contentChanges': [{'text': text}]})
|
||||
source.write_text(text)
|
||||
lsp.notify('textDocument/didSave', {'textDocument': {'uri': source.as_uri()}, 'text': text})
|
||||
lsp.request('java/buildWorkspace', False, 120)
|
||||
# What the app's Reload Changed Classes sends (DebugManager::redefine_classes).
|
||||
r = d.request('redefineClasses', {}, 60)
|
||||
check('hot swap: java-debug redefines Exc$Boom', r['success'] and 'Exc$Boom' in r.get('body', {}).get('changedClasses', []), r)
|
||||
# java-debug pops the frames of redefined classes and re-enters them (a `step` stop), so the throw runs again.
|
||||
swapped = []
|
||||
for _ in range(4):
|
||||
d.request('continue', {'threadId': thread})
|
||||
try:
|
||||
body, thread, top, info = stop(d, 'after hot swap', 10)
|
||||
except (TimeoutError, AssertionError):
|
||||
break
|
||||
print(' after hot swap:', body['reason'], top.get('name'), top.get('line'), info.get('description'), flush=True)
|
||||
if body['reason'] == 'exception' and info.get('exceptionId') == 'Exc$Boom':
|
||||
swapped.append(info.get('description', ''))
|
||||
break
|
||||
check('hot swap: the Exc$Boom breakpoint still stops, in the new constructor',
|
||||
bool(swapped) and all('BOOM: lazy' in s for s in swapped), swapped)
|
||||
d.request('disconnect', {'terminateDebuggee': True}, 20)
|
||||
|
||||
|
||||
def attach_case(project_name):
|
||||
port = free_port()
|
||||
p = subprocess.Popen(['java', f'-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{port}',
|
||||
'-cp', str(classes), 'Exc'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
jvms.append(p)
|
||||
p.stdout.readline() # "Listening for transport dt_socket ..."
|
||||
threading.Thread(target=lambda: [None for _ in p.stdout], daemon=True).start()
|
||||
d = debug_session(lsp, 'openidea-jvm-exceptions')
|
||||
d.start('attach', {'hostName': '127.0.0.1', 'port': port, 'timeout': 30000, 'projectName': project_name})
|
||||
target = {'pid': None, 'host': 'localhost', 'port': port, 'generation': 0}
|
||||
states = configure(d, target, bp('ise', 'java.lang.IllegalStateException', uncaught=False))
|
||||
check('attach: pending before the program runs', states == {'ise': 'pending'}, states)
|
||||
expect(d, 'attach start-up', line('first'), 'java.lang.IllegalStateException', 'first line')
|
||||
d.request('disconnect', {'terminateDebuggee': True}, 20)
|
||||
|
||||
|
||||
try:
|
||||
wanted = [COMMAND, 'vscode.java.startDebugSession']
|
||||
jdtls, lsp, registered = start_jdtls(home, work, project, [java_debug, bundle], wanted)
|
||||
if check('JDT LS registers the exception command and java-debug', all(c in registered for c in wanted), registered):
|
||||
wait_ready(lsp)
|
||||
lsp.notify('textDocument/didOpen', {'textDocument': {'uri': source.as_uri(), 'languageId': 'java', 'version': 1,
|
||||
'text': PROGRAM}})
|
||||
lsp.command('vscode.java.updateDebugSettings', json.dumps({'hotCodeReplace': 'auto', 'logLevel': 'WARNING'}))
|
||||
for _ in range(30):
|
||||
main = lsp.command('vscode.java.resolveMainClass', project.as_uri())
|
||||
if main:
|
||||
break
|
||||
time.sleep(2)
|
||||
project_name = main[0].get('projectName')
|
||||
_, classpaths = lsp.command('vscode.java.resolveClasspath', 'Exc', project_name)
|
||||
for case in (lambda: launch_case(project_name, classpaths), lambda: attach_case(project_name),
|
||||
lambda: hot_swap_case(project_name, classpaths)):
|
||||
try:
|
||||
case()
|
||||
except Exception as e:
|
||||
report('FAIL', 'case', repr(e))
|
||||
except Exception as e:
|
||||
report('FAIL', 'harness', repr(e))
|
||||
finally:
|
||||
kill(jvms, launched)
|
||||
if lsp:
|
||||
stop_jdtls(jdtls, lsp)
|
||||
sys.exit(finish(work))
|
||||
@@ -1095,6 +1095,61 @@ def real_run_uncaught_throw_user_filter():
|
||||
dbg.end()
|
||||
|
||||
|
||||
def exception_breakpoints(dbg, *breakpoints):
|
||||
"""`openidea.jvm.exceptions.set`; returns breakpoint id → state."""
|
||||
return {s['id']: s['state'] for s in ok(lsp.command('openidea.jvm.exceptions.set', dbg.target, {'breakpoints': list(breakpoints)}))}
|
||||
|
||||
|
||||
def exception_breakpoint(id, class_name, exclude=()):
|
||||
return {'id': id, 'className': class_name, 'caught': True, 'uncaught': True, 'enabled': True,
|
||||
'classFilters': [], 'classExclusionFilters': list(exclude)}
|
||||
|
||||
|
||||
@case
|
||||
def real_run_uncaught_throw_exception_breakpoint():
|
||||
# A caught+uncaught breakpoint on the thrown class: silenced while the terminal runs (a stop inside
|
||||
# its invoke would hang the trace), then the uncaught throw stops once, not once per request.
|
||||
dbg = real('U')
|
||||
try:
|
||||
states = exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException'))
|
||||
check('U-class: armed or pending', states['ae'] in ('armed', 'pending'), states)
|
||||
trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',))
|
||||
check('U-class: parked after the lambda threw', state['state'] == 'parked', state)
|
||||
uncaught_stop(dbg, 'U-class', trace, 'java.lang.ArithmeticException')
|
||||
finally:
|
||||
dbg.end()
|
||||
|
||||
|
||||
@case
|
||||
def real_run_uncaught_throw_filtered_exception_breakpoint():
|
||||
# The breakpoint's class filter leaves out where the lambda throws: the trace still watches the throw.
|
||||
dbg = real('U')
|
||||
try:
|
||||
exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException', exclude=['Real']))
|
||||
trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',))
|
||||
check('U-class-filtered: parked after the lambda threw', state['state'] == 'parked', state)
|
||||
uncaught_stop(dbg, 'U-class-filtered', trace, 'java.lang.ArithmeticException')
|
||||
finally:
|
||||
dbg.end()
|
||||
|
||||
|
||||
@case
|
||||
def exception_breakpoints_set_during_a_trace_wait_for_its_end():
|
||||
# Set while the trace silences breakpoints: nothing is armed inside it; the list is applied once the
|
||||
# breakpoints are back on, before the trace decides whether to watch the uncaught throw itself.
|
||||
dbg = real('U')
|
||||
try:
|
||||
trace = ok(arm(dbg, at='U', steps=(spec('map', 1),), step_kinds=('sync',)))['traceId']
|
||||
states = exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException'))
|
||||
check('U-deferred: deferred while the trace silences', states == {'ae': 'deferred'}, states)
|
||||
resume(dbg)
|
||||
state = wait_until_done(dbg, trace)
|
||||
check('U-deferred: parked after the lambda threw', state['state'] == 'parked', state)
|
||||
uncaught_stop(dbg, 'U-deferred', trace, 'java.lang.ArithmeticException')
|
||||
finally:
|
||||
dbg.end()
|
||||
|
||||
|
||||
@case
|
||||
def real_run_uncaught_abort():
|
||||
dbg = real('Ua')
|
||||
|
||||
Reference in New Issue
Block a user