2 transport::{Payload, Request, Transport},
7pub use log::{error, info};
10 net::{IpAddr, Ipv4Addr, SocketAddr},
13 sync::atomic::{AtomicU64, Ordering},
16 io::{AsyncBufRead, AsyncWrite, BufReader, BufWriter},
18 process::{Child, Command},
19 sync::mpsc::{channel, unbounded_channel, UnboundedReceiver, UnboundedSender},
26 _process: Option<Child>,
27 server_tx: UnboundedSender<Request>,
28 request_counter: AtomicU64,
29 pub caps: Option<DebuggerCapabilities>,
31 pub breakpoints: HashMap<PathBuf, Vec<SourceBreakpoint>>,
32 // TODO: multiple threads support
33 pub stack_pointer: Option<StackFrame>,
34 pub stopped_thread: Option<usize>,
39 // Spawn a process and communicate with it by either TCP or stdio
41 cfg: DebugAdapterConfig,
43 ) -> Result<(Self, UnboundedReceiver<Payload>)> {
44 if cfg.transport == "tcp" && cfg.port_arg.is_some() {
47 cfg.args.iter().map(|s| s.as_str()).collect(),
48 &cfg.port_arg.unwrap(),
52 } else if cfg.transport == "stdio" {
55 cfg.args.iter().map(|s| s.as_str()).collect(),
59 Result::Err(Error::Other(anyhow!(
60 "Incorrect transport {}",
67 rx: Box<dyn AsyncBufRead + Unpin + Send>,
68 tx: Box<dyn AsyncWrite + Unpin + Send>,
70 process: Option<Child>,
71 ) -> Result<(Self, UnboundedReceiver<Payload>)> {
72 let (server_rx, server_tx) = Transport::start(rx, tx, id);
73 let (client_rx, client_tx) = unbounded_channel();
79 request_counter: AtomicU64::new(0),
82 breakpoints: HashMap::new(),
88 tokio::spawn(Self::recv(server_rx, client_rx));
90 Ok((client, client_tx))
94 addr: std::net::SocketAddr,
96 ) -> Result<(Self, UnboundedReceiver<Payload>)> {
97 let stream = TcpStream::connect(addr).await?;
98 let (rx, tx) = stream.into_split();
99 Self::streams(Box::new(BufReader::new(rx)), Box::new(tx), id, None)
106 ) -> Result<(Self, UnboundedReceiver<Payload>)> {
107 let process = Command::new(cmd)
109 .stdin(Stdio::piped())
110 .stdout(Stdio::piped())
111 // make sure the process is reaped on drop
115 let mut process = process?;
117 // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
118 let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
119 let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
122 Box::new(BufReader::new(reader)),
129 async fn get_port() -> Option<u16> {
131 tokio::net::TcpListener::bind(SocketAddr::new(
132 IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
143 pub async fn tcp_process(
148 ) -> Result<(Self, UnboundedReceiver<Payload>)> {
149 let port = Self::get_port().await.unwrap();
151 let process = Command::new(cmd)
153 .args(port_format.replace("{}", &port.to_string()).split(' '))
155 .stdin(Stdio::null())
156 .stdout(Stdio::null())
157 .stderr(Stdio::null())
158 // Do not kill debug adapter when leaving, it should exit automatically
161 // Wait for adapter to become ready for connection
162 time::sleep(time::Duration::from_millis(500)).await;
164 let stream = TcpStream::connect(SocketAddr::new(
165 IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
170 let (rx, tx) = stream.into_split();
172 Box::new(BufReader::new(rx)),
179 async fn recv(mut server_rx: UnboundedReceiver<Payload>, client_tx: UnboundedSender<Payload>) {
180 while let Some(msg) = server_rx.recv().await {
182 Payload::Event(ev) => {
183 client_tx.send(Payload::Event(ev)).expect("Failed to send");
185 Payload::Response(_) => unreachable!(),
186 Payload::Request(req) => {
188 .send(Payload::Request(req))
189 .expect("Failed to send");
195 pub fn id(&self) -> usize {
199 fn next_request_id(&self) -> u64 {
200 self.request_counter.fetch_add(1, Ordering::Relaxed)
203 async fn request<R: crate::types::Request>(
205 arguments: R::Arguments,
206 ) -> Result<R::Result> {
207 let (callback_tx, mut callback_rx) = channel(1);
209 let arguments = Some(serde_json::to_value(arguments)?);
212 back_ch: Some(callback_tx),
213 seq: self.next_request_id(),
214 command: R::COMMAND.to_string(),
220 .expect("Failed to send request to debugger");
222 let response = callback_rx.recv().await.unwrap()?;
223 let response = serde_json::from_value(response.body.unwrap_or_default())?;
227 pub fn capabilities(&self) -> &DebuggerCapabilities {
230 .expect("debugger not yet initialized!")
233 pub async fn initialize(&mut self, adapter_id: String) -> Result<()> {
234 let args = requests::InitializeArguments {
235 client_id: Some("hx".to_owned()),
236 client_name: Some("helix".to_owned()),
238 locale: Some("en-us".to_owned()),
239 lines_start_at_one: Some(true),
240 columns_start_at_one: Some(true),
241 path_format: Some("path".to_owned()),
242 supports_variable_type: Some(true),
243 supports_variable_paging: Some(false),
244 supports_run_in_terminal_request: Some(false),
245 supports_memory_references: Some(false),
246 supports_progress_reporting: Some(false),
247 supports_invalidated_event: Some(false),
250 let response = self.request::<requests::Initialize>(args).await?;
251 self.caps = Some(response);
256 pub async fn disconnect(&mut self) -> Result<()> {
257 self.request::<requests::Disconnect>(()).await
260 pub async fn launch(&mut self, args: serde_json::Value) -> Result<()> {
261 let response = self.request::<requests::Launch>(args).await?;
262 log::error!("launch response {}", response);
267 pub async fn attach(&mut self, args: serde_json::Value) -> Result<()> {
268 let response = self.request::<requests::Attach>(args).await?;
269 log::error!("attach response {}", response);
274 pub async fn set_breakpoints(
277 breakpoints: Vec<SourceBreakpoint>,
278 ) -> Result<Option<Vec<Breakpoint>>> {
279 let args = requests::SetBreakpointsArguments {
283 source_reference: None,
284 presentation_hint: None,
290 breakpoints: Some(breakpoints),
291 source_modified: Some(false),
294 let response = self.request::<requests::SetBreakpoints>(args).await?;
296 Ok(response.breakpoints)
299 pub async fn configuration_done(&mut self) -> Result<()> {
300 self.request::<requests::ConfigurationDone>(()).await
303 pub async fn continue_thread(&mut self, thread_id: usize) -> Result<Option<bool>> {
304 let args = requests::ContinueArguments { thread_id };
306 let response = self.request::<requests::Continue>(args).await?;
307 Ok(response.all_threads_continued)
310 pub async fn stack_trace(
313 ) -> Result<(Vec<StackFrame>, Option<usize>)> {
314 let args = requests::StackTraceArguments {
321 let response = self.request::<requests::StackTrace>(args).await?;
322 Ok((response.stack_frames, response.total_frames))
325 pub async fn threads(&mut self) -> Result<Vec<Thread>> {
326 let response = self.request::<requests::Threads>(()).await?;
330 pub async fn scopes(&mut self, frame_id: usize) -> Result<Vec<Scope>> {
331 let args = requests::ScopesArguments { frame_id };
333 let response = self.request::<requests::Scopes>(args).await?;
337 pub async fn variables(&mut self, variables_reference: usize) -> Result<Vec<Variable>> {
338 let args = requests::VariablesArguments {
346 let response = self.request::<requests::Variables>(args).await?;
347 Ok(response.variables)
350 pub async fn step_in(&mut self, thread_id: usize) -> Result<()> {
351 let args = requests::StepInArguments {
357 self.request::<requests::StepIn>(args).await
360 pub async fn step_out(&mut self, thread_id: usize) -> Result<()> {
361 let args = requests::StepOutArguments {
366 self.request::<requests::StepOut>(args).await
369 pub async fn next(&mut self, thread_id: usize) -> Result<()> {
370 let args = requests::NextArguments {
375 self.request::<requests::Next>(args).await
378 pub async fn pause(&mut self, thread_id: usize) -> Result<()> {
379 let args = requests::PauseArguments { thread_id };
381 self.request::<requests::Pause>(args).await
387 frame_id: Option<usize>,
388 ) -> Result<requests::EvaluateResponse> {
389 let args = requests::EvaluateArguments {
396 self.request::<requests::Evaluate>(args).await
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list