diff --git a/crates/languages/src/rust.rs b/crates/languages/src/rust.rs index dfe8075bce7..afc88ee1006 100644 --- a/crates/languages/src/rust.rs +++ b/crates/languages/src/rust.rs @@ -73,12 +73,6 @@ impl RustLspAdapter { const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer"); -#[cfg(target_os = "linux")] -enum LibcType { - Gnu, - Musl, -} - impl RustLspAdapter { fn convert_rust_analyzer_schema(raw_schema: &serde_json::Value) -> serde_json::Value { let Some(schema_array) = raw_schema.as_array() else { @@ -142,59 +136,11 @@ impl RustLspAdapter { }) } - #[cfg(target_os = "linux")] - async fn determine_libc_type() -> LibcType { - use futures::pin_mut; - - async fn from_ldd_version() -> Option { - use util::command::new_command; - - let ldd_output = new_command("ldd").arg("--version").output().await.ok()?; - let ldd_version = String::from_utf8_lossy(&ldd_output.stdout); - - if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") { - Some(LibcType::Gnu) - } else if ldd_version.contains("musl") { - Some(LibcType::Musl) - } else { - None - } - } - - if let Some(libc_type) = from_ldd_version().await { - return libc_type; - } - - let Ok(dir_entries) = smol::fs::read_dir("/lib").await else { - // defaulting to gnu because nix doesn't have /lib files due to not following FHS - return LibcType::Gnu; - }; - let dir_entries = dir_entries.filter_map(async move |e| e.ok()); - pin_mut!(dir_entries); - - let mut has_musl = false; - let mut has_gnu = false; - - while let Some(entry) = dir_entries.next().await { - let file_name = entry.file_name(); - let file_name = file_name.to_string_lossy(); - if file_name.starts_with("ld-musl-") { - has_musl = true; - } else if file_name.starts_with("ld-linux-") { - has_gnu = true; - } - } - - match (has_musl, has_gnu) { - (true, _) => LibcType::Musl, - (_, true) => LibcType::Gnu, - _ => LibcType::Gnu, - } - } - #[cfg(target_os = "linux")] async fn build_arch_server_name_linux() -> String { - let libc = match Self::determine_libc_type().await { + use util::libc_type::{LibcType, host_libc_type}; + + let libc = match host_libc_type().await { LibcType::Musl => "musl", LibcType::Gnu => "gnu", }; diff --git a/crates/project/src/agent_registry_store.rs b/crates/project/src/agent_registry_store.rs index 7ab885daba1..20647be10a2 100644 --- a/crates/project/src/agent_registry_store.rs +++ b/crates/project/src/agent_registry_store.rs @@ -381,7 +381,7 @@ async fn build_registry_agents( fs.create_dir(&icons_dir).await?; } - let current_platform = current_platform_key(); + let current_platform_keys = current_platform_keys().await; let icon_paths = resolve_icon_paths( &index.agents, &icons_dir, @@ -424,9 +424,9 @@ async fn build_registry_agents( ); } - let supports_current_platform = current_platform - .as_ref() - .is_some_and(|platform| targets.contains_key(*platform)); + let supports_current_platform = current_platform_keys + .iter() + .any(|platform_key| targets.contains_key(*platform_key)); Some(RegistryBinaryAgent { metadata: metadata.clone(), @@ -584,43 +584,34 @@ fn resolve_icon_url(entry: &RegistryEntry) -> Option { )) } -fn current_platform_key() -> Option<&'static str> { - let os = if cfg!(target_os = "macos") { - "darwin" - } else if cfg!(target_os = "linux") { - "linux" - } else if cfg!(target_os = "windows") { - "windows" - } else { - return None; +/// Registry platform keys for the current host, in order of preference. +pub(crate) async fn current_platform_keys() -> &'static [&'static str] { + // The probe spawns a process and reads the real filesystem, which the + // deterministic test scheduler can't drive, so tests assume glibc. + let prefers_musl = cfg_select! { + all(target_os = "linux", not(any(test, feature = "test-support"))) => { + util::libc_type::host_libc_type().await == util::libc_type::LibcType::Musl + } + _ => false, }; - let arch = if cfg!(target_arch = "aarch64") { - "aarch64" - } else if cfg!(target_arch = "x86_64") { - "x86_64" - } else { - return None; - }; + platform_keys(std::env::consts::OS, std::env::consts::ARCH, prefers_musl) +} - Some(match os { - "darwin" => match arch { - "aarch64" => "darwin-aarch64", - "x86_64" => "darwin-x86_64", - _ => return None, - }, - "linux" => match arch { - "aarch64" => "linux-aarch64", - "x86_64" => "linux-x86_64", - _ => return None, - }, - "windows" => match arch { - "aarch64" => "windows-aarch64", - "x86_64" => "windows-x86_64", - _ => return None, - }, - _ => return None, - }) +fn platform_keys(os: &str, arch: &str, prefers_musl: bool) -> &'static [&'static str] { + match (os, arch, prefers_musl) { + ("macos", "aarch64", _) => &["darwin-aarch64"], + ("macos", "x86_64", _) => &["darwin-x86_64"], + ("windows", "aarch64", _) => &["windows-aarch64"], + ("windows", "x86_64", _) => &["windows-x86_64"], + ("linux", "aarch64", false) => &["linux-aarch64"], + ("linux", "x86_64", false) => &["linux-x86_64"], + // Not every agent publishes a musl build, and the glibc one may still + // run through a compatibility layer, so keep it as a fallback. + ("linux", "aarch64", true) => &["linux-aarch64-musl", "linux-aarch64"], + ("linux", "x86_64", true) => &["linux-x86_64-musl", "linux-x86_64"], + _ => &[], + } } fn registry_cache_dir() -> PathBuf { @@ -683,3 +674,25 @@ struct RegistryNpxDistribution { #[serde(default)] env: HashMap, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_platform_keys() { + assert_eq!(platform_keys("macos", "aarch64", false), ["darwin-aarch64"]); + assert_eq!( + platform_keys("windows", "x86_64", false), + ["windows-x86_64"] + ); + assert_eq!(platform_keys("linux", "x86_64", false), ["linux-x86_64"]); + assert_eq!( + platform_keys("linux", "aarch64", true), + ["linux-aarch64-musl", "linux-aarch64"] + ); + assert_eq!(platform_keys("macos", "aarch64", true), ["darwin-aarch64"]); + assert!(platform_keys("freebsd", "x86_64", false).is_empty()); + assert!(platform_keys("linux", "riscv64", false).is_empty()); + } +} diff --git a/crates/project/src/agent_server_store.rs b/crates/project/src/agent_server_store.rs index 794cb3ad857..8f609b946d8 100644 --- a/crates/project/src/agent_server_store.rs +++ b/crates/project/src/agent_server_store.rs @@ -15,6 +15,7 @@ use gpui::{ TaskExt, }; use http_client::HttpClient; +use itertools::Itertools as _; use node_runtime::NodeRuntime; use percent_encoding::percent_decode_str; use remote::RemoteClient; @@ -1176,36 +1177,18 @@ impl ExternalAgentServer for LocalRegistryArchiveAgent { let dir = installation_dir; fs.create_dir(&dir).await?; - let os = if cfg!(target_os = "macos") { - "darwin" - } else if cfg!(target_os = "linux") { - "linux" - } else if cfg!(target_os = "windows") { - "windows" - } else { - anyhow::bail!("unsupported OS"); - }; - - let arch = if cfg!(target_arch = "aarch64") { - "aarch64" - } else if cfg!(target_arch = "x86_64") { - "x86_64" - } else { - anyhow::bail!("unsupported architecture"); - }; - - let platform_key = format!("{}-{}", os, arch); - let target_config = targets.get(&platform_key).with_context(|| { - format!( - "no target specified for platform '{}'. Available platforms: {}", - platform_key, - targets - .keys() - .map(|k| k.as_str()) - .collect::>() - .join(", ") - ) - })?; + let platform_keys = crate::agent_registry_store::current_platform_keys().await; + anyhow::ensure!(!platform_keys.is_empty(), "unsupported platform"); + let target_config = platform_keys + .iter() + .find_map(|platform_key| targets.get(*platform_key)) + .with_context(|| { + format!( + "no target specified for platform '{}'. Available platforms: {}", + platform_keys.join("' or '"), + targets.keys().join(", ") + ) + })?; env.extend(target_config.env.clone()); env.extend(extra_env); diff --git a/crates/util/src/libc_type.rs b/crates/util/src/libc_type.rs new file mode 100644 index 00000000000..3e76e3a0e7b --- /dev/null +++ b/crates/util/src/libc_type.rs @@ -0,0 +1,79 @@ +use crate::command::new_command; +use futures::StreamExt as _; +use smol::lock::OnceCell; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LibcType { + Gnu, + Musl, +} + +/// Detects the libc of the host system, which is not necessarily the libc this +/// binary was built against: the remote server is statically linked with musl +/// and runs on glibc hosts, so `cfg!(target_env = "musl")` can't be used to pick +/// binaries to download. +pub async fn host_libc_type() -> LibcType { + static HOST_LIBC_TYPE: OnceCell = OnceCell::new(); + *HOST_LIBC_TYPE.get_or_init(detect_host_libc_type).await +} + +async fn detect_host_libc_type() -> LibcType { + if let Some(libc_type) = libc_type_from_ldd().await { + return libc_type; + } + + let Ok(mut dir_entries) = smol::fs::read_dir("/lib").await else { + // defaulting to gnu because nix doesn't have /lib files due to not following FHS + return LibcType::Gnu; + }; + + while let Some(entry) = dir_entries.next().await { + let Ok(entry) = entry else { + continue; + }; + if entry.file_name().to_string_lossy().starts_with("ld-musl-") { + return LibcType::Musl; + } + } + + LibcType::Gnu +} + +async fn libc_type_from_ldd() -> Option { + let output = new_command("ldd").arg("--version").output().await.ok()?; + // musl's ldd prints its version to stderr and exits with a failure status. + parse_ldd_version(&String::from_utf8_lossy(&output.stdout)) + .or_else(|| parse_ldd_version(&String::from_utf8_lossy(&output.stderr))) +} + +fn parse_ldd_version(ldd_version: &str) -> Option { + if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") { + Some(LibcType::Gnu) + } else if ldd_version.contains("musl") { + Some(LibcType::Musl) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_ldd_version() { + assert_eq!( + parse_ldd_version("ldd (Ubuntu GLIBC 2.39-0ubuntu8.4) 2.39"), + Some(LibcType::Gnu) + ); + assert_eq!( + parse_ldd_version("ldd (GNU libc) 2.40"), + Some(LibcType::Gnu) + ); + assert_eq!( + parse_ldd_version("musl libc (x86_64)\nVersion 1.2.5\n"), + Some(LibcType::Musl) + ); + assert_eq!(parse_ldd_version(""), None); + } +} diff --git a/crates/util/src/util.rs b/crates/util/src/util.rs index df08f0420d7..e8eae85710a 100644 --- a/crates/util/src/util.rs +++ b/crates/util/src/util.rs @@ -7,6 +7,8 @@ pub mod archive; pub mod command; #[cfg(not(target_family = "wasm"))] pub mod fs; +#[cfg(target_os = "linux")] +pub mod libc_type; #[cfg(not(target_family = "wasm"))] pub mod process; #[cfg(not(target_family = "wasm"))]