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/1387.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**A launched Java program's debug port listens on loopback only** — in launch mode the JDI bridge started the JVM with a JDWP address of `*:<port>`, which listens on every network interface, and then attached through `localhost`. The JVM is now started with `127.0.0.1:<port>` and the bridge attaches to that same address; the bridge's free-port probe binds loopback as well, so nothing the bridge opens listens beyond loopback. Attach mode is unchanged: it connects to the host and port you give it (#1387)
2 changes: 2 additions & 0 deletions docs/java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ If you use a build tool:

JDI bridge spawns the JVM and connects via JDI. The adapter derives `mainClass` from the `program` field in the launch configuration and forwards `classpath`, `vmArgs`, `javaPath`, and the program `args`.

The launched JVM's JDWP debug port listens only on `127.0.0.1`; the bridge connects to that same literal address. Both run on the same machine or inside the same container, so the launch port does not need to be published.

Put the Java-specific keys in `start_debugging`'s `adapterLaunchConfig` — the parameter reserved for adapter-specific overrides — and leave standard DAP keys such as `stopOnEntry` in `dapLaunchArgs`. Both objects are merged into the one launch config the adapter transforms, so either container reaches the bridge; `adapterLaunchConfig` is the documented home (see [tool reference](../tool-reference.md#start_debugging)).

```text
Expand Down
6 changes: 3 additions & 3 deletions packages/adapter-java/java/JdiDapServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -379,15 +379,15 @@ private void handleLaunch(int reqSeq, Map<String, Object> args) throws Exception

// Find a free port for JDWP
int jdwpPort;
try (ServerSocket ss = new ServerSocket(0)) {
try (ServerSocket ss = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
jdwpPort = ss.getLocalPort();
}

// Build java command
String javaCmd = strOr(args, "javaPath", findJava());
List<String> cmdList = new ArrayList<>();
cmdList.add(javaCmd);
cmdList.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:" + jdwpPort);
cmdList.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:" + jdwpPort);

// Add VM args if provided
String vmArgs = str(args, "vmArgs");
Expand Down Expand Up @@ -496,7 +496,7 @@ private void handleLaunch(int reqSeq, Map<String, Object> args) throws Exception
// Attach via JDI
AttachingConnector connector = findAttachConnector();
Map<String, Connector.Argument> connArgs = connector.defaultArguments();
connArgs.get("hostname").setValue("localhost");
connArgs.get("hostname").setValue("127.0.0.1");
connArgs.get("port").setValue(String.valueOf(jdwpPort));

// Retry attach for up to 10 seconds
Expand Down
153 changes: 153 additions & 0 deletions tests/adapters/java/integration/java-launch-loopback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/** The bridge's real launch keeps the debuggee's JDWP endpoint on loopback. */
import { afterAll, 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 type { DebugProtocol } from '@vscode/debugprotocol';
import { TcpDapClient } from '../../../test-utils/helpers/dap-test-client.js';

const ROOT = fileURLToPath(new URL('../../../../', import.meta.url));
const APP = [
'public class LaunchLoopback {',
' public static void main(String[] args) {',
' System.out.println("launch completed");',
' }',
'}',
''
].join('\n');

class StartupExitError extends Error {}

/** End only the child whose handle this test retained. */
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 if another process claims the reserved port before the bridge binds it. */
async function startBridge(work: string): Promise<{ child: ChildProcess; port: number; stderr: () => string }> {
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', [
'-cp', work, 'JdiDapServer', '--port', String(port), '--owner-pid', String(process.pid), '--debug'
], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stdout!.resume();
try {
await new Promise<void>((resolve, reject) => {
const cleanup = (): void => {
clearTimeout(timer);
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(`Bridge exited (${code}): ${stderr}`));
const timer = setTimeout(() => fail(new Error(`Bridge startup timed out: ${stderr}`)), 10_000);
// Keep this reader for the child's lifetime: --debug continues writing
// after readiness, and the launch assertion reads the accumulated log.
child.stderr!.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
if (stderr.includes('JdiDapServer listening on port')) {
cleanup();
resolve();
}
});
child.once('error', fail);
child.once('exit', exited);
});
return { child, port, stderr: () => stderr };
} catch (error) {
await stopChild(child);
if (!(error instanceof StartupExitError) || attempt === 2) throw error;
}
}
throw new Error('Bridge startup attempts exhausted');
}

describe('Java launch JDWP address @requires-java', () => {
let work: string;

beforeAll(() => {
const cache = path.join(ROOT, 'node_modules', '.cache');
fs.mkdirSync(cache, { recursive: true });
work = fs.realpathSync(fs.mkdtempSync(path.join(cache, 'java-launch-loopback-')));
const source = path.join(work, 'LaunchLoopback.java');
fs.writeFileSync(source, APP);
execFileSync('javac', [
'-g', '-d', work,
path.join(ROOT, 'packages', 'adapter-java', 'java', 'JdiDapServer.java'), source
], { windowsHide: true });
}, 30_000);

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

it('launches the JVM with JDWP bound to 127.0.0.1 and connects successfully', async () => {
const client = new TcpDapClient();
let bridge: ChildProcess | undefined;
let connected = false;
try {
const started = await startBridge(work);
bridge = started.child;
await client.connect(started.port);
connected = true;
expect(await client.request('initialize', { adapterID: 'java' })).toMatchObject({ success: true });
const launched = await client.request('launch', {
mainClass: 'LaunchLoopback', classpath: work, cwd: work, stopOnEntry: false
});
expect(launched, started.stderr()).toMatchObject({ success: true });

// HotSpot announces only the port, not the bind address. Inspect the
// real launch's debug log and correlate it with that JVM announcement.
const announcement = (): RegExpExecArray | null => {
for (const frame of client.frames) {
if (frame.type === 'event' && (frame as DebugProtocol.Event).event === 'output') {
const match = /Listening for transport dt_socket at address: (\d+)/.exec(
(frame as DebugProtocol.OutputEvent).body.output
);
if (match) return match;
}
}
return null;
};
await expect.poll(announcement, { timeout: 10_000 }).not.toBeNull();
const command = /Launching: ([^\r\n]+)/.exec(started.stderr())?.[1];
expect(command, started.stderr()).toBeDefined();
const address = /-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=([^\s]+)/.exec(command!)?.[1];
expect(address).toBe(`127.0.0.1:${announcement()![1]}`);

expect(await client.request('configurationDone')).toMatchObject({ success: true });
await client.waitForEvent('terminated');
const stdout = client.frames.filter((frame): frame is DebugProtocol.OutputEvent =>
frame.type === 'event' && (frame as DebugProtocol.Event).event === 'output'
).map(frame => frame.body.output).join('');
expect(stdout).toContain('launch completed');
} finally {
try {
// The bridge owns the target's Process handle; disconnect ends it.
// A failed connection needs no DAP request or request-timeout wait.
if (connected && !client.isClosed && bridge?.exitCode === null && bridge.signalCode === null) {
await client.request('disconnect', undefined, 1_000).catch(() => {});
await client.waitForClose(1_000).catch(() => {});
}
} finally {
try {
client.close();
} finally {
await stopChild(bridge);
}
}
}
}, 30_000);
});
Loading