Skip to content
haranaPublic
forked from sztomi/dap-rs

About

A Rust implementation of the Debug Adapter Protocol

Resources

Code of conduct

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

dap-rs, a Rust implementation of the Debug Adapter Protocol

Introduction

This crate is a Rust implementation of the Debug Adapter Protocol (or DAP for short).

The best way to think of DAP is to compare it to LSP (Language Server Protocol) but for debuggers. The core idea is the same: a protocol that serves as lingua franca for editors and debuggers to talk to each other. This means that an editor that implements DAP can use a debugger that also implements DAP.

In practice, the adapter might be separate from the actual debugger. For example, one could implement an adapter that writes commands to the stdin of a gdb subprocess, then parses the output it receives (this is why it's called an "adapter" - it adapts the debugger to editors that know DAP).

Generated protocol types

The protocol types (types, requests, responses, events, reverse_requests and spec_version) are generated from the published DAP JSON schema, which is vendored in schema/debugAdapterProtocol.json together with its provenance in schema/metadata.json. The generated files are checked in, so nothing is generated while building the crate.

To move to a newer specification, drop in the new schema, update schema/metadata.json and re-run the generator:

cargo xtask codegen

CI runs cargo xtask codegen --check, which fails when the checked-in modules no longer match the schema. Everything else in dap/src (the server, base message and errors) is hand-written.

Reverse requests

A debug adapter can ask the client to do something with Server::send_reverse_request (runInTerminal, startDebugging). The client's answer arrives as a ReverseResponse: Server::poll returns it as Received::Response, and Server::poll_request buffers it so it can be taken with Server::next_reverse_response. Correlate the answer with the request through its request_seq, which matches the seq of the ReverseRequest that was sent.

Error responses

A response with success: false has no typed body: the specification puts a structured Message in body.error instead. Response mirrors that — body stays None, the structured error is parsed into Response::error, the short form into Response::message, and the command being answered into Response::command (which is also what makes the error responses produced by Request::error/Request::cancellation carry the required command field on the wire).

let response = client.wait_for_response(seq)?;
if !response.success {
  let reason = response.error.map(|error| error.format);
  eprintln!("{:?} failed: {reason:?}", response.command);
}

Stability

This crate is in a fairly early stage and breakages will be frequent. Any version before 1.0 might be a breaking version.

Minimal example: implementing an adapter

To get started, create a binary project and add dap to your Cargo.toml:

[package]
name = "dummy-server"
version = "*"
edition = "2021"

[dependencies]
dap = "*"

Our dummy server is going to read its input from a text file and write the output to stdout.

use std::fs::File;
use std::io::{BufReader, BufWriter};

use thiserror::Error;

use dap::prelude::*;

#[derive(Error, Debug)]
enum MyAdapterError {
  #[error("Unhandled command")]
  UnhandledCommandError,

  #[error("Missing command")]
  MissingCommandError,
}

type DynResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;

fn main() -> DynResult<()> {
  let output = BufWriter::new(std::io::stdout());
  let f = File::open("testinput.txt")?;
  let input = BufReader::new(f);
  let mut server = Server::new(input, output);

  let req = match server.poll_request()? {
    Some(req) => req,
    None => return Err(Box::new(MyAdapterError::MissingCommandError)),
  };
  if let Command::Initialize(_) = req.command {
    let rsp = req.success(
      ResponseBody::Initialize(types::Capabilities {
        ..Default::default()
      }),
    );

    // When you call respond, send_event etc. the message will be wrapped
    // in a base message with a appropriate seq number, so you don't have to keep track of that yourself
    server.respond(rsp)?;

    server.send_event(Event::Initialized)?;
  } else {
    return Err(Box::new(MyAdapterError::UnhandledCommandError));
  }
  Ok(())
}

A full end-to-end example: debugging a Rust program through lldb-dap

The example above implements the adapter side of the protocol. Because every generated type serializes in both directions, the crate works equally well on the client side — the role an editor normally plays. That makes it possible to show a complete, working debug session with nothing but this crate and a real debugger:

┌──────────────────────┐   DAP over stdio   ┌──────────┐   ptrace    ┌──────────┐
│ lldb-dap-client      │ ◄────────────────► │ lldb-dap │ ◄─────────► │ debuggee │
│ (dap-rs, client role)│                    │ (LLDB)   │             │ (Rust)   │
└──────────────────────┘                    └──────────┘             └──────────┘

The client is checked in as dap/examples/lldb-dap-client.rs. It spawns the adapter, negotiates capabilities, sets a source breakpoint, and then either launches a program or attaches to one that is already running. Every time the breakpoint is hit it prints the stack trace and resumes the debuggee; after three hits it disconnects (terminating a launched program, leaving an attached one running).

Choosing an adapter

We standardise on lldb-dap, the DAP adapter maintained in-tree with LLDB. LLDB understands Rust debug info well, and lldb-dap ships with LLVM packages on every major platform, so it is the most dependable baseline for debugging Rust programs. The main alternative is CodeLLDB, which layers nicer Rust value rendering on top of LLDB — worth using inside VS Code, but it is distributed as an editor extension rather than a standalone binary, which makes lldb-dap the better target for examples and automation. (GDB 14+ also speaks DAP natively via gdb -i dap, if you are on a platform where GDB is the norm.)

Install it from your package manager, e.g.:

# Debian/Ubuntu (the binary is versioned, e.g. lldb-dap-18)
sudo apt install lldb-18
# macOS: already included in the Xcode Command Line Tools (`xcode-select --install`),
# or from Homebrew's LLVM
brew install llvm
# or via your distro's plain `lldb` package, which often includes lldb-dap

The example looks for lldb-dap on PATH; set LLDB_DAP=lldb-dap-18 (or wherever your binary lives) if it is named differently. On macOS the binary ships with the Command Line Tools but is not on PATH, so ask xcrun where it is:

export LLDB_DAP=$(xcrun -f lldb-dap)

One quirk of lldb-dap 21 (including the Apple build) is worth knowing: pathFormat is optional in the specification, but its initialize handler treats it as mandatory and answers with missing value at arguments.pathFormat when it is absent (llvm/llvm-project#170171). The example therefore always sends it.

The program we will debug

Any Rust binary with debug info works. The only "modification" a program needs to be debuggable is debug info in the build — cargo build includes it by default in the dev profile, and release builds can opt in with:

[profile.release]
debug = true

For a reproducible walkthrough, create a small program that we can both launch and attach to (cargo new counter):

use std::{thread, time::Duration};

fn tick(count: u64) -> u64 {
    let next = count + 1; // <-- we will set a breakpoint on this line (line 4)
    println!("count is now {next}");
    next
}

fn main() {
    println!("counter started, pid {}", std::process::id());
    let mut count = 0;
    loop {
        count = tick(count);
        thread::sleep(Duration::from_secs(1));
    }
}

Build it with cargo build (from the counter directory).

Scenario 1: launch a program under the debugger

From a checkout of this repository:

cargo run --example lldb-dap-client -- \
  launch path/to/counter/target/debug/counter path/to/counter/src/main.rs 4

The client starts the program via lldb-dap, and the breakpoint on line 4 is hit on every loop iteration:

launching /home/you/counter/target/debug/counter
breakpoint set at /home/you/counter/src/main.rs:4
[debuggee] counter started, pid 8232

stopped (reason: Breakpoint), stack trace:
  #524288 counter::tick::h3f9c6d27b89c4173 (main.rs:4)
  #524289 counter::main::h6442514c9c4d5a91 (main.rs:13)
  ...
[debuggee] count is now 1

stopped (reason: Breakpoint), stack trace:
  ...

disconnecting

After the third hit the client disconnects with terminateDebuggee: true and the program is killed.

Scenario 2: attach to an already-running program

Start the program normally, outside of any debugger:

path/to/counter/target/debug/counter
# counter started, pid 8962
# count is now 1
# ...

Then attach to it by pid (on Linux this may require sudo sysctl kernel.yama.ptrace_scope=0, or running the client with the same privileges as the target):

cargo run --example lldb-dap-client -- attach 8962 path/to/counter/src/main.rs 4

The client stops the running process at the same breakpoint, prints stack traces, and after three hits disconnects with terminateDebuggee: false — the counter keeps running as if nothing happened.

How the session works

The client walks through the canonical DAP sequence. Abridged from the example (the full source includes the message framing and buffering):

// 1. Negotiate capabilities.
let seq = client.send(Command::Initialize(requests::InitializeRequestArguments {
  adapter_id: "lldb-dap".to_string(),
  lines_start_at1: Some(true),
  columns_start_at1: Some(true),
  ..Default::default()
}))?;
client.wait_for_response(seq)?;

// 2. Launch the program — or attach with `Command::Attach` and `{ "pid": pid }`.
//    Fields beyond the specification's own (`program`, `pid`, ...) are
//    adapter-specific, which is what `additional_data` is for.
let launch = client.send(Command::Launch(requests::LaunchRequestArguments {
  additional_data: Some(json!({ "program": program })),
  ..Default::default()
}))?;

// 3. Wait for the `initialized` event, then configure breakpoints. The adapter
//    answers `launch`/`attach` only after `configurationDone`.
loop {
  match client.next_event()? {
    Event::Initialized => break,
    event => log_event(event),
  }
}
let seq = client.send(Command::SetBreakpoints(requests::SetBreakpointsArguments {
  source: types::Source { path: Some(source), ..Default::default() },
  breakpoints: Some(vec![types::SourceBreakpoint { line, ..Default::default() }]),
  ..Default::default()
}))?;
client.wait_for_response(seq)?;
let seq = client.send(Command::ConfigurationDone(None))?;
client.wait_for_response(seq)?;
client.wait_for_response(launch)?;

// 4. The debuggee is now running. On every `stopped` event, inspect and resume.
let stopped = loop {
  match client.next_event()? {
    Event::Stopped(body) => break body,
    event => log_event(event),
  }
};
let thread_id = stopped.thread_id.unwrap_or(1);
let seq = client.send(Command::StackTrace(requests::StackTraceArguments {
  thread_id,
  levels: Some(5),
  ..Default::default()
}))?;
if let Some(ResponseBody::StackTrace(trace)) = client.wait_for_response(seq)?.body {
  for frame in &trace.stack_frames {
    println!("  #{:<2} {} ({})", frame.id, frame.name, frame.line);
  }
}
let seq = client.send(Command::Continue(requests::ContinueArguments {
  thread_id,
  ..Default::default()
}))?;
client.wait_for_response(seq)?;

// 5. Disconnect: kill a launched debuggee, leave an attached one running.
let seq = client.send(Command::Disconnect(Some(requests::DisconnectArguments {
  terminate_debuggee: Some(mode == "launch"),
  ..Default::default()
})))?;
client.wait_for_response(seq)?;

Two details are worth calling out when talking to real adapters:

  • Responses arrive out of order. lldb-dap answers the launch/attach request only after configurationDone, and events (output, process, stopped) interleave with responses. The example buffers both and matches responses to requests via request_seq — don't assume the next message is the answer to your last request.
  • Launch/attach arguments are adapter-specific. The DAP specification deliberately leaves them open; LaunchRequestArguments/AttachRequestArguments expose the adapter-specific part through the flattened additional_data field. For lldb-dap that is {"program": "..."} to launch and {"pid": ...} to attach (see its documentation for the full list, including args, env, cwd and stopOnEntry).

License

This library is dual-licensed as MIT and Apache 2.0. That means users may choose either of these licenses. In general, these are non-restrictive, non-viral licenses, a.k.a. "do what you want but no guarantees from me".

Commercial support is available on a contract basis (contact me: szelei.t@gmail.com).

About

A Rust implementation of the Debug Adapter Protocol

Resources

Code of conduct

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages