Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1383.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**A Java step that lands on a line with a breakpoint is announced as one stop** — JDI delivers the step's completion and the breakpoint hit as two events in one event set, and the bridge sent a `stopped` event for each: `step`, then `breakpoint` a millisecond later, for one suspension (49 of 300 `step_over` calls in a loop with one breakpoint line). The bridge now sends one `stopped` per event set. When a set holds both, the stop is reported as `breakpoint`, which is what debugpy and js-debug report for the same step; an exception in the set takes precedence over both. The stop's `allThreadsStopped` now comes from the event set as well: stepping onto a breakpoint with `suspendPolicy: "thread"` reported that one thread had stopped while the JVM had suspended all of them, and the next `continue_execution` then left every other thread suspended (#1383)
26 changes: 20 additions & 6 deletions packages/adapter-java/java/JdiDapServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -1867,6 +1867,7 @@ private void startEventLoop() {
boolean resume = true;

boolean stopped = false; // true once a stopping event (breakpoint/step/exception) is seen
Map<String, Object> stoppedBody = null;

for (Event event : eventSet) {
if (event instanceof BreakpointEvent) {
Expand All @@ -1885,10 +1886,15 @@ private void startEventLoop() {
}

log("Breakpoint hit: " + bpe.location());
boolean allStopped = bpr == null || bpr.suspendPolicy() == EventRequest.SUSPEND_ALL;
// Function breakpoints report their own DAP stop reason
boolean isFnBp = bpr != null && bpr.getProperty("jdi-fnbp-name") != null;
sendStoppedEvent(isFnBp ? "function breakpoint" : "breakpoint", bpe.thread().uniqueID(), allStopped);
// One suspension can contain both step and breakpoint events,
// in either order. A stopping breakpoint takes precedence.
if (stoppedBody == null || "step".equals(stoppedBody.get("reason"))) {
stoppedBody = new HashMap<>();
stoppedBody.put("reason", isFnBp ? "function breakpoint" : "breakpoint");
stoppedBody.put("threadId", bpe.thread().uniqueID());
}
resume = false;
stopped = true;

Expand All @@ -1897,7 +1903,11 @@ private void startEventLoop() {
// Delete the step request (one-shot)
vm.eventRequestManager().deleteEventRequest(se.request());
log("Step completed: " + se.location());
sendStoppedEvent("step", se.thread().uniqueID());
if (stoppedBody == null) {
stoppedBody = new HashMap<>();
stoppedBody.put("reason", "step");
stoppedBody.put("threadId", se.thread().uniqueID());
}
resume = false;
stopped = true;

Expand Down Expand Up @@ -1947,19 +1957,23 @@ private void startEventLoop() {
log("Exception: " + fqcn + " at " + ee.location());
lastException = new ExceptionStop(exObj, ee.thread().uniqueID(), ee.catchLocation() != null);
String message = throwableMessage(exObj);
lastStopAllThreads = true; // exception requests are SUSPEND_ALL
Map<String, Object> body = new HashMap<>();
body.put("reason", "exception");
body.put("threadId", ee.thread().uniqueID());
body.put("text", fqcn);
body.put("description", message != null ? fqcn + ": " + message : fqcn);
body.put("allThreadsStopped", true);
sendEvent("stopped", body);
stoppedBody = body;
resume = false;
stopped = true;
}
}

if (stoppedBody != null) {
boolean allStopped = eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL;
stoppedBody.put("allThreadsStopped", allStopped);
lastStopAllThreads = allStopped;
sendEvent("stopped", stoppedBody);
}
if (resume) {
eventSet.resume();
}
Expand Down
254 changes: 254 additions & 0 deletions tests/adapters/java/integration/java-event-set-stop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
/** A step landing on a breakpoint is one JDI suspension (issue #1383). */
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as settle } from 'node:timers/promises';
import type { DebugProtocol } from '@vscode/debugprotocol';
import { TcpDapClient } from '../../../test-utils/helpers/dap-test-client.js';

const ROOT = fileURLToPath(new URL('../../../../', import.meta.url));
const FIXTURE = [
'public class EventSetStop {',
' public static void main(String[] args) {',
' int n = 1;',
' n++;',
' System.out.println(n);',
' }',
'}',
''
].join('\n');
const FUNCTION_FIXTURE = [
'public class EventSetFunction {',
' public static void main(String[] args) {',
' int n = compute(1);',
' System.out.println(n);',
' }',
' static int compute(int n) {',
' return n + 1;',
' }',
'}',
''
].join('\n');
const THREAD_FIXTURE = [
'import java.util.concurrent.CountDownLatch;',
'public class EventSetThreads {',
' static final CountDownLatch ready = new CountDownLatch(1);',
' static final CountDownLatch release = new CountDownLatch(1);',
' public static void main(String[] args) throws InterruptedException {',
' Thread worker = new Thread(EventSetThreads::work);',
' worker.start();',
' ready.await();',
' int n = 1;',
' release.countDown();',
' worker.join();',
' System.out.println(n);',
' }',
' static void work() {',
' ready.countDown();',
' try { release.await(); } catch (InterruptedException e) { throw new RuntimeException(e); }',
' }',
'}',
''
].join('\n');

class StartupExitError extends Error {}

/** Wait on this child's output, without probing the bridge's single-client socket. */
function announced(child: ChildProcess, pattern: RegExp): Promise<RegExpExecArray> {
return new Promise((resolve, reject) => {
let output = '';
const cleanup = (): void => {
clearTimeout(timer);
child.stdout?.off('data', read);
child.stderr?.off('data', read);
// --debug keeps writing after startup; drain both pipes until exit.
child.stdout?.resume();
child.stderr?.resume();
child.off('error', fail);
child.off('exit', exited);
};
const fail = (error: Error): void => { cleanup(); reject(error); };
const exited = (code: number | null): void => fail(new StartupExitError(`Child exited (${code}): ${output}`));
const read = (chunk: Buffer): void => {
output += chunk.toString();
const match = pattern.exec(output);
if (match) { cleanup(); resolve(match); }
};
const timer = setTimeout(() => fail(new Error(`Child startup timed out: ${output}`)), 10_000);
child.stdout?.on('data', read);
child.stderr?.on('data', read);
child.once('error', fail);
child.once('exit', exited);
});
}

/** Only the retained handle of a child we started may be terminated. */
async function stopChild(child: ChildProcess | undefined): Promise<void> {
if (!child || child.exitCode !== null || child.signalCode !== null) return;
const exited = once(child, 'exit');
child.kill();
await exited;
}

/** Retry a lost port reservation if the bridge exits before announcing readiness. */
async function startBridge(work: string): Promise<{ child: ChildProcess; port: number }> {
for (let attempt = 0; attempt < 3; attempt++) {
const reservation = net.createServer();
reservation.listen(0, '127.0.0.1');
await once(reservation, 'listening');
const port = (reservation.address() as net.AddressInfo).port;
await new Promise<void>((resolve, reject) => reservation.close(error => error ? reject(error) : resolve()));
const child = spawn('java', [
'-Djava.net.preferIPv4Stack=true', '-cp', work, 'JdiDapServer', '--port', String(port), '--debug'
], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
try {
await announced(child, /JdiDapServer listening on port/);
return { child, port };
} catch (error) {
await stopChild(child);
if (!(error instanceof StartupExitError) || attempt === 2) throw error;
}
}
throw new Error('Bridge startup attempts exhausted');
}

/** History stays in TcpDapClient, so collect only frames after this command. */
async function stoppedAfter(client: TcpDapClient, command: string, threadId: number): Promise<DebugProtocol.StoppedEvent> {
const firstFrame = client.frames.length;
expect(await client.request(command, { threadId })).toMatchObject({ success: true });
const stops = (): DebugProtocol.StoppedEvent[] => client.frames.slice(firstFrame).filter(
(message): message is DebugProtocol.StoppedEvent =>
message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped'
);
await expect.poll(() => stops().length, { timeout: 10_000 }).toBeGreaterThan(0);
await settle(200);
expect(stops()).toHaveLength(1);
return stops()[0];
}

async function expectLine(client: TcpDapClient, threadId: number, line: number): Promise<void> {
const stack = await client.request('stackTrace', { threadId }) as DebugProtocol.StackTraceResponse;
expect(stack.success).toBe(true);
expect(stack.body.stackFrames[0].line).toBe(line);
}

describe('One Java stopped event per event set @requires-java', () => {
let work: string;
let client: TcpDapClient;
let bridge: ChildProcess | undefined;
let jvm: ChildProcess | undefined;

beforeAll(() => {
const cache = path.join(ROOT, 'node_modules', '.cache');
fs.mkdirSync(cache, { recursive: true });
work = fs.mkdtempSync(path.join(cache, 'java-event-set-'));
const sources = Object.entries({ EventSetStop: FIXTURE, EventSetFunction: FUNCTION_FIXTURE, EventSetThreads: THREAD_FIXTURE })
.map(([name, text]) => {
const source = path.join(work, `${name}.java`);
fs.writeFileSync(source, text);
return source;
});
execFileSync('javac', [
'-g', '-d', work,
path.join(ROOT, 'packages', 'adapter-java', 'java', 'JdiDapServer.java'), ...sources
], { windowsHide: true });
}, 30_000);

afterEach(async () => {
client?.close();
const results = await Promise.allSettled([stopChild(bridge), stopChild(jvm)]);
bridge = undefined;
jvm = undefined;
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Child cleanup failed');
});

afterAll(() => {
if (work) fs.rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
});

async function attach(
mainClass: string,
breakpoints: Array<{ line: number; condition?: string; suspendPolicy?: string }>,
functionBreakpoints: Array<{ name: string }> = []
): Promise<DebugProtocol.StoppedEvent> {
client = new TcpDapClient();
const started = await startBridge(work);
bridge = started.child;
await client.connect(started.port);
expect(await client.request('initialize', { adapterID: 'java' })).toMatchObject({ success: true });
expect(await client.request('setBreakpoints', {
source: { path: path.join(work, `${mainClass}.java`) }, breakpoints
})).toMatchObject({ success: true });
if (functionBreakpoints.length) {
expect(await client.request('setFunctionBreakpoints', { breakpoints: functionBreakpoints })).toMatchObject({ success: true });
}
jvm = spawn('java', [
'-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0',
'-cp', work, mainClass
], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
const jdwp = await announced(jvm, /Listening for transport dt_socket at address: (\d+)/);
expect(await client.request('attach', { host: '127.0.0.1', port: Number(jdwp[1]) })).toMatchObject({ success: true });
expect(await client.request('configurationDone')).toMatchObject({ success: true });
expect(await client.request('continue', { threadId: 1 })).toMatchObject({ success: true });
const initial = await client.waitForEvent('stopped') as DebugProtocol.StoppedEvent;
expect(initial.body.reason).toBe('breakpoint');
await expectLine(client, initial.body.threadId!, breakpoints[0].line);
return initial;
}

it('next onto a breakpoint emits one breakpoint stop, then next emits one plain step', async () => {
const initial = await attach('EventSetStop', [{ line: 3 }, { line: 4 }]);
const threadId = initial.body.threadId!;
const breakpoint = await stoppedAfter(client, 'next', threadId);
expect(breakpoint.body).toMatchObject({ reason: 'breakpoint', threadId, allThreadsStopped: true });
await expectLine(client, threadId, 4);

const step = await stoppedAfter(client, 'next', threadId);
expect(step.body).toMatchObject({ reason: 'step', threadId, allThreadsStopped: true });
await expectLine(client, threadId, 5);
}, 30_000);

it('next onto a false conditional breakpoint emits exactly one step stop', async () => {
const initial = await attach('EventSetStop', [{ line: 3 }, { line: 4, condition: 'n < 0' }]);
const threadId = initial.body.threadId!;
const step = await stoppedAfter(client, 'next', threadId);
expect(step.body).toMatchObject({ reason: 'step', threadId, allThreadsStopped: true });
await expectLine(client, threadId, 4);
}, 30_000);

it('stepIn onto a function breakpoint emits exactly one function breakpoint stop', async () => {
const initial = await attach('EventSetFunction', [{ line: 3 }], [{ name: 'EventSetFunction.compute' }]);
const threadId = initial.body.threadId!;
const step = await stoppedAfter(client, 'stepIn', threadId);
expect(step.body).toMatchObject({ reason: 'function breakpoint', threadId, allThreadsStopped: true });
await expectLine(client, threadId, 7);
}, 30_000);

it('next onto a thread-policy breakpoint reports all threads stopped and continue finishes both threads', async () => {
const initial = await attach('EventSetThreads', [
{ line: 9, suspendPolicy: 'thread' }, { line: 10, suspendPolicy: 'thread' }
]);
const threadId = initial.body.threadId!;
expect(initial.body.allThreadsStopped).toBe(false);
// Idempotent thread pause seeds lastStopAllThreads=false through a separate
// path, so omitting the event-set bookkeeping update is observable too.
const paused = await stoppedAfter(client, 'pause', threadId);
expect(paused.body).toMatchObject({ reason: 'pause', allThreadsStopped: false });

const step = await stoppedAfter(client, 'next', threadId);
expect(step.body.reason).toBe('breakpoint');
await expectLine(client, threadId, 10);
expect.soft(step.body.allThreadsStopped).toBe(true);
const continued = await client.request('continue', { threadId });
expect(continued.success).toBe(true);
expect.soft(continued.body.allThreadsContinued).toBe(true);
// main releases the worker and joins it. Resuming only main leaves the
// worker suspended forever, so the VM cannot terminate.
await client.waitForEvent('terminated', 3_000);
}, 30_000);
});
Loading