Skip to main content

aft_base/
developer_tools.rs

1//! Keep AFT from running Apple's developer-tool shims on a Mac without them.
2//!
3//! On macOS, `/usr/bin/git` (and `clangd`, `sourcekit-lsp`, `python3`, `make`,
4//! `xcrun`, ...) is not the tool itself but a small launcher linked against
5//! `/usr/lib/libxcselect.dylib`. The launcher looks up the active developer
6//! directory and runs the real tool from it. When no developer directory is
7//! installed it prints "xcode-select: note: No developer tools were found,
8//! requesting install" and opens the "Install Command Line Developer Tools"
9//! dialog in the user's GUI session, once per invocation. So AFT must never
10//! spawn a launcher on such a machine, not even with `--version`.
11//!
12//! The launcher's lookup order is documented in xcode-select(1): the
13//! `DEVELOPER_DIR` environment variable overrides everything; otherwise the
14//! system-wide selection written by `xcode-select --switch` (the
15//! `/var/db/xcode_select_link` symlink) is used; with no selection the
16//! defaults are `/Applications/Xcode.app/Contents/Developer` and then
17//! `/Library/Developer/CommandLineTools`. `xcode-select -p` reports that same
18//! state and is safe (with no tools it prints an error and exits non-zero,
19//! without the dialog). Reading those directories answers the common case
20//! without spawning anything, so this module does that first and asks
21//! `xcode-select -p` only when no known directory holds the tools.
22//!
23//! The decision is made once per process. Only a launcher is ever refused: a
24//! user whose PATH finds a real git first (Homebrew, MacPorts, Nix) keeps
25//! every git feature even without the Xcode tools.
26
27use std::collections::HashMap;
28use std::ffi::OsStr;
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex, OnceLock};
31
32/// Test seam, read at runtime because integration tests drive the production
33/// binary: `absent` or `present` replaces the developer-directory lookup.
34const DEVELOPER_TOOLS_OVERRIDE_ENV: &str = "AFT_TEST_DEVELOPER_TOOLS";
35/// Test seam: a PATH-style list of directories whose executables are treated
36/// as Apple launchers (instead of `/usr/bin` binaries linking libxcselect).
37const LAUNCHER_DIRS_OVERRIDE_ENV: &str = "AFT_TEST_XCODE_LAUNCHER_DIRS";
38
39/// Every Apple launcher names this library in its load commands; ordinary
40/// `/usr/bin` programs such as `ssh` do not.
41const XCSELECT_LIBRARY_MARKER: &[u8] = b"/usr/lib/libxcselect.dylib";
42
43/// Whether AFT may run `git` in this process.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub enum GitAvailability {
46    /// `git` resolves to a real binary, to Apple's launcher on a Mac that has
47    /// developer tools, or to nothing (spawns then fail the ordinary way).
48    Usable,
49    /// `git` resolves to Apple's launcher and no developer tools exist, so
50    /// running it would open the install dialog.
51    MissingDeveloperTools { launcher: PathBuf },
52}
53
54/// The user-facing explanation shown by status when git features are off.
55pub const MISSING_DEVELOPER_TOOLS_REASON: &str =
56    "git features are off: macOS developer tools are not installed, and running \
57     /usr/bin/git would open Apple's install dialog. Install them with \
58     `xcode-select --install`, or put another git (for example Homebrew's) on PATH, \
59     then restart AFT.";
60
61#[derive(Clone, Debug, PartialEq, Eq)]
62struct LauncherStamp {
63    len: u64,
64    modified: Option<std::time::SystemTime>,
65    #[cfg(unix)]
66    identity: (u64, u64, i64, i64, u32),
67}
68
69impl LauncherStamp {
70    fn from_metadata(metadata: &std::fs::Metadata) -> Self {
71        #[cfg(unix)]
72        use std::os::unix::fs::MetadataExt;
73        Self {
74            len: metadata.len(),
75            modified: metadata.modified().ok(),
76            #[cfg(unix)]
77            identity: (
78                metadata.dev(),
79                metadata.ino(),
80                metadata.ctime(),
81                metadata.ctime_nsec(),
82                metadata.mode(),
83            ),
84        }
85    }
86}
87
88type LauncherCache = Arc<Mutex<HashMap<PathBuf, (LauncherStamp, bool)>>>;
89
90/// Inputs to the launcher decision, separated from the process so tests can
91/// inject a "no developer tools" machine and a fake launcher directory.
92#[derive(Clone, Debug)]
93pub struct Detector {
94    launcher_dirs: Vec<PathBuf>,
95    /// When true, a file in a launcher directory only counts as a launcher if
96    /// it links libxcselect. Injected launcher directories skip this so a
97    /// test can use a shell script.
98    require_xcselect_marker: bool,
99    developer_tools_present: bool,
100    launcher_cache: LauncherCache,
101    #[cfg(any(test, feature = "test-support"))]
102    marker_reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
103}
104
105impl Detector {
106    /// Build a detector from explicit inputs; every file in `launcher_dirs`
107    /// counts as a launcher.
108    pub fn new(launcher_dirs: Vec<PathBuf>, developer_tools_present: bool) -> Self {
109        Self {
110            launcher_dirs: canonical_dirs(launcher_dirs),
111            require_xcselect_marker: false,
112            developer_tools_present,
113            launcher_cache: Default::default(),
114            #[cfg(any(test, feature = "test-support"))]
115            marker_reads: Default::default(),
116        }
117    }
118
119    fn from_process() -> Self {
120        let override_dirs = std::env::var_os(LAUNCHER_DIRS_OVERRIDE_ENV)
121            .filter(|value| !value.is_empty())
122            .map(|value| std::env::split_paths(&value).collect::<Vec<_>>());
123        let override_tools = std::env::var(DEVELOPER_TOOLS_OVERRIDE_ENV)
124            .ok()
125            .and_then(|value| match value.as_str() {
126                "absent" => Some(false),
127                "present" => Some(true),
128                _ => None,
129            });
130
131        let (launcher_dirs, require_xcselect_marker) = match override_dirs {
132            Some(dirs) => (canonical_dirs(dirs), false),
133            None if cfg!(target_os = "macos") => (vec![PathBuf::from("/usr/bin")], true),
134            None => (Vec::new(), false),
135        };
136        // Only look at the developer directories when a launcher could matter;
137        // on other platforms the answer is irrelevant.
138        let developer_tools_present = override_tools.unwrap_or_else(|| {
139            launcher_dirs.is_empty()
140                || macos_developer_tools_present(DeveloperDirProbe::system())
141                || xcode_select_reports_developer_dir()
142        });
143        Self {
144            launcher_dirs,
145            require_xcselect_marker,
146            developer_tools_present,
147            launcher_cache: Default::default(),
148            #[cfg(any(test, feature = "test-support"))]
149            marker_reads: Default::default(),
150        }
151    }
152
153    pub fn developer_tools_present(&self) -> bool {
154        self.developer_tools_present
155    }
156
157    /// True when `path` is an Apple launcher that would open the install
158    /// dialog if run. Reuses marker reads while file metadata is unchanged;
159    /// never executes the candidate.
160    pub fn is_unusable_launcher(&self, path: &Path) -> bool {
161        self.is_unusable_launcher_with_reader(path, |path| std::fs::read(path))
162    }
163
164    fn is_unusable_launcher_with_reader(
165        &self,
166        path: &Path,
167        read: impl FnOnce(&Path) -> std::io::Result<Vec<u8>>,
168    ) -> bool {
169        if self.developer_tools_present || self.launcher_dirs.is_empty() {
170            return false;
171        }
172        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
173        let in_launcher_dir = canonical
174            .parent()
175            .is_some_and(|parent| self.launcher_dirs.iter().any(|dir| dir == parent));
176        if !in_launcher_dir {
177            return false;
178        }
179        if !self.require_xcselect_marker {
180            return true;
181        }
182        let Ok(metadata) = std::fs::metadata(&canonical) else {
183            return true;
184        };
185        let stamp = LauncherStamp::from_metadata(&metadata);
186        let mut cache = self
187            .launcher_cache
188            .lock()
189            .unwrap_or_else(|error| error.into_inner());
190        if let Some((cached_stamp, decision)) = cache.get(&canonical) {
191            if cached_stamp == &stamp {
192                return *decision;
193            }
194        }
195        #[cfg(any(test, feature = "test-support"))]
196        self.marker_reads
197            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
198        let bytes = match read(&canonical) {
199            Ok(bytes) => bytes,
200            // Refuse an unreadable candidate because it may open the install
201            // dialog, but retry transient errors instead of caching a guess.
202            Err(_) => return true,
203        };
204        let decision = contains_subslice(&bytes, XCSELECT_LIBRARY_MARKER);
205        cache.insert(canonical, (stamp, decision));
206        decision
207    }
208
209    /// Decide whether `git` found on `path_var` may run.
210    pub fn git_availability(&self, path_var: &OsStr) -> GitAvailability {
211        if self.developer_tools_present || self.launcher_dirs.is_empty() {
212            return GitAvailability::Usable;
213        }
214        match first_on_path(path_var, "git") {
215            Some(git) if self.is_unusable_launcher(&git) => {
216                GitAvailability::MissingDeveloperTools { launcher: git }
217            }
218            _ => GitAvailability::Usable,
219        }
220    }
221}
222
223fn canonical_dirs(dirs: Vec<PathBuf>) -> Vec<PathBuf> {
224    dirs.into_iter()
225        .filter(|dir| !dir.as_os_str().is_empty())
226        .map(|dir| std::fs::canonicalize(&dir).unwrap_or(dir))
227        .collect()
228}
229
230fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
231    !needle.is_empty()
232        && haystack
233            .windows(needle.len())
234            .any(|window| window == needle)
235}
236
237/// First executable `binary` on a PATH-style list, the one a spawn would run.
238fn first_on_path(path_var: &OsStr, binary: &str) -> Option<PathBuf> {
239    std::env::split_paths(path_var)
240        .filter(|dir| !dir.as_os_str().is_empty())
241        .find_map(|dir| crate::tool_path::probe_tool_in_dir(&dir, binary))
242}
243
244/// Where the launcher looks for a developer directory, in its own order.
245#[derive(Clone, Debug)]
246pub struct DeveloperDirProbe {
247    pub developer_dir_env: Option<PathBuf>,
248    pub selection_link: PathBuf,
249    pub defaults: Vec<PathBuf>,
250}
251
252impl DeveloperDirProbe {
253    fn system() -> Self {
254        Self {
255            developer_dir_env: crate::environment::non_empty_os_var("DEVELOPER_DIR")
256                .map(PathBuf::from),
257            selection_link: PathBuf::from("/var/db/xcode_select_link"),
258            defaults: vec![
259                PathBuf::from("/Applications/Xcode.app/Contents/Developer"),
260                PathBuf::from("/Library/Developer/CommandLineTools"),
261            ],
262        }
263    }
264}
265
266/// A developer directory counts only if it holds the tools (`usr/bin`); an
267/// empty leftover directory would still leave the launcher prompting.
268fn is_developer_dir(dir: &Path) -> bool {
269    dir.join("usr").join("bin").is_dir()
270}
271
272/// Follow the launcher's lookup order without running anything.
273pub fn macos_developer_tools_present(probe: DeveloperDirProbe) -> bool {
274    if let Some(dir) = probe.developer_dir_env {
275        // DEVELOPER_DIR replaces the lookup entirely, so a bad value is not
276        // rescued by an installed default.
277        return is_developer_dir(&dir);
278    }
279    if let Ok(selected) = std::fs::canonicalize(&probe.selection_link) {
280        if is_developer_dir(&selected) {
281            return true;
282        }
283    }
284    probe.defaults.iter().any(|dir| is_developer_dir(dir))
285}
286
287/// Second opinion for a Mac where none of the known directories hold the
288/// tools: Xcode may live under another name (say `Xcode-beta.app`) that the
289/// launcher still finds. `xcode-select -p` answers from the same lookup and,
290/// unlike the launchers, only prints an error and exits non-zero when nothing
291/// is installed; it never opens the install dialog. It runs at most once per
292/// process, and only on a Mac that looks like it has no tools.
293fn xcode_select_reports_developer_dir() -> bool {
294    if !cfg!(target_os = "macos") {
295        return false;
296    }
297    std::process::Command::new("/usr/bin/xcode-select")
298        .arg("-p")
299        .stdin(std::process::Stdio::null())
300        .stderr(std::process::Stdio::null())
301        .output()
302        .is_ok_and(|output| {
303            output.status.success()
304                && is_developer_dir(Path::new(String::from_utf8_lossy(&output.stdout).trim()))
305        })
306}
307
308fn process_detector() -> &'static Detector {
309    static DETECTOR: OnceLock<Detector> = OnceLock::new();
310    DETECTOR.get_or_init(Detector::from_process)
311}
312
313/// The once-per-process git decision. Logs once when git is turned off.
314pub fn git_availability() -> &'static GitAvailability {
315    static GIT: OnceLock<GitAvailability> = OnceLock::new();
316    GIT.get_or_init(|| {
317        let availability =
318            process_detector().git_availability(crate::effective_path::effective_path());
319        if let GitAvailability::MissingDeveloperTools { launcher } = &availability {
320            log::warn!(
321                "git disabled for this process: {} is Apple's developer-tools launcher and no \
322                 developer tools are installed; running it would open the install dialog. \
323                 Git-backed features use their non-git fallbacks.",
324                launcher.display()
325            );
326        }
327        availability
328    })
329}
330
331/// Whether engine code may spawn `git`. A disabled tool cannot determine whether
332/// a directory is a repository or which index data belongs to it. Preserve that
333/// uncertainty rather than using it to choose another identity or delete data.
334pub fn git_usable() -> bool {
335    #[cfg(any(test, feature = "test-support"))]
336    if let Some(usable) = TEST_GIT_USABLE.with(|value| value.get()) {
337        return usable;
338    }
339    matches!(git_availability(), GitAvailability::Usable)
340}
341
342#[cfg(any(test, feature = "test-support"))]
343thread_local! {
344    static TEST_GIT_USABLE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
345}
346
347#[cfg(any(test, feature = "test-support"))]
348pub fn with_git_usable_for_test<T>(usable: bool, run: impl FnOnce() -> T) -> T {
349    struct Reset(Option<bool>);
350    impl Drop for Reset {
351        fn drop(&mut self) {
352            TEST_GIT_USABLE.with(|value| value.set(self.0));
353        }
354    }
355    let _reset = Reset(TEST_GIT_USABLE.with(|value| value.replace(Some(usable))));
356    run()
357}
358
359/// Status payload describing whether git features are on.
360pub fn git_status_json() -> serde_json::Value {
361    match git_availability() {
362        GitAvailability::Usable => serde_json::json!({ "available": true }),
363        GitAvailability::MissingDeveloperTools { launcher } => serde_json::json!({
364            "available": false,
365            "reason": "macos_developer_tools_missing",
366            "message": MISSING_DEVELOPER_TOOLS_REASON,
367            "launcher": launcher.display().to_string(),
368        }),
369    }
370}
371
372/// Whether a resolved tool path (LSP server, formatter) is an Apple launcher
373/// that must not run on this machine. Callers treat it as not installed.
374pub fn is_unusable_launcher(path: &Path) -> bool {
375    process_detector().is_unusable_launcher(path)
376}
377
378#[cfg(all(test, unix))]
379mod tests {
380    use super::*;
381
382    #[test]
383    fn launcher_read_error_is_retried_without_metadata_changes() {
384        let dir = tempfile::tempdir().unwrap();
385        let tool = dir.path().join("git");
386        std::fs::write(&tool, b"a real tool without the launcher marker").unwrap();
387        let mut detector = Detector::new(vec![dir.path().to_path_buf()], false);
388        detector.require_xcselect_marker = true;
389        let before = LauncherStamp::from_metadata(&std::fs::metadata(&tool).unwrap());
390
391        assert!(detector.is_unusable_launcher_with_reader(&tool, |_| {
392            Err(std::io::Error::from_raw_os_error(libc::EMFILE))
393        }));
394        assert_eq!(
395            before,
396            LauncherStamp::from_metadata(&std::fs::metadata(&tool).unwrap())
397        );
398        assert!(!detector.is_unusable_launcher(&tool));
399        assert_eq!(
400            detector
401                .marker_reads
402                .load(std::sync::atomic::Ordering::Relaxed),
403            2
404        );
405        assert!(!detector.is_unusable_launcher(&tool));
406        assert_eq!(
407            detector
408                .marker_reads
409                .load(std::sync::atomic::Ordering::Relaxed),
410            2
411        );
412    }
413
414    #[test]
415    fn launcher_marker_is_memoized_and_invalidated_by_file_replacement() {
416        let dir = tempfile::tempdir().unwrap();
417        let launcher = dir.path().join("git");
418        std::fs::write(&launcher, XCSELECT_LIBRARY_MARKER).unwrap();
419        let mut detector = Detector::new(vec![dir.path().to_path_buf()], false);
420        detector.require_xcselect_marker = true;
421        assert!(detector.is_unusable_launcher(&launcher));
422        assert!(detector.clone().is_unusable_launcher(&launcher));
423        assert_eq!(
424            detector
425                .marker_reads
426                .load(std::sync::atomic::Ordering::Relaxed),
427            1
428        );
429
430        let replacement = dir.path().join("replacement");
431        std::fs::write(&replacement, vec![b'x'; XCSELECT_LIBRARY_MARKER.len()]).unwrap();
432        // Equal size and mtime must not hide a replacement inode from the cache.
433        let original_time = std::fs::metadata(&launcher).unwrap().modified().unwrap();
434        std::fs::File::options()
435            .write(true)
436            .open(&replacement)
437            .unwrap()
438            .set_modified(original_time)
439            .unwrap();
440        std::fs::remove_file(&launcher).unwrap();
441        std::fs::rename(&replacement, &launcher).unwrap();
442        assert!(!detector.is_unusable_launcher(&launcher));
443        assert!(!detector.is_unusable_launcher(&launcher));
444        assert_eq!(
445            detector
446                .marker_reads
447                .load(std::sync::atomic::Ordering::Relaxed),
448            2
449        );
450    }
451
452    fn executable(path: &Path, body: &str) {
453        crate::executable_cache::write_executable(path, body.as_bytes()).unwrap();
454    }
455
456    #[test]
457    fn launcher_git_without_developer_tools_is_refused() {
458        let temp = tempfile::tempdir().unwrap();
459        let launchers = temp.path().join("usr-bin");
460        std::fs::create_dir_all(&launchers).unwrap();
461        executable(&launchers.join("git"), "#!/bin/sh\nexit 1\n");
462
463        let detector = Detector::new(vec![launchers.clone()], false);
464        assert_eq!(
465            detector.git_availability(launchers.as_os_str()),
466            GitAvailability::MissingDeveloperTools {
467                launcher: launchers.join("git")
468            }
469        );
470        // The same launcher is fine once developer tools exist.
471        let with_tools = Detector::new(vec![launchers.clone()], true);
472        assert_eq!(
473            with_tools.git_availability(launchers.as_os_str()),
474            GitAvailability::Usable
475        );
476    }
477
478    #[test]
479    fn real_git_earlier_on_path_wins_over_the_launcher() {
480        let temp = tempfile::tempdir().unwrap();
481        let launchers = temp.path().join("usr-bin");
482        let homebrew = temp.path().join("homebrew-bin");
483        std::fs::create_dir_all(&launchers).unwrap();
484        std::fs::create_dir_all(&homebrew).unwrap();
485        executable(&launchers.join("git"), "#!/bin/sh\nexit 1\n");
486        executable(&homebrew.join("git"), "#!/bin/sh\nexit 0\n");
487
488        let detector = Detector::new(vec![launchers.clone()], false);
489        let path = std::env::join_paths([&homebrew, &launchers]).unwrap();
490        assert_eq!(detector.git_availability(&path), GitAvailability::Usable);
491        // Order matters: the launcher first is still refused.
492        let reversed = std::env::join_paths([&launchers, &homebrew]).unwrap();
493        assert!(matches!(
494            detector.git_availability(&reversed),
495            GitAvailability::MissingDeveloperTools { .. }
496        ));
497    }
498
499    #[test]
500    fn marker_check_keeps_ordinary_binaries_in_the_launcher_dir() {
501        let temp = tempfile::tempdir().unwrap();
502        let dir = temp.path().join("usr-bin");
503        std::fs::create_dir_all(&dir).unwrap();
504        executable(&dir.join("ssh"), "plain program\n");
505        executable(&dir.join("clangd"), "...\0/usr/lib/libxcselect.dylib\0...");
506        let mut detector = Detector::new(vec![dir.clone()], false);
507        detector.require_xcselect_marker = true;
508        assert!(!detector.is_unusable_launcher(&dir.join("ssh")));
509        assert!(detector.is_unusable_launcher(&dir.join("clangd")));
510    }
511
512    #[test]
513    fn developer_dir_lookup_follows_the_launcher_order() {
514        let temp = tempfile::tempdir().unwrap();
515        let installed = temp.path().join("CommandLineTools");
516        std::fs::create_dir_all(installed.join("usr/bin")).unwrap();
517        let empty = temp.path().join("Leftover");
518        std::fs::create_dir_all(&empty).unwrap();
519        let missing_link = temp.path().join("no-link");
520
521        let probe = |env: Option<&Path>, link: &Path, defaults: Vec<PathBuf>| DeveloperDirProbe {
522            developer_dir_env: env.map(Path::to_path_buf),
523            selection_link: link.to_path_buf(),
524            defaults,
525        };
526        assert!(!macos_developer_tools_present(probe(
527            None,
528            &missing_link,
529            vec![empty.clone(), temp.path().join("Xcode.app")]
530        )));
531        assert!(macos_developer_tools_present(probe(
532            None,
533            &missing_link,
534            vec![installed.clone()]
535        )));
536        let link = temp.path().join("xcode_select_link");
537        std::os::unix::fs::symlink(&installed, &link).unwrap();
538        assert!(macos_developer_tools_present(probe(None, &link, vec![])));
539        // DEVELOPER_DIR replaces the lookup, even when a default is installed.
540        assert!(!macos_developer_tools_present(probe(
541            Some(&empty),
542            &link,
543            vec![installed.clone()]
544        )));
545        assert!(macos_developer_tools_present(probe(
546            Some(&installed),
547            &missing_link,
548            vec![]
549        )));
550    }
551}