дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
perf(debug): share one lldb-dap server across Xcode debug sessions (#7442)
Every Xcode attach started a fresh lldb-dap, which parses the symbol tables of the ~550 system libraries an iOS app loads before reaching a breakpoint. Xcode attaches on macOS now reuse one lldb-dap server (keyed by working directory, lldb-dap binary and environment, over a private Unix socket) that keeps the parsed modules; it ends after 10 minutes without a session, when the IDE quits, or when another configuration replaces it. Overlapping attaches and custom adapter invocations keep their own process. Measured on an iOS Simulator: attach to stopped-with-frames 1.74 s before, 0.49 s with a warm server, 1.56 s cold. Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
406cf4e474
коміт
72db7ecb97
7 files changed
+486
-4
No files matched your search
@@ -51,6 +51,8 @@ pub struct AdapterSpec {
|
||||
pub pinned: Option<ProgramPin>,
|
||||
/// See [`DebuggerConfig::resolve_lazy_variables`].
|
||||
pub resolve_lazy_variables: bool,
|
||||
/// Connect to the one lldb-dap server every such session shares ([`crate::lldb_server`]).
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
/// Built-in adapters used when no language definition names `adapter`.
|
||||
@@ -193,6 +195,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
|
||||
connect: config.connect.clone(),
|
||||
pinned: config.pinned.clone(),
|
||||
resolve_lazy_variables: config.resolve_lazy_variables,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +301,7 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
|
||||
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
|
||||
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
|
||||
fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
pub(crate) fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
|
||||
(!own).then(|| ide_core::tool_path::search_path_in(cwd))
|
||||
}
|
||||
@@ -744,6 +747,18 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
.ok_or_else(|| missing(&spec))?
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
if spec.shared && spec.transport == Transport::Stdio && spec.connect.is_none() && spec.args.is_empty() {
|
||||
match crate::lldb_server::connect(&spec, &binary).await {
|
||||
Ok(Some(io)) => return Ok(io),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(
|
||||
target: "ide_dap::adapter",
|
||||
"no shared lldb-dap server ({}); starting one for this session",
|
||||
e.message
|
||||
),
|
||||
}
|
||||
}
|
||||
let launch_after_configuration =
|
||||
if spec.adapter == "gdb" { prepare_gdb(&spec, &binary).await? } else { false };
|
||||
let base_args = substitute_root(&spec.args, &spec.cwd);
|
||||
@@ -891,7 +906,7 @@ fn is_port_race(err: &IdeError) -> bool {
|
||||
|| message.contains("exited before accepting connections")
|
||||
}
|
||||
|
||||
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
pub(crate) fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
stream: R,
|
||||
name: String,
|
||||
sink: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
|
||||
@@ -103,6 +103,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let session = Session::new(
|
||||
DebugSessionId(1),
|
||||
|
||||
@@ -21,6 +21,8 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod lldb_server;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
@@ -516,6 +518,7 @@ fn is_native(adapter: &str) -> bool {
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
const XCODE_ATTACH: &str = "__openideaXcodeAttach";
|
||||
|
||||
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
|
||||
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
|
||||
@@ -1203,6 +1206,7 @@ impl DebugManager {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
@@ -1269,7 +1273,7 @@ impl DebugManager {
|
||||
parent: Option<DebugSessionId>,
|
||||
request: String,
|
||||
mut arguments: Value,
|
||||
spec: AdapterSpec,
|
||||
mut spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
@@ -1278,6 +1282,13 @@ impl DebugManager {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
}
|
||||
// Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the
|
||||
// system libraries it parsed, so the next attach skips that (#6665 E7).
|
||||
let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH));
|
||||
spec.shared = xcode_attach == Some(Value::Bool(true))
|
||||
&& adapter_name == "lldb-dap"
|
||||
&& request == "attach"
|
||||
&& arguments.get(RUN_LINK).is_some();
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Cache one lldb-dap server for successive attaches to Xcode runs (#6665 E7).
|
||||
//!
|
||||
//! An iOS app loads about 550 system libraries before its first line runs, and a fresh lldb-dap
|
||||
//! parses all of their symbol tables (about 5 million symbols) on each attach: 1.5 s on an idle
|
||||
//! Mac, far more under load. A server keeps the modules it parsed, so later sessions skip that
|
||||
//! and reach a breakpoint about as fast as Run reaches the same line. LLDB's own on-disk index
|
||||
//! cache would serve the first session too, but Xcode 27.1's lldb crashes on cached symbols.
|
||||
//!
|
||||
//! The server holds about 1 GB, so it ends once no session has been connected for
|
||||
//! [`IDLE_TIMEOUT`]; the next Debug then starts cold, as every Debug did before. A shell holds
|
||||
//! it and ends it when its stdin closes: when the IDE quits or crashes, when the server idles
|
||||
//! out, or when a server for another lldb-dap or environment replaces it.
|
||||
|
||||
use crate::adapter::{AdapterIo, AdapterSpec, adapter_path, pump_lines};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsString;
|
||||
use std::fs::Permissions;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::pin::Pin;
|
||||
use std::process::Stdio;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::UnixStream;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
/// What a server was started with: a session reuses it only when its own start would match.
|
||||
#[derive(PartialEq)]
|
||||
struct Key {
|
||||
binary: PathBuf,
|
||||
cwd: PathBuf,
|
||||
cwd_env: Vec<(OsString, Option<OsString>)>,
|
||||
}
|
||||
|
||||
struct Server {
|
||||
key: Key,
|
||||
socket: PathBuf,
|
||||
/// Recent stderr for the active connection.
|
||||
stderr: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
idle: Arc<Idle>,
|
||||
/// The shell holding the server; dropping it closes its stdin, which ends the server.
|
||||
_holder: Child,
|
||||
_socket_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
/// When the last session disconnected, or `None` while a session owns the server.
|
||||
type Idle = parking_lot::Mutex<Option<Instant>>;
|
||||
|
||||
type Slot = tokio::sync::Mutex<Option<Server>>;
|
||||
|
||||
static SERVER: LazyLock<Slot> = LazyLock::new(Default::default);
|
||||
|
||||
/// How long a server with no session stays up.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
/// How long a new server may take to listen.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// A connection to a running server; a server that does not take it is replaced.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Starts the server and ends it when the shell's stdin closes (`read` sees EOF) or when the
|
||||
/// server exits on its own (`wait`), so a `binary` without `--connection` fails at once.
|
||||
const HOLDER: &str = "exec 3<&0\n\
|
||||
\"$0\" --connection \"$1\" </dev/null >/dev/null &\n\
|
||||
server=$!\n\
|
||||
(read _ <&3; kill \"$server\" 2>/dev/null) &\n\
|
||||
watcher=$!\n\
|
||||
wait \"$server\"\n\
|
||||
result=$?\n\
|
||||
kill \"$watcher\" 2>/dev/null\n\
|
||||
wait \"$watcher\" 2>/dev/null\n\
|
||||
exit \"$result\"\n";
|
||||
|
||||
/// A connection to the shared server of `binary`, started first when there is none.
|
||||
pub async fn connect(spec: &AdapterSpec, binary: &Path) -> IdeResult<Option<AdapterIo>> {
|
||||
connect_to(&SERVER, spec, binary, IDLE_TIMEOUT).await
|
||||
}
|
||||
|
||||
async fn connect_to(
|
||||
slot: &'static Slot,
|
||||
spec: &AdapterSpec,
|
||||
binary: &Path,
|
||||
idle_timeout: Duration,
|
||||
) -> IdeResult<Option<AdapterIo>> {
|
||||
// The server gets the environment a per-session lldb-dap would: the project's (its Xcode's
|
||||
// `DEVELOPER_DIR`, from `cwd`), the adapter's search path and the spec's own variables.
|
||||
let mut cmd = Command::new("/bin/sh");
|
||||
cmd.current_dir(&spec.cwd);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
cmd.env("PATH", path);
|
||||
}
|
||||
cmd.envs(spec.env.iter().map(|(k, v)| (k, v)));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
|
||||
env.sort();
|
||||
let key = Key { binary: binary.to_path_buf(), cwd: spec.cwd.clone(), cwd_env: env };
|
||||
|
||||
let mut server = slot.lock().await;
|
||||
// A concurrent launch uses its own adapter. Replacing the cached process here would
|
||||
// disconnect the ongoing session, and concurrent sessions would share its stderr.
|
||||
if server.as_ref().is_some_and(|running| running.idle.lock().is_none()) {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(running) = server.as_ref().filter(|s| s.key == key)
|
||||
&& let Ok(Ok(stream)) = tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(&running.socket)).await
|
||||
{
|
||||
running.stderr.lock().clear();
|
||||
return Ok(Some(io(stream, running.stderr.clone(), lease(&running.idle))));
|
||||
}
|
||||
*server = None;
|
||||
let socket_dir = tempfile::Builder::new()
|
||||
.permissions(Permissions::from_mode(0o700))
|
||||
.tempdir()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot create the lldb-dap socket directory: {e}")))?;
|
||||
let socket = socket_dir.path().join("dap.sock");
|
||||
let mut uri = OsString::from("accept://");
|
||||
uri.push(&socket);
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.arg("-c").arg(HOLDER).arg(binary).arg(uri).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
let mut holder = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start lldb-dap: {e}")))?;
|
||||
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
if let Some(err) = holder.stderr.take() {
|
||||
pump_lines(err, spec.adapter.clone(), stderr.clone(), None);
|
||||
}
|
||||
let stream = connect_when_ready(&socket, &mut holder).await?;
|
||||
let idle = Arc::new(Idle::default());
|
||||
let first = lease(&idle);
|
||||
tokio::spawn(end_when_idle(slot, idle.clone(), idle_timeout));
|
||||
*server = Some(Server { key, socket, stderr: stderr.clone(), idle, _holder: holder, _socket_dir: socket_dir });
|
||||
Ok(Some(io(stream, stderr, first)))
|
||||
}
|
||||
|
||||
async fn connect_when_ready(socket: &Path, holder: &mut Child) -> IdeResult<UnixStream> {
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
let error = match UnixStream::connect(socket).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(error) => error,
|
||||
};
|
||||
if let Ok(Some(status)) = holder.try_wait() {
|
||||
return Err(IdeError::unavailable(format!("debug adapter exited before accepting connections ({status})")));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(IdeError::unavailable(format!("could not connect to lldb-dap: {error}")));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's hold on the server, released when its connection's both halves are gone.
|
||||
struct Lease(Arc<Idle>);
|
||||
|
||||
fn lease(idle: &Arc<Idle>) -> Arc<Lease> {
|
||||
*idle.lock() = None;
|
||||
Arc::new(Lease(idle.clone()))
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
*self.0.lock() = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the server in `slot` once no session has been connected to it for `timeout`; returns
|
||||
/// early when another server took its place.
|
||||
async fn end_when_idle(slot: &'static Slot, idle: Arc<Idle>, timeout: Duration) {
|
||||
loop {
|
||||
let since = *idle.lock();
|
||||
let wait = since.map_or(timeout, |at| (at + timeout).saturating_duration_since(Instant::now()));
|
||||
tokio::time::sleep(wait.max(Duration::from_millis(10))).await;
|
||||
let mut server = slot.lock().await;
|
||||
if !server.as_ref().is_some_and(|s| Arc::ptr_eq(&s.idle, &idle)) {
|
||||
return;
|
||||
}
|
||||
if idle.lock().is_some_and(|at| at.elapsed() >= timeout) {
|
||||
*server = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One half of a session's connection, holding the session's [`Lease`].
|
||||
struct Leased<T> {
|
||||
inner: T,
|
||||
_lease: Arc<Lease>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + Unpin> AsyncRead for Leased<T> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncWrite + Unpin> AsyncWrite for Leased<T> {
|
||||
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's streams. When the server dies the session's connection closes and the session
|
||||
/// ends with the server's last stderr lines, whichever session started it.
|
||||
fn io(stream: UnixStream, stderr: Arc<parking_lot::Mutex<Vec<String>>>, lease: Arc<Lease>) -> AdapterIo {
|
||||
let (r, w) = stream.into_split();
|
||||
AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(Leased { inner: r, _lease: lease.clone() }),
|
||||
writer: Box::new(Leased { inner: w, _lease: lease }),
|
||||
// The server is not the session's to stop.
|
||||
child: None,
|
||||
port: None,
|
||||
stderr,
|
||||
program_output: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
/// A stand-in for lldb-dap's server mode: it parses `--connection accept:///path`,
|
||||
/// records each start in `starts`, and answers every connection with its pid and the
|
||||
/// `DEVELOPER_DIR` it was started with.
|
||||
fn fake_lldb_dap(dir: &Path) -> Option<PathBuf> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::process::Command::new("python3").arg("-c").arg("").status().ok()?.success().then_some(())?;
|
||||
let path = dir.join("lldb-dap");
|
||||
let log = dir.join("starts");
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"#!/usr/bin/env python3\nimport os, socket, sys\n\
|
||||
assert sys.argv[1] == '--connection'\n\
|
||||
open({:?}, 'a').write('start\\n')\n\
|
||||
path = sys.argv[2][len('accept://'):]\n\
|
||||
s = socket.socket(socket.AF_UNIX)\n\
|
||||
s.bind(path); s.listen()\n\
|
||||
while True:\n c, _ = s.accept(); c.sendall(f\"{{os.getpid()}} {{os.environ.get('DEVELOPER_DIR', '')}}\".encode()); c.close()\n",
|
||||
log.to_string_lossy(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// The server's pid and `DEVELOPER_DIR`; the session's connection is closed afterwards.
|
||||
async fn server_of(io: AdapterIo) -> (i32, String) {
|
||||
let mut reader = io.reader;
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).await.unwrap();
|
||||
let (pid, dir) = text.split_once(' ').unwrap();
|
||||
(pid.parse().unwrap(), dir.to_owned())
|
||||
}
|
||||
|
||||
fn spec(dir: &Path) -> AdapterSpec {
|
||||
AdapterSpec {
|
||||
adapter: "lldb-dap".into(),
|
||||
command: "lldb-dap".into(),
|
||||
args: Vec::new(),
|
||||
transport: crate::adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: dir.to_path_buf(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot() -> &'static Slot {
|
||||
Box::leak(Box::default())
|
||||
}
|
||||
|
||||
fn starts(dir: &Path) -> usize {
|
||||
std::fs::read_to_string(dir.join("starts")).unwrap_or_default().lines().count()
|
||||
}
|
||||
|
||||
fn alive(pid: i32) -> bool {
|
||||
unsafe { libc::kill(pid, 0) == 0 }
|
||||
}
|
||||
|
||||
async fn until_gone(pid: i32) -> bool {
|
||||
for _ in 0..150 {
|
||||
if !alive(pid) {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
|
||||
/// Sessions share one server; it outlives them, and goes when its holder does (the IDE quits).
|
||||
#[tokio::test]
|
||||
async fn sessions_share_one_server_that_ends_with_its_holder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(first.child.is_none(), "a session must not stop the shared server");
|
||||
let first_stderr = first.stderr.clone();
|
||||
let (pid, _) = server_of(first).await;
|
||||
let second = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&second.stderr, &first_stderr), "every session sees the server's errors");
|
||||
assert_eq!(server_of(second).await.0, pid, "the second session reuses the server");
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
|
||||
// Another lldb-dap (the selected Xcode changed) gets its own server; the old one ends.
|
||||
let other_dir = tempfile::tempdir().unwrap();
|
||||
let other = fake_lldb_dap(other_dir.path()).unwrap();
|
||||
let (other_pid, _) =
|
||||
server_of(connect_to(slot, &spec(other_dir.path()), &other, LONG).await.unwrap().unwrap()).await;
|
||||
assert_ne!(other_pid, pid);
|
||||
assert!(until_gone(pid).await, "the replaced server is still running");
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(other_pid).await, "the server outlived its holder");
|
||||
}
|
||||
|
||||
/// The server gets the session's environment, and a session with another Xcode
|
||||
/// (`DEVELOPER_DIR`) does not reuse a server started for a different one.
|
||||
#[tokio::test]
|
||||
async fn a_server_is_reused_only_with_the_same_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let with = |xcode: &str| AdapterSpec { env: vec![("DEVELOPER_DIR".into(), xcode.into())], ..spec(dir.path()) };
|
||||
let (a, dir_a) = server_of(connect_to(slot, &with("/Xcode-a"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_a, "/Xcode-a");
|
||||
let (b, dir_b) = server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_b, "/Xcode-b");
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await.0, b);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(b).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_attaches_leave_the_active_server_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
for cwd in [dir.path(), other.path()] {
|
||||
assert!(connect_to(slot, &spec(cwd), &binary, LONG).await.unwrap().is_none());
|
||||
}
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
let (first_pid, _) = server_of(first).await;
|
||||
assert!(alive(first_pid));
|
||||
|
||||
let replacement = connect_to(slot, &spec(other.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
let (replacement_pid, _) = server_of(replacement).await;
|
||||
assert_ne!(first_pid, replacement_pid, "changing only the working directory replaces an idle server");
|
||||
assert!(until_gone(first_pid).await);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(replacement_pid).await);
|
||||
}
|
||||
|
||||
/// The server ends once no session has been connected for the idle timeout; a connected
|
||||
/// session, or a new one within the timeout, keeps it.
|
||||
#[tokio::test]
|
||||
async fn an_idle_server_ends_and_the_next_session_starts_another() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let idle = Duration::from_millis(400);
|
||||
let held = connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap();
|
||||
tokio::time::sleep(idle * 2).await;
|
||||
let (pid, _) = server_of(held).await;
|
||||
assert!(alive(pid), "a connected session keeps the server");
|
||||
|
||||
tokio::time::sleep(idle / 4).await;
|
||||
assert_eq!(server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await.0, pid);
|
||||
assert_eq!(starts(dir.path()), 1, "a session within the timeout reuses the server");
|
||||
|
||||
assert!(until_gone(pid).await, "the idle server is still running");
|
||||
let (next, _) = server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await;
|
||||
assert_ne!(next, pid);
|
||||
assert_eq!(starts(dir.path()), 2);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(next).await);
|
||||
}
|
||||
|
||||
/// An lldb-dap without server mode fails at once, so the caller can start it as before.
|
||||
#[tokio::test]
|
||||
async fn an_lldb_dap_without_server_mode_fails_fast() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("lldb-dap");
|
||||
std::fs::write(&binary, "#!/bin/sh\necho \"unknown option $1\" >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let e = connect_to(slot(), &spec(dir.path()), &binary, LONG).await.err().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(e.message.contains("exited before accepting connections"), "{}", e.message);
|
||||
}
|
||||
}
|
||||
@@ -4044,6 +4044,52 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug's attach goes to the shared lldb-dap server, which keeps the system libraries
|
||||
/// parsed by earlier sessions (#6665 E7); other sessions start their own adapter.
|
||||
#[tokio::test]
|
||||
async fn only_an_lldb_dap_attach_to_a_run_shares_the_server() {
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
shared: Arc<parking_lot::Mutex<Vec<bool>>>,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.shared.lock().push(spec.shared);
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let shared: Arc<parking_lot::Mutex<Vec<bool>>> = Arc::default();
|
||||
let launcher = CaptureLauncher {
|
||||
inner: FakeLauncher { log: Arc::default(), script: Script::default() },
|
||||
shared: shared.clone(),
|
||||
};
|
||||
let manager = DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let session = |adapter: &str, request: &str, linked: bool, xcode: bool| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: request.into(),
|
||||
extra_json: Some(
|
||||
if linked {
|
||||
json!({ RUN_LINK: 7, XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
} else {
|
||||
json!({ XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
..config()
|
||||
};
|
||||
for launch in [
|
||||
session("lldb-dap", "attach", true, true),
|
||||
session("lldb-dap", "attach", true, false),
|
||||
session("lldb-dap", "attach", false, true),
|
||||
session("lldb-dap", "launch", true, true),
|
||||
session("debugpy", "attach", true, true),
|
||||
] {
|
||||
let (owner, _) = recording_owner("main");
|
||||
manager.start(launch, owner).await.unwrap();
|
||||
}
|
||||
assert_eq!(*shared.lock(), [true, false, false, false, false]);
|
||||
}
|
||||
|
||||
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
|
||||
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
|
||||
#[tokio::test]
|
||||
|
||||
@@ -52,6 +52,7 @@ test("Debug launches the app suspended and attaches lldb-dap to its pid once", a
|
||||
runConfig: config,
|
||||
show: false,
|
||||
extra: {
|
||||
__openideaXcodeAttach: true,
|
||||
sourceMap: [
|
||||
["/tmp", "/private/tmp"],
|
||||
["/var", "/private/var"],
|
||||
|
||||
@@ -42,7 +42,7 @@ export async function debugXcodeApp(config: RunConfig, show?: boolean): Promise<
|
||||
process: runId,
|
||||
runConfig: config,
|
||||
show,
|
||||
extra: { sourceMap: XCODE_SOURCE_MAP },
|
||||
extra: { sourceMap: XCODE_SOURCE_MAP, __openideaXcodeAttach: true },
|
||||
});
|
||||
};
|
||||
const session = await startRun(config, undefined, undefined, {
|
||||
|
||||
Reference in new issue
Заблокувати користувача