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
33 changes: 28 additions & 5 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,7 @@ or removing a command fails until the table changes in the same commit.
| `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments |
| `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O |
| `debug.adapters.executablePlan` | Say where to look for the program a launch debugs: the user's setting and the adapter's candidate paths |
| `debug.adapters.readAnnouncement` | Read whether one output line of a `tcpAnnounced` adapter announces its endpoint, and accept only a loopback one; reads no process output and opens no socket |
| `debug.transport.policy` | Return the default byte-stream deadlines, queue budgets and the session `initialize` deadline; creates no state |
| `debug.transport.handle` | Apply one platform event to an IDE-to-adapter byte-stream lifecycle and return the effects the platform runs next |
| `debug.transport.release` | Forget the lifecycle of a stopped byte stream once the platform dropped its handles |
Expand Down Expand Up @@ -2384,7 +2385,8 @@ bounded best-effort drain of queued frames (including disconnect) for up to one
second before closing; this is local write completion, not a remote acknowledgement.
Failure and explicit transport abort close immediately. There is no automatic reconnect or request
replay. Proxy/tunnel implementations and plugin `tcpPort` / `tcpAnnounced`
process hosting are not enabled by this API.
process hosting are not enabled by this API; `tcpAnnounced` hosting reads its
endpoint through `debug.adapters.readAnnouncement`.

The `debug.transport.*` commands hold the lifecycle rules of that byte stream
so every platform network layer shares one rule set. They are separate from the
Expand Down Expand Up @@ -4055,9 +4057,27 @@ only `launch: { kind: "backend", function, timeoutMilliseconds }` with empty
`requiredDirectories` and no `resolveParams`: the server's own session asks
the backend with the directories of its start, so resolving the adapter needs
no `workspaceStateDirectory`, `logDirectory` or `temporaryDirectory`. Core validates every declared
`transport`, but a host starts only the transports it implements: the macOS host
runs `stdio` and refuses `tcpPort` and `tcpAnnounced` before starting the
process, with `plugin.launch.unsupportedTransport`.
`transport`, but a host starts only the transports it implements and refuses
the others before starting the process, with `plugin.launch.unsupportedTransport`.

`debug.adapters.readAnnouncement` accepts exactly `{ endpoint, stream, line }`:
the plan's `debugAdapter.endpoint` of a `tcpAnnounced` adapter (`stream`,
`prefix`, `value`), the stream one line of the adapter's output came from
(`stdout` or `stderr`), and that line without its line break. A line on another
stream, or without the prefix, returns `{ status: "none" }`. Otherwise the line
is the announcement: the rest after the prefix's first occurrence, without
surrounding whitespace, returns `{ status: "announced", host, port }` when it is
a port from 1 to 65535 in decimal digits (`value: "port"`, host `127.0.0.1`) or
`host:port` / `[ipv6]:port` with a loopback host (`value: "hostPort"`; host as
written, without brackets). It returns `{ status: "invalid", reason:
"malformed" }` for any other text and `{ status: "invalid", reason:
"notLoopback" }` for a well-formed host that is not `localhost`, 127.0.0.0/8 or
`::1`. An endpoint that is not a valid `tcpAnnounced` endpoint, an unknown
stream or field fails with `invalid_request`. The host feeds the declared
stream to this command from the transport's `discoverEndpoint` effect until an
answer other than `none`, then reports `endpointResolved` for `announced` or
fails with `invalidEndpoint`; the discovery deadline bounds the wait. Cases
live in `rust/fixtures/debug/adapter-announcements-v1.json`.

`debug.adapters.startArguments` accepts `{ manifest, adapterID, request:
"launch" | "attach", facts: { registration: { generation, currentGeneration },
Expand All @@ -4069,7 +4089,10 @@ configuration already sets it. `configuration` is a plugin backend's own DAP
arguments from `lithe/host/debug/start`, as `debug.decodeBackendConfiguration`
returned them; each of its keys replaces the argument of the same name, so the
host sends `arguments` to the adapter unchanged. A `noDebug` or `__` key there is
refused with `plugin.debug.invalidStart` and `field: "configuration.<key>"`. `program` is filled from `target.path`, or from
refused with `plugin.debug.invalidStart` and `field: "configuration.<key>"`. `program` is filled from `target.path`; from the directory
containing `target.path` when the configuration binds it to `target.directory`
(an adapter such as Delve that builds a package; a path without a directory is
`debug.target.invalid` with `field: "target.path"`); or from
`target.executable` (an absolute path the host found) when the configuration
binds it to `target.executable`. Refusals use the `rejected` shape with
`debug.provider.stale`, `debug.request.unsupported`, `debug.runtime.stale`, or
Expand Down
7 changes: 7 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,9 @@ pub enum DebugCommand {
ValidateAdapterEndpoint,
/// Says where to look for the program a launch debugs (`debug.adapters.executablePlan`).
AdaptersExecutablePlan,
/// Reads whether one output line of a `tcpAnnounced` adapter announces its
/// loopback endpoint (`debug.adapters.readAnnouncement`).
AdaptersReadAnnouncement,
/// Returns the default byte-stream deadlines and queue budgets (`debug.transport.policy`).
TransportPolicy,
/// Applies one platform event to a byte-stream lifecycle and returns the effects to run
Expand Down Expand Up @@ -1003,6 +1006,9 @@ impl CoreCommand {
"debug.adapters.executablePlan" => {
Some(Self::Debug(DebugCommand::AdaptersExecutablePlan))
}
"debug.adapters.readAnnouncement" => {
Some(Self::Debug(DebugCommand::AdaptersReadAnnouncement))
}
"debug.transport.policy" => Some(Self::Debug(DebugCommand::TransportPolicy)),
"debug.transport.handle" => Some(Self::Debug(DebugCommand::TransportHandle)),
"debug.transport.release" => Some(Self::Debug(DebugCommand::TransportRelease)),
Expand Down Expand Up @@ -1668,6 +1674,7 @@ mod tests {
"debug.transport.policy",
"debug.transport.handle",
"debug.transport.release",
"debug.adapters.readAnnouncement",
] {
assert!(CoreCommand::parse(command).is_some(), "missing {command}");
}
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ pub(super) fn dispatch(command: DebugCommand, id: Option<String>, payload: Value
Err(error) => CoreResponse::failure(id, error),
}
}
DebugCommand::AdaptersReadAnnouncement => {
match crate::debug::adapters::read_announcement(payload) {
Ok(data) => CoreResponse::success(id, data),
Err(error) => CoreResponse::failure(id, error),
}
}
DebugCommand::TransportPolicy => match crate::debug::transport_policy(payload) {
Ok(data) => CoreResponse::success(id, data),
Err(error) => CoreResponse::failure(id, error),
Expand Down
29 changes: 29 additions & 0 deletions rust/crates/core/src/tests/declarative_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2049,6 +2049,35 @@ fn debug_start_arguments_need_an_absolute_resolved_executable() {
}
}

#[test]
fn debug_start_arguments_bind_program_to_the_directory_of_the_target() {
// The host sends native paths, and the directory depends on the platform.
let (path, directory) = if cfg!(windows) {
(r"C:\work\cmd\app\main.go", r"C:\work\cmd\app")
} else {
("/work/cmd/app/main.go", "/work/cmd/app")
};
let mut manifest = fixture("debug-adapter.plugin.json");
manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"]["program"] =
json!("target.directory");
let launch = lithe_plugin_manifest::debug_start_arguments_command(json!({
"manifest": manifest,
"adapterID": "example",
"request": "launch",
"facts": {
"registration": { "generation": 3, "currentGeneration": 3 },
"target": { "kind": "file", "path": path, "workingDirectory": "/work" },
},
}))
.expect("payload is well formed");
assert_eq!(launch["status"], "ok", "{launch}");
// A package debugger builds every file of the directory, not one file.
assert_eq!(
launch["arguments"],
json!({ "stopOnEntry": false, "program": directory, "cwd": "/work" })
);
}

#[test]
fn debug_executable_plan_lists_the_configured_path_and_ordered_candidates() {
let plan = debug_executable_plan(
Expand Down
24 changes: 24 additions & 0 deletions rust/crates/core/src/tests/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,30 @@ fn debug_adapter_endpoint_validation_crosses_the_json_boundary() {
}
}

#[test]
fn debug_adapter_announcements_cross_the_json_boundary() {
let fixture: Value = serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/debug/adapter-announcements-v1.json"
)))
.expect("announcement fixture is JSON");
for case in fixture["cases"].as_array().expect("announcement cases") {
let request = serde_json::json!({
"id": "read-announcement", "command": "debug.adapters.readAnnouncement", "payload": case["input"]
});
let response: Value = serde_json::from_str(&execute_json(&request.to_string()))
.expect("announcement response is JSON");
assert_eq!(response["id"], "read-announcement");
match case.get("result") {
Some(result) => {
assert_eq!(response["ok"], true, "{case}");
assert_eq!(response["data"], *result, "{case}");
}
None => assert_eq!(response["error"]["code"], "invalid_request", "{case}"),
}
}
}

#[test]
fn debug_transport_commands_cross_the_json_boundary() {
let call = |command: &str, payload: Value| -> Value {
Expand Down
10 changes: 8 additions & 2 deletions rust/crates/debug/src/adapters.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! `debugAdapters[]` of an API level 4 plugin manifest: what a host must know
//! about a debug adapter before starting any process for it.
//! `debugAdapters[]` of a plugin manifest: what a host must know about a
//! debug adapter before starting any process for it.
//!
//! A declaration names the adapter, how its process is started and reached
//! (stdio, a loopback TCP endpoint, or a port the plugin's own language server
Expand All @@ -26,6 +26,7 @@ use serde_json::{json, Map, Value};
use std::collections::{BTreeSet, HashSet};
use std::net::IpAddr;

mod announcement;
mod checks;
mod declaration;
mod plan;
Expand All @@ -36,6 +37,7 @@ mod validate_adapter;
mod validate_configuration;
mod validate_launch;

pub use announcement::*;
pub(crate) use checks::*;
pub use declaration::*;
pub use plan::*;
Expand Down Expand Up @@ -87,6 +89,10 @@ const MAX_EXECUTABLE_CANDIDATE: usize = 1024;
/// resolved, instead of the target's own path.
const TARGET_EXECUTABLE: &str = "target.executable";

/// The `targetBindings.program` source that reads the directory containing the
/// target's path, for adapters that debug a package rather than one file.
const TARGET_DIRECTORY: &str = "target.directory";

/// The target kind of a remote `host:port` the debuggee listens on.
const TARGET_CONNECTION: &str = "connection";

Expand Down
147 changes: 147 additions & 0 deletions rust/crates/debug/src/adapters/announcement.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//! The endpoint a `tcpAnnounced` adapter prints on its own output.
//!
//! The host reads the adapter's output line by line and asks Core about each
//! one until a line announces the endpoint, then connects to it. Core decides
//! which line is the announcement and which endpoints are acceptable, so every
//! platform host reads the same announcements the same way. Core never reads
//! the process output, opens a socket, resolves a name or keeps a clock: the
//! host bounds the wait with the transport's discovery deadline.

use super::*;
use lithe_protocol::{CoreError, ErrorCode};

/// Longest endpoint text after the prefix, in bytes: room for a bracketed IPv6
/// address and a port, with margin.
const MAX_ANNOUNCED_ENDPOINT: usize = 128;

/// Where a `port` announcement listens: adapters that print only a port listen
/// on the IPv4 loopback address.
const ANNOUNCED_PORT_HOST: &str = "127.0.0.1";

/// `debug.adapters.readAnnouncement`: whether one output line of a
/// `tcpAnnounced` adapter announces its endpoint.
///
/// The payload is `{ endpoint, stream, line }`: the `endpoint` of the
/// adapter's launch plan, the stream the line came from, and the line without
/// its line break. A line on another stream, or one without the prefix, is
/// `{ status: "none" }`. A line with the prefix is the announcement: the rest
/// of the line after the prefix's first occurrence, without surrounding
/// whitespace, is `{ status: "announced", host, port }` when it is a loopback
/// endpoint, and `{ status: "invalid", reason }` otherwise. A malformed
/// payload fails with `invalid_request`.
pub fn read_announcement(payload: Value) -> Result<Value, CoreError> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
endpoint: DebugEndpoint,
stream: String,
line: String,
}
let request: Request = serde_json::from_value(payload).map_err(|error| {
CoreError::new(ErrorCode::InvalidRequest, "Invalid announcement request.")
.with_details(error.to_string())
})?;
if !request.endpoint.is_announced() {
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"An announced endpoint names a stream, a one-line prefix, and port or hostPort.",
));
}
if !matches!(request.stream.as_str(), "stdout" | "stderr") {
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"A line comes from stdout or stderr.",
));
}
let endpoint = request.endpoint;
let prefix = endpoint.prefix.as_deref().unwrap_or_default();
if endpoint.stream.as_deref() != Some(request.stream.as_str()) {
return Ok(json!({ "status": "none" }));
}
let Some((_, rest)) = request.line.split_once(prefix) else {
return Ok(json!({ "status": "none" }));
};
let announced = rest.trim();
let parsed = match endpoint.value.as_deref() {
Some("port") => announced_port(announced).map(|port| (ANNOUNCED_PORT_HOST, port)),
_ => announced_host_port(announced),
};
Ok(match parsed {
Err(reason) => json!({ "status": "invalid", "reason": reason }),
Ok((host, port)) => json!({ "status": "announced", "host": host, "port": port }),
})
}

/// Why an announcement is not an endpoint the host may connect to.
type Refusal = &'static str;

/// The text is not a port, or not `host:port` with a valid host.
const MALFORMED: Refusal = "malformed";

/// The text names a host Core cannot tell is this machine.
const NOT_LOOPBACK: Refusal = "notLoopback";

/// A port from 1 to 65535 written in decimal digits only.
fn announced_port(text: &str) -> Result<u16, Refusal> {
if text.is_empty() || text.len() > 5 || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(MALFORMED);
}
match text.parse::<u16>() {
Ok(port) if port >= 1 => Ok(port),
_ => Err(MALFORMED),
}
}

/// `host:port`, or `[address]:port` for IPv6, with a loopback host.
fn announced_host_port(text: &str) -> Result<(&str, u16), Refusal> {
if text.len() > MAX_ANNOUNCED_ENDPOINT {
return Err(MALFORMED);
}
let (host, port) = match text.strip_prefix('[') {
Some(bracketed) => {
let (address, port) = bracketed.split_once("]:").ok_or(MALFORMED)?;
if !address.contains(':') {
return Err(MALFORMED);
}
(address, port)
}
None => {
let (host, port) = text.rsplit_once(':').ok_or(MALFORMED)?;
if host.contains(':') {
return Err(MALFORMED);
}
(host, port)
}
};
let port = announced_port(port)?;
if host_problem(host).is_some() {
return Err(MALFORMED);
}
if !is_loopback_host(host) {
return Err(NOT_LOOPBACK);
}
Ok((host, port))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn announcement_fixtures_match_the_reading() {
let fixture: Value = serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/debug/adapter-announcements-v1.json"
)))
.expect("announcement fixture is JSON");
let cases = fixture["cases"].as_array().expect("fixture cases");
assert!(!cases.is_empty());
for case in cases {
let result = read_announcement(case["input"].clone());
match case.get("result") {
Some(expected) => assert_eq!(result.expect("a reading"), *expected, "{case}"),
None => assert!(result.is_err(), "{case}"),
}
}
}
}
3 changes: 2 additions & 1 deletion rust/crates/debug/src/adapters/declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ pub struct DebugTargetBindings {
/// Source of the `env` argument: only `target.environment`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub env: Option<String>,
/// Source of the `program` argument: `target.path` or `target.executable`. Launch only.
/// Source of the `program` argument: `target.path`, `target.directory` (the
/// directory containing `target.path`) or `target.executable`. Launch only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub program: Option<String>,
/// Source of the `processId` argument: only `target.processID`. Attach only.
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/debug/src/adapters/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ pub fn plan(
{
return Err(missing("target.path", "path"));
}
Some(TARGET_DIRECTORY) if target.path.as_deref().and_then(target_directory).is_none() => {
return Err(missing("target.path", "path inside a directory"));
}
_ => {}
}
if bindings.args.is_some()
Expand Down
14 changes: 14 additions & 0 deletions rust/crates/debug/src/adapters/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ fn bound_arguments(
};
let program = match bindings.program.as_deref() {
Some(TARGET_EXECUTABLE) => target.executable.clone(),
Some(TARGET_DIRECTORY) => target
.path
.as_deref()
.and_then(target_directory)
.map(str::to_string),
_ => target.path.clone(),
};
bind("program", &bindings.program, program.map(Value::from));
Expand Down Expand Up @@ -184,6 +189,15 @@ fn bound_arguments(
})
}

/// The directory that contains a target path, or `None` when the path names
/// no directory, for example a bare file name.
pub(crate) fn target_directory(path: &str) -> Option<&str> {
std::path::Path::new(path)
.parent()
.and_then(std::path::Path::to_str)
.filter(|directory| !directory.is_empty())
}

/// Writes the target's endpoint, and its path mappings when the adapter takes
/// them, to the destinations the binding names.
fn bind_connection(
Expand Down
Loading
Loading