ZIm/crates/terminal/src/pty_info.rs
Remco Smits 41a60ffecf
Debugger implementation (#13433)
###  DISCLAIMER

> As of 6th March 2025, debugger is still in development. We plan to
merge it behind a staff-only feature flag for staff use only, followed
by non-public release and then finally a public one (akin to how Git
panel release was handled). This is done to ensure the best experience
when it gets released.

### END OF DISCLAIMER 

**The current state of the debugger implementation:**


https://github.com/user-attachments/assets/c4deff07-80dd-4dc6-ad2e-0c252a478fe9


https://github.com/user-attachments/assets/e1ed2345-b750-4bb6-9c97-50961b76904f

----

All the todo's are in the following channel, so it's easier to work on
this together:
https://zed.dev/channel/zed-debugger-11370

If you are on Linux, you can use the following command to join the
channel:
```cli
zed https://zed.dev/channel/zed-debugger-11370 
```

## Current Features

- Collab
  - Breakpoints
    - Sync when you (re)join a project
    - Sync when you add/remove a breakpoint
  - Sync active debug line
  - Stack frames
    - Click on stack frame
      - View variables that belong to the stack frame
      - Visit the source file
    - Restart stack frame (if adapter supports this)
  - Variables
  - Loaded sources
  - Modules
  - Controls
    - Continue
    - Step back
      - Stepping granularity (configurable)
    - Step into
      - Stepping granularity (configurable)
    - Step over
      - Stepping granularity (configurable)
    - Step out
      - Stepping granularity (configurable)
  - Debug console
- Breakpoints
  - Log breakpoints
  - line breakpoints
  - Persistent between zed sessions (configurable)
  - Multi buffer support
  - Toggle disable/enable all breakpoints
- Stack frames
  - Click on stack frame
    - View variables that belong to the stack frame
    - Visit the source file
    - Show collapsed stack frames
  - Restart stack frame (if adapter supports this)
- Loaded sources
  - View all used loaded sources if supported by adapter.
- Modules
  - View all used modules (if adapter supports this)
- Variables
  - Copy value
  - Copy name
  - Copy memory reference
  - Set value (if adapter supports this)
  - keyboard navigation
- Debug Console
  - See logs
  - View output that was sent from debug adapter
    - Output grouping
  - Evaluate code
    - Updates the variable list
    - Auto completion
- If not supported by adapter, we will show auto-completion for existing
variables
- Debug Terminal
- Run custom commands and change env values right inside your Zed
terminal
- Attach to process (if adapter supports this)
  - Process picker
- Controls
  - Continue
  - Step back
    - Stepping granularity (configurable)
  - Step into
    - Stepping granularity (configurable)
  - Step over
    - Stepping granularity (configurable)
  - Step out
    - Stepping granularity (configurable)
  - Disconnect
  - Restart
  - Stop
- Warning when a debug session exited without hitting any breakpoint
- Debug view to see Adapter/RPC log messages
- Testing
  - Fake debug adapter
    - Fake requests & events

---

Release Notes:

- N/A

---------

Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Anthony Eid <hello@anthonyeid.me>
Co-authored-by: Anthony <anthony@zed.dev>
Co-authored-by: Piotr Osiewicz <peterosiewicz@gmail.com>
Co-authored-by: Piotr <piotr@zed.dev>
2025-03-18 12:55:25 -04:00

158 lines
4.4 KiB
Rust

use alacritty_terminal::tty::Pty;
#[cfg(target_os = "windows")]
use std::num::NonZeroU32;
#[cfg(unix)]
use std::os::fd::AsRawFd;
use std::path::PathBuf;
#[cfg(target_os = "windows")]
use windows::Win32::{Foundation::HANDLE, System::Threading::GetProcessId};
use sysinfo::{Pid, Process, ProcessRefreshKind, RefreshKind, System, UpdateKind};
pub struct ProcessIdGetter {
handle: i32,
fallback_pid: u32,
}
#[cfg(unix)]
impl ProcessIdGetter {
fn new(pty: &Pty) -> ProcessIdGetter {
ProcessIdGetter {
handle: pty.file().as_raw_fd(),
fallback_pid: pty.child().id(),
}
}
fn pid(&self) -> Option<Pid> {
let pid = unsafe { libc::tcgetpgrp(self.handle) };
if pid < 0 {
return Some(Pid::from_u32(self.fallback_pid));
}
Some(Pid::from_u32(pid as u32))
}
pub fn fallback_pid(&self) -> u32 {
self.fallback_pid
}
}
#[cfg(windows)]
impl ProcessIdGetter {
fn new(pty: &Pty) -> ProcessIdGetter {
let child = pty.child_watcher();
let handle = child.raw_handle();
let fallback_pid = child.pid().unwrap_or_else(|| unsafe {
NonZeroU32::new_unchecked(GetProcessId(HANDLE(handle as _)))
});
ProcessIdGetter {
handle: handle as i32,
fallback_pid: u32::from(fallback_pid),
}
}
fn pid(&self) -> Option<Pid> {
let pid = unsafe { GetProcessId(HANDLE(self.handle as _)) };
// the GetProcessId may fail and returns zero, which will lead to a stack overflow issue
if pid == 0 {
// in the builder process, there is a small chance, almost negligible,
// that this value could be zero, which means child_watcher returns None,
// GetProcessId returns 0.
if self.fallback_pid == 0 {
return None;
}
return Some(Pid::from_u32(self.fallback_pid));
}
Some(Pid::from_u32(pid))
}
pub fn fallback_pid(&self) -> u32 {
self.fallback_pid
}
}
#[derive(Clone, Debug)]
pub struct ProcessInfo {
pub name: String,
pub cwd: PathBuf,
pub argv: Vec<String>,
}
/// Fetches Zed-relevant Pseudo-Terminal (PTY) process information
pub struct PtyProcessInfo {
system: System,
refresh_kind: ProcessRefreshKind,
pid_getter: ProcessIdGetter,
pub current: Option<ProcessInfo>,
}
impl PtyProcessInfo {
pub fn new(pty: &Pty) -> PtyProcessInfo {
let process_refresh_kind = ProcessRefreshKind::new()
.with_cmd(UpdateKind::Always)
.with_cwd(UpdateKind::Always)
.with_exe(UpdateKind::Always);
let refresh_kind = RefreshKind::new().with_processes(process_refresh_kind);
let system = System::new_with_specifics(refresh_kind);
PtyProcessInfo {
system,
refresh_kind: process_refresh_kind,
pid_getter: ProcessIdGetter::new(pty),
current: None,
}
}
pub fn pid_getter(&self) -> &ProcessIdGetter {
&self.pid_getter
}
fn refresh(&mut self) -> Option<&Process> {
let pid = self.pid_getter.pid()?;
if self.system.refresh_processes_specifics(
sysinfo::ProcessesToUpdate::Some(&[pid]),
self.refresh_kind,
) == 1
{
self.system.process(pid)
} else {
None
}
}
fn load(&mut self) -> Option<ProcessInfo> {
let process = self.refresh()?;
let cwd = process.cwd().map_or(PathBuf::new(), |p| p.to_owned());
let info = ProcessInfo {
name: process.name().to_str()?.to_owned(),
cwd,
argv: process
.cmd()
.iter()
.filter_map(|s| s.to_str().map(ToOwned::to_owned))
.collect(),
};
self.current = Some(info.clone());
Some(info)
}
/// Updates the cached process info, returns whether the Zed-relevant info has changed
pub fn has_changed(&mut self) -> bool {
let current = self.load();
let has_changed = match (self.current.as_ref(), current.as_ref()) {
(None, None) => false,
(Some(prev), Some(now)) => prev.cwd != now.cwd || prev.name != now.name,
_ => true,
};
if has_changed {
self.current = current;
}
has_changed
}
pub fn pid(&self) -> Option<Pid> {
self.pid_getter.pid()
}
}