Skip to main content

aft_base/
pinned_executable.rs

1//! Process-lifetime re-exec identity, independent of the deployment pathname.
2//!
3//! Placement may rename a new binary over the daemon's fixed deployment pathname
4//! while it serves requests. Its children must keep using the startup image.
5//! Standalone hosts use versioned paths and retain normal executable discovery.
6
7use std::io;
8use std::path::{Path, PathBuf};
9use std::sync::{Mutex, OnceLock};
10
11#[cfg(target_os = "linux")]
12mod linux_image;
13#[cfg(all(target_os = "linux", feature = "test-hooks"))]
14pub use linux_image::prepare_fixture_pin;
15
16#[rustfmt::skip]
17test_support_visibility! {
18struct PinnedExecutable {
19    #[cfg(any(test, feature = "test-support"))]
20    pub executable: PathBuf,
21    #[cfg(not(any(test, feature = "test-support")))]
22    executable: PathBuf,
23    #[cfg(any(test, feature = "test-support"))]
24    pub directory: PathBuf,
25    #[cfg(not(any(test, feature = "test-support")))]
26    directory: PathBuf,
27    state: Mutex<PinState>,
28}
29}
30
31struct PinState {
32    owner: Option<std::fs::File>,
33    #[cfg(any(target_os = "linux", target_os = "macos"))]
34    source: std::fs::File,
35    #[cfg(target_os = "linux")]
36    image_key: linux_image::ImageKey,
37    #[cfg(target_os = "linux")]
38    pin_identity: linux_image::PinIdentity,
39}
40
41#[rustfmt::skip]
42test_support_visibility! {
43static PINNED: OnceLock<PinnedExecutable> = OnceLock::new();
44}
45
46thread_local! {
47    static TASK_IMAGE: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
48}
49
50const OWNER_LOCK: &str = "owner.lock";
51pub const TASK_IMAGE_DIR: &str = "startup-image";
52
53#[cfg(target_os = "macos")]
54struct StartupSource {
55    path: PathBuf,
56    file: std::fs::File,
57}
58#[cfg(target_os = "macos")]
59static SOURCE: OnceLock<Result<StartupSource, String>> = OnceLock::new();
60
61/// On macOS, hold the startup executable open without creating a persistent
62/// pin. Metadata-only CLI modes may call this; other platforms need no handle.
63pub fn capture_at_startup() {
64    #[cfg(target_os = "macos")]
65    SOURCE.get_or_init(|| {
66        let path = std::env::current_exe()
67            .and_then(|path| path.canonicalize())
68            .map_err(|error| error.to_string())?;
69        let file = std::fs::File::open(&path).map_err(|error| error.to_string())?;
70        Ok(StartupSource { path, file })
71    });
72}
73
74/// Called once by the daemon, before any serving-process child can be spawned.
75pub fn initialize() -> io::Result<()> {
76    if PINNED.get().is_some() {
77        return Ok(());
78    }
79    let storage = crate::storage_path::storage_dir(None);
80    let pin = prepare(&storage)?;
81    PINNED
82        .set(pin)
83        .map_err(|_| io::Error::other("executable pin was initialized concurrently"))
84}
85
86#[rustfmt::skip]
87test_support_visibility! {
88
89fn prepare(storage: &Path) -> io::Result<PinnedExecutable> {
90    // Resolve the image before touching storage. Keep an open source when a
91    // copy is needed so a concurrent placement cannot change the copied bytes.
92    #[cfg(target_os = "macos")]
93    capture_at_startup();
94    #[cfg(target_os = "macos")]
95    let source = SOURCE
96        .get()
97        .expect("startup source captured")
98        .as_ref()
99        .map_err(|error| io::Error::other(error.clone()))?;
100    #[cfg(target_os = "macos")]
101    let mut source_file = source.file.try_clone()?;
102    #[cfg(target_os = "macos")]
103    let source_path = source.path.clone();
104    // Landlock shells cannot dereference an unsandboxed daemon's procfs exe
105    // link. Materialize that kernel-held image once, rather than per command.
106    #[cfg(target_os = "linux")]
107    let source_file = std::fs::File::open(linux_image_path())?;
108    #[cfg(target_os = "linux")]
109    let image_key = linux_image::ImageKey::new(&source_file)?;
110
111    crate::private_storage::open_root(storage)?;
112    let storage = storage.canonicalize()?;
113    let run = storage.join("run");
114    match crate::private_storage::create_dir(&run) {
115        Ok(()) => {}
116        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
117        Err(error) => return Err(error),
118    }
119    // Require the storage `run` path to be a directory, not a symlink.
120    if !std::fs::symlink_metadata(&run)?.file_type().is_dir() {
121        return Err(io::Error::other(
122            "AFT storage run domain is not a directory",
123        ));
124    }
125    crate::private_storage::tighten_open_dir(&storage, &run);
126    cleanup(&run)?;
127    let pid = std::process::id();
128    let start = crate::process_identity::process_start_time_ms(pid)
129        .ok_or_else(|| io::Error::other("cannot determine executable pin owner start time"))?;
130    let directory = run.join(format!("aft-pinned-{pid}-{start}"));
131    crate::private_storage::create_dir(&directory)?;
132
133    let result = (|| {
134        let owner = owner_lock(&directory)?;
135        #[cfg(target_os = "linux")]
136        let (executable, pin_identity) = image_key.pin(&run, &source_file)?;
137        #[cfg(target_os = "macos")]
138        let executable = {
139            let destination = directory.join("aft");
140            materialize(&source_path, &mut source_file, &destination, link_image)?;
141            warm_new_image(&destination);
142            destination
143        };
144        // Windows holds the executable image open without write/delete sharing;
145        // placement cannot replace a running .exe at its deployment pathname.
146        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
147        let executable = std::env::current_exe()?;
148        std::fs::metadata(&executable)?;
149        Ok(PinnedExecutable {
150            executable,
151            directory: directory.clone(),
152            state: Mutex::new(PinState {
153                owner: Some(owner),
154                #[cfg(any(target_os = "linux", target_os = "macos"))]
155                source: source_file,
156                #[cfg(target_os = "linux")]
157                image_key,
158                #[cfg(target_os = "linux")]
159                pin_identity,
160            }),
161        })
162    })();
163    if result.is_err() {
164        let _ = std::fs::remove_dir_all(directory);
165    }
166    result
167}
168}
169
170fn cleanup(run: &Path) -> io::Result<()> {
171    for entry in std::fs::read_dir(run)? {
172        let entry = entry?;
173        let name = entry.file_name();
174        let Some((pid, start)) = owner(&name.to_string_lossy()) else {
175            continue;
176        };
177        if !entry.file_type()?.is_dir() {
178            continue;
179        }
180        let alive = match crate::process_identity::process_start_time_ms(pid) {
181            Some(actual) => actual == start,
182            // An inaccessible start time is not proof of death.
183            None => crate::fs_lock::process_alive(pid),
184        };
185        if !alive {
186            // The kernel lease is authoritative even if another PID namespace
187            // or a changed boot-clock conversion reports a different owner.
188            let lease_path = entry.path().join(OWNER_LOCK);
189            let lease = if lease_path.try_exists()? {
190                let mut options = crate::private_storage::options();
191                #[cfg(unix)]
192                {
193                    use std::os::unix::fs::OpenOptionsExt;
194                    options.custom_flags(libc::O_NOFOLLOW);
195                }
196                let Ok(file) = options.read(true).write(true).open(&lease_path) else {
197                    continue;
198                };
199                if file.try_lock().is_err() {
200                    continue;
201                }
202                Some(file)
203            } else {
204                None
205            };
206            // Windows cannot unlink an open lock file. The owner is already
207            // dead and pin names are never reused, so release before removal.
208            drop(lease);
209            match std::fs::remove_dir_all(entry.path()) {
210                Ok(()) => {}
211                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
212                Err(error) => return Err(error),
213            }
214        }
215    }
216    Ok(())
217}
218
219fn owner_lock(directory: &Path) -> io::Result<std::fs::File> {
220    let file = crate::private_storage::options()
221        .read(true)
222        .write(true)
223        .create_new(true)
224        .open(directory.join(OWNER_LOCK))?;
225    file.lock_shared()?;
226    Ok(file)
227}
228
229impl PinnedExecutable {
230    fn path(&self) -> io::Result<PathBuf> {
231        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
232        #[cfg(target_os = "linux")]
233        let has_image = self
234            .executable
235            .symlink_metadata()
236            .is_ok_and(|metadata| state.pin_identity.matches(&metadata));
237        #[cfg(not(target_os = "linux"))]
238        let has_image = self.executable.is_file();
239        if has_image && self.directory.is_dir() {
240            return Ok(self.executable.clone());
241        }
242        crate::slog_warn!(
243            "startup executable pin missing; restoring {}",
244            self.executable.display()
245        );
246        crate::private_storage::create_dir_all(&self.directory)?;
247        if !self.directory.join(OWNER_LOCK).try_exists()? {
248            state.owner = Some(owner_lock(&self.directory)?);
249        }
250        #[cfg(target_os = "linux")]
251        {
252            (_, state.pin_identity) = state.image_key.pin(
253                self.directory.parent().expect("pin owner directory in run"),
254                &state.source,
255            )?;
256        }
257        #[cfg(target_os = "macos")]
258        {
259            let temporary = self.directory.join("aft.repin");
260            let _ = std::fs::remove_file(&temporary);
261            // The deployment pathname may now contain a different build. Only
262            // the held startup image is a valid source for repair.
263            materialize(&self.executable, &mut state.source, &temporary, |_, _| {
264                Err(io::Error::other("repair from held startup image"))
265            })?;
266            std::fs::rename(temporary, &self.executable)?;
267        }
268        std::fs::metadata(&self.executable)?;
269        Ok(self.executable.clone())
270    }
271
272    #[rustfmt::skip]
273    test_support_visibility! {
274
275    fn cleanup_at_exit(&self) {
276        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
277        state.owner.take();
278        let _ = std::fs::remove_dir_all(&self.directory);
279    }
280    }
281
282    fn task_image(&self, task_io: &Path) -> io::Result<PathBuf> {
283        let executable = self.path()?;
284        let directory = task_io.join(TASK_IMAGE_DIR);
285        crate::private_storage::create_dir(&directory)?;
286        let destination = task_executable(task_io);
287        #[cfg(unix)]
288        {
289            #[cfg(target_os = "linux")]
290            std::os::unix::fs::symlink(&executable, &destination)?;
291            #[cfg(not(target_os = "linux"))]
292            {
293                let mut source = std::fs::File::open(&executable)?;
294                materialize(&executable, &mut source, &destination, |from, to| {
295                    std::fs::hard_link(from, to)
296                })?;
297            }
298            let entry = self.directory.join("shims/gh");
299            let retained = directory.join("shims/gh");
300            match std::fs::symlink_metadata(&entry) {
301                Ok(metadata) if metadata.is_symlink() => {
302                    let target = std::fs::read_link(&entry)?;
303                    let target = if target == self.executable {
304                        destination
305                    } else {
306                        target
307                    };
308                    crate::private_storage::create_dir(&directory.join("shims"))?;
309                    std::os::unix::fs::symlink(target, &retained)?;
310                }
311                Ok(metadata) if metadata.is_file() => {
312                    // An unverified candidate is replaced by a script that
313                    // refuses to run gh. Keep that script executable in the
314                    // task's PATH rather than exposing the system gh.
315                    crate::private_storage::create_dir(&directory.join("shims"))?;
316                    std::fs::copy(&entry, &retained)?;
317                }
318                Ok(_) => return Err(io::Error::other("unexpected gh shim file type")),
319                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
320                Err(error) => return Err(error),
321            }
322        }
323        #[cfg(windows)]
324        {
325            // Windows keeps the running deployment image locked, but not the
326            // daemon-owned gh.cmd pathname. Retain both in the task's lifetime.
327            if std::fs::hard_link(&executable, &destination).is_err() {
328                std::fs::copy(&executable, &destination)?;
329            }
330            let shim = self.directory.join("shims/gh.cmd");
331            if shim.is_file() {
332                let contents = std::fs::read(&shim)?;
333                let contents = if contents == crate::gh_shim_paths::windows_gh_cmd(&executable) {
334                    crate::gh_shim_paths::windows_gh_cmd(&destination)
335                } else {
336                    contents
337                };
338                crate::private_storage::create_dir(&directory.join("shims"))?;
339                std::fs::write(directory.join("shims/gh.cmd"), contents)?;
340            }
341        }
342        Ok(directory)
343    }
344}
345
346/// Freeze the launcher and shim into the task's own artifact lifetime before
347/// constructing a native profile or launching an unconfined shell. Foreground
348/// tasks need the same lifetime because they can be promoted to background.
349pub fn with_task_image<R>(task_io: &Path, run: impl FnOnce() -> R) -> io::Result<R> {
350    let Some(pin) = PINNED.get() else {
351        return Ok(run());
352    };
353    let directory = pin.task_image(task_io)?;
354    struct Scope(Option<PathBuf>);
355    impl Drop for Scope {
356        fn drop(&mut self) {
357            TASK_IMAGE.with(|slot| {
358                slot.replace(self.0.take());
359            });
360        }
361    }
362    let _scope = Scope(TASK_IMAGE.with(|slot| slot.replace(Some(directory))));
363    Ok(run())
364}
365
366pub fn task_executable(task_io: &Path) -> PathBuf {
367    task_io
368        .join(TASK_IMAGE_DIR)
369        .join(if cfg!(windows) { "aft.exe" } else { "aft" })
370}
371
372/// Non-launcher plans have no launcher pathname to carry the retained image.
373/// Redirect their request overrides before either the pipe or PTY adapter runs.
374pub fn retain_task_environment(
375    task_io: &Path,
376    environment: &mut std::collections::HashMap<String, String>,
377) -> io::Result<()> {
378    with_task_image(task_io, || {
379        let mut values = environment
380            .iter()
381            .map(|(key, value)| (key.into(), value.into()))
382            .collect();
383        task_environment(&task_executable(task_io), &mut values);
384        *environment = values
385            .into_iter()
386            .map(|(key, value)| {
387                (
388                    key.to_string_lossy().into_owned(),
389                    value.to_string_lossy().into_owned(),
390                )
391            })
392            .collect();
393    })
394}
395
396pub fn is_dead_pin_path(path: &Path) -> bool {
397    path.is_absolute()
398        && path.ancestors().any(|ancestor| {
399            ancestor
400                .file_name()
401                .and_then(|name| name.to_str())
402                .and_then(owner)
403                .is_some()
404                && ancestor.parent().and_then(Path::file_name) == Some(std::ffi::OsStr::new("run"))
405        })
406        && matches!(path.try_exists(), Ok(false))
407}
408
409pub fn task_environment(
410    launcher: &Path,
411    environment: &mut std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>,
412) {
413    let Some(pin) = PINNED.get() else {
414        return;
415    };
416    let Some(directory) = launcher
417        .parent()
418        .filter(|path| path.file_name() == Some(std::ffi::OsStr::new(TASK_IMAGE_DIR)))
419    else {
420        return;
421    };
422    let redirect = |path: &Path| {
423        if path == pin.executable {
424            return launcher.to_path_buf();
425        }
426        path.strip_prefix(&pin.directory)
427            .map(|suffix| directory.join(suffix))
428            .unwrap_or_else(|_| path.to_path_buf())
429    };
430    for key in [
431        crate::gh_shim_paths::GH_SHIMS_DIR_ENV,
432        crate::gh_shim_paths::GH_SHIM_BINARY_ENV,
433    ] {
434        if let Some(value) = environment.get_mut(std::ffi::OsStr::new(key)) {
435            *value = redirect(Path::new(value)).into_os_string();
436        }
437    }
438    if let Some(value) = environment.get_mut(std::ffi::OsStr::new("PATH")) {
439        let entries = std::env::split_paths(value)
440            .map(|path| redirect(&path))
441            .filter(|path| !is_dead_pin_path(path))
442            .collect::<Vec<_>>();
443        if let Ok(path) = std::env::join_paths(entries) {
444            *value = path;
445        }
446    }
447}
448
449fn owner(name: &str) -> Option<(u32, u64)> {
450    let (pid, start) = name.strip_prefix("aft-pinned-")?.split_once('-')?;
451    Some((pid.parse().ok()?, start.parse().ok()?))
452}
453
454#[cfg(target_os = "macos")]
455fn link_image(source: &Path, destination: &Path) -> io::Result<()> {
456    // The privacy controls name the program that asks for protected
457    // files (a removable volume, Documents, ...) by the path the kernel
458    // reports for the responsible process's executable, and with several hard
459    // links that can be any of them. Every task image then looked like a
460    // different "aft", so an Allow never stuck and the prompt blocked the
461    // volume until someone answered. Clone or copy the held image instead.
462    let _ = (source, destination);
463    Err(io::Error::new(
464        io::ErrorKind::Unsupported,
465        "the daemon's executable is never hard-linked",
466    ))
467}
468
469#[cfg(all(unix, not(target_os = "linux")))]
470fn materialize(
471    source_path: &Path,
472    source: &mut std::fs::File,
473    destination: &Path,
474    link: impl FnOnce(&Path, &Path) -> io::Result<()>,
475) -> io::Result<()> {
476    use std::os::unix::fs::{MetadataExt, PermissionsExt};
477    match link(source_path, destination) {
478        Ok(()) => {
479            let held = source.metadata()?;
480            let linked = std::fs::metadata(destination)?;
481            if (held.dev(), held.ino()) != (linked.dev(), linked.ino()) {
482                let _ = std::fs::remove_file(destination);
483                return Err(io::Error::other("deployment image changed while pinning"));
484            }
485        }
486        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error),
487        Err(_) => {
488            // On APFS a clone of the held image is a separate file that shares
489            // its blocks, so it costs no disk and keeps the signed bytes.
490            #[cfg(target_os = "macos")]
491            if clone_held_image(source, destination).is_ok() {
492                return Ok(());
493            }
494            // The pin is never a link (`link_image`), and storage may be on
495            // another volume. Stream the already-open image unchanged so
496            // embedded code signatures on macOS remain valid.
497            let mut output = crate::private_storage::executable_options()
498                .write(true)
499                .create_new(true)
500                .open(destination)?;
501            // Cloned startup handles share a cursor. Positional reads let
502            // concurrent task copies and later repairs read the complete image.
503            use std::io::Write;
504            use std::os::unix::fs::FileExt;
505            let mut offset = 0;
506            let mut buffer = [0; 64 * 1024];
507            loop {
508                let count = match source.read_at(&mut buffer, offset) {
509                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
510                    result => result?,
511                };
512                if count == 0 {
513                    break;
514                }
515                output.write_all(&buffer[..count])?;
516                offset += count as u64;
517            }
518            aft_store::sync::sync_all(&output, destination)?;
519            output.set_permissions(std::fs::Permissions::from_mode(0o500))?;
520        }
521    }
522    Ok(())
523}
524
525/// Run a newly created image once, so its first launch is paid here.
526///
527/// On macOS the pin is a new file, not another name for the running image,
528/// and the first launch of a new executable can be slow (the system assesses
529/// it, and a large debug build pays for its size). The gh shim's version
530/// probe allows only two seconds, so without this a slow first launch would
531/// refuse the shim and leave shells without `gh`. A failure here is only
532/// logged: the probe still decides whether the image is usable.
533#[cfg(target_os = "macos")]
534fn warm_new_image(image: &Path) {
535    use std::os::unix::process::CommandExt;
536    use std::process::{Command, Stdio};
537    const WARM_BUDGET: std::time::Duration = std::time::Duration::from_secs(30);
538    let started = std::time::Instant::now();
539    let mut child = match Command::new(image)
540        .env_clear()
541        .args(["gh-shim", "--shim-version"])
542        .stdin(Stdio::null())
543        .stdout(Stdio::null())
544        .stderr(Stdio::null())
545        .process_group(0)
546        .spawn()
547    {
548        Ok(child) => child,
549        Err(error) => {
550            log::warn!("pinned image first launch failed to start: {error}");
551            return;
552        }
553    };
554    loop {
555        match child.try_wait() {
556            Ok(Some(_)) => break,
557            Ok(None) if started.elapsed() < WARM_BUDGET => {
558                std::thread::sleep(std::time::Duration::from_millis(10))
559            }
560            _ => {
561                // SAFETY: the child leads its own process group (spawned above).
562                unsafe {
563                    libc::kill(-(child.id() as i32), libc::SIGKILL);
564                }
565                let _ = child.wait();
566                log::warn!(
567                    "pinned image first launch did not finish within {}s",
568                    WARM_BUDGET.as_secs()
569                );
570                return;
571            }
572        }
573    }
574    let elapsed = started.elapsed();
575    if elapsed > std::time::Duration::from_secs(1) {
576        log::info!("pinned image first launch took {}ms", elapsed.as_millis());
577    }
578}
579
580/// Clone the held (already open) image into `destination` as a new file, then
581/// make it owner-only like every other file under AFT's storage.
582#[cfg(target_os = "macos")]
583fn clone_held_image(source: &std::fs::File, destination: &Path) -> io::Result<()> {
584    use std::os::unix::ffi::OsStrExt;
585    use std::os::unix::fs::PermissionsExt;
586    use std::os::unix::io::AsRawFd;
587    let target =
588        std::ffi::CString::new(destination.as_os_str().as_bytes()).map_err(io::Error::other)?;
589    // SAFETY: the descriptor is open for this call's duration and the path is
590    // NUL-terminated. Cloning from the descriptor, not a path, copies the image
591    // this process started from even if the deployment path was replaced.
592    if unsafe { libc::fclonefileat(source.as_raw_fd(), libc::AT_FDCWD, target.as_ptr(), 0) } != 0 {
593        return Err(io::Error::last_os_error());
594    }
595    if let Err(error) =
596        std::fs::set_permissions(destination, std::fs::Permissions::from_mode(0o500))
597    {
598        let _ = std::fs::remove_file(destination);
599        return Err(error);
600    }
601    Ok(())
602}
603
604/// Remove this daemon's private launch directory, including exits that skip Drop.
605/// Startup cleanup handles crashes and any best-effort removal failures.
606pub fn cleanup_at_exit() {
607    if let Some(pin) = PINNED.get() {
608        pin.cleanup_at_exit();
609    }
610}
611
612/// The metadata of the executable image this process started from, even
613/// after another binary was renamed over its path: on Linux the image the
614/// kernel holds, on macOS the file opened at startup (see
615/// [`capture_at_startup`]). Elsewhere a running executable cannot be
616/// replaced, so its path is read. `None` when the image cannot be examined.
617pub fn startup_image_metadata() -> Option<std::fs::Metadata> {
618    #[cfg(target_os = "linux")]
619    {
620        std::fs::metadata(linux_image_path()).ok()
621    }
622    #[cfg(target_os = "macos")]
623    {
624        capture_at_startup();
625        SOURCE.get()?.as_ref().ok()?.file.metadata().ok()
626    }
627    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
628    {
629        std::env::current_exe().and_then(std::fs::metadata).ok()
630    }
631}
632
633/// Return the daemon's startup pin, or normal executable discovery for standalone
634/// and library-only hosts that have not initialized a pin.
635pub fn path() -> io::Result<PathBuf> {
636    // On Linux the task-local path is only for the task's environment. The
637    // daemon always launches the private pin, not a mutable task artifact.
638    #[cfg(not(target_os = "linux"))]
639    if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
640        return Ok(directory.join(if cfg!(windows) { "aft.exe" } else { "aft" }));
641    }
642    if let Some(pin) = PINNED.get() {
643        return pin.path();
644    }
645    std::env::current_exe()
646}
647
648/// A native profile may read and execute the task's exact launcher, not its
649/// containing cache. Outside launch setup there is no task grant to add.
650#[cfg(target_os = "linux")]
651pub fn linux_task_pin() -> io::Result<Option<PathBuf>> {
652    if TASK_IMAGE.with(|slot| slot.borrow().is_some()) {
653        PINNED.get().map(PinnedExecutable::path).transpose()
654    } else {
655        Ok(None)
656    }
657}
658
659pub fn shims_dir(storage: &Path) -> PathBuf {
660    if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
661        return directory.join("shims");
662    }
663    match PINNED.get() {
664        // A shared, mutable `shims/gh` could be retargeted by a second daemon
665        // running a different build. Keep each server's PATH entry immutable.
666        Some(pin) => pin.directory.join("shims"),
667        None => storage.join(crate::gh_shim_paths::SHIMS_DIR_NAME),
668    }
669}
670
671#[cfg(target_os = "linux")]
672fn linux_image_path() -> PathBuf {
673    // When a child shell resolves /proc/self/exe, it names the shell's image,
674    // not AFT's. Use the serving PID for both the supervisor and the gh link.
675    PathBuf::from(format!("/proc/{}/exe", std::process::id()))
676}
677
678#[cfg(any(test, feature = "test-support"))]
679#[cfg_attr(not(test), allow(dead_code, unused_imports))]
680pub mod tests {
681    use super::*;
682
683    #[test]
684    fn pinned_executable_unpinned_path_is_current_exe() {
685        assert!(PINNED.get().is_none());
686        assert_eq!(path().unwrap(), std::env::current_exe().unwrap());
687    }
688
689    #[test]
690    fn pinned_executable_unpinned_shims_use_storage() {
691        assert!(PINNED.get().is_none());
692        let storage = tempfile::tempdir().unwrap();
693        assert_eq!(
694            shims_dir(storage.path()),
695            storage.path().join(crate::gh_shim_paths::SHIMS_DIR_NAME)
696        );
697    }
698
699    #[rustfmt::skip]
700    test_support_visibility! {
701    #[cfg_attr(test, test)]
702    fn pinned_executable_cleanup_preserves_live_owner_and_unrelated_entries() {
703        let storage = tempfile::tempdir().unwrap();
704        let run = storage.path();
705        let pid = std::process::id();
706        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
707        let live = run.join(format!("aft-pinned-{pid}-{start}"));
708        let reused = run.join(format!("aft-pinned-{pid}-{}", start - 1));
709        let unrelated = run.join("operator-state");
710        for directory in [&live, &reused, &unrelated] {
711            std::fs::create_dir(directory).unwrap();
712            std::fs::write(directory.join("aft"), b"image").unwrap();
713        }
714        cleanup(run).unwrap();
715        assert!(live.join("aft").exists());
716        assert!(!reused.exists(), "a reused PID must not retain an old pin");
717        assert!(unrelated.join("aft").exists());
718    }
719    }
720
721    #[cfg(unix)]
722    #[test]
723    fn pinned_executable_cleanup_preserves_another_live_process() {
724        let mut child = std::process::Command::new("/bin/sleep")
725            .arg("60")
726            .spawn()
727            .unwrap();
728        let storage = tempfile::tempdir().unwrap();
729        let pid = child.id();
730        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
731        let directory = storage.path().join(format!("aft-pinned-{pid}-{start}"));
732        std::fs::create_dir(&directory).unwrap();
733        std::fs::write(directory.join("aft"), b"live image").unwrap();
734        let result = cleanup(storage.path());
735        let retained = directory.join("aft").exists();
736        let alive = child.try_wait().unwrap().is_none();
737        child.kill().unwrap();
738        child.wait().unwrap();
739        result.unwrap();
740        assert!(
741            alive && retained,
742            "cleanup removed a live process's executable"
743        );
744        cleanup(storage.path()).unwrap();
745        assert!(!directory.exists());
746    }
747
748    #[test]
749    fn pinned_executable_cleanup_lease_overrides_mismatched_process_clock() {
750        let storage = tempfile::tempdir().unwrap();
751        let pid = std::process::id();
752        let start = crate::process_identity::process_start_time_ms(pid).unwrap();
753        let directory = storage
754            .path()
755            .join(format!("aft-pinned-{pid}-{}", start - 1));
756        std::fs::create_dir(&directory).unwrap();
757        let lease = owner_lock(&directory).unwrap();
758        cleanup(storage.path()).unwrap();
759        assert!(
760            directory.exists(),
761            "a held lease must override an apparent PID reuse"
762        );
763        drop(lease);
764        cleanup(storage.path()).unwrap();
765        assert!(!directory.exists());
766    }
767
768    #[cfg(unix)]
769    #[test]
770    fn pinned_executable_task_image_and_shim_outlive_daemon_pin() {
771        let storage = tempfile::tempdir().unwrap();
772        let task = tempfile::tempdir().unwrap();
773        let pin = prepare(storage.path()).unwrap();
774        std::fs::create_dir(pin.directory.join("shims")).unwrap();
775        std::os::unix::fs::symlink(&pin.executable, pin.directory.join("shims/gh")).unwrap();
776        let image = pin.task_image(task.path()).unwrap();
777        pin.cleanup_at_exit();
778        assert!(!pin.directory.exists());
779        assert_eq!(
780            std::fs::read_link(image.join("shims/gh")).unwrap(),
781            image.join("aft")
782        );
783        let output = std::process::Command::new(image.join("shims/gh"))
784            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
785            .output()
786            .unwrap();
787        assert!(output.status.success(), "{output:?}");
788        assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
789    }
790
791    #[cfg(windows)]
792    #[test]
793    fn pinned_executable_windows_task_wrapper_outlives_daemon_pin() {
794        let storage = tempfile::tempdir().unwrap();
795        let task = tempfile::tempdir().unwrap();
796        let pin = prepare(storage.path()).unwrap();
797        std::fs::create_dir(pin.directory.join("shims")).unwrap();
798        std::fs::write(
799            pin.directory.join("shims/gh.cmd"),
800            crate::gh_shim_paths::windows_gh_cmd(&pin.executable),
801        )
802        .unwrap();
803        let image = pin.task_image(task.path()).unwrap();
804        pin.cleanup_at_exit();
805        assert!(!pin.directory.exists());
806        assert_eq!(
807            std::fs::read(image.join("shims/gh.cmd")).unwrap(),
808            crate::gh_shim_paths::windows_gh_cmd(&image.join("aft.exe"))
809        );
810        assert!(image.join("aft.exe").is_file());
811    }
812
813    #[cfg(unix)]
814    #[test]
815    fn pinned_executable_missing_pin_is_repaired_from_complete_held_image() {
816        use sha2::{Digest, Sha256};
817        use std::io::Seek;
818        let storage = tempfile::tempdir().unwrap();
819        let pin = prepare(storage.path()).unwrap();
820        let digest = |path: &Path| {
821            let mut hash = Sha256::new();
822            io::copy(&mut std::fs::File::open(path).unwrap(), &mut hash).unwrap();
823            hash.finalize()
824        };
825        let original = digest(&pin.executable);
826        pin.state
827            .lock()
828            .unwrap()
829            .source
830            .seek(io::SeekFrom::End(0))
831            .unwrap();
832        std::fs::remove_dir_all(&pin.directory).unwrap();
833        #[cfg(target_os = "linux")]
834        std::fs::remove_file(&pin.executable).unwrap();
835        assert_eq!(pin.path().unwrap(), pin.executable);
836        assert_eq!(original, digest(&pin.executable));
837        assert!(pin.directory.join(OWNER_LOCK).exists());
838        pin.cleanup_at_exit();
839    }
840
841    #[cfg(unix)]
842    #[test]
843    fn pinned_executable_cleanup_does_not_follow_symlinks() {
844        let storage = tempfile::tempdir().unwrap();
845        let outside = tempfile::tempdir().unwrap();
846        let name = format!("aft-pinned-{}-1", std::process::id());
847        let link = storage.path().join(name);
848        std::fs::write(outside.path().join("aft"), b"keep").unwrap();
849        std::os::unix::fs::symlink(outside.path(), &link).unwrap();
850        cleanup(storage.path()).unwrap();
851        assert!(link.is_symlink());
852        assert_eq!(std::fs::read(outside.path().join("aft")).unwrap(), b"keep");
853    }
854
855    #[cfg(unix)]
856    #[test]
857    fn pinned_executable_refuses_redirected_run_directory() {
858        let storage = tempfile::tempdir().unwrap();
859        let outside = tempfile::tempdir().unwrap();
860        std::os::unix::fs::symlink(outside.path(), storage.path().join("run")).unwrap();
861        assert!(prepare(storage.path()).is_err());
862        assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
863    }
864
865    #[cfg(all(unix, not(target_os = "linux")))]
866    #[test]
867    fn pinned_executable_cross_volume_fallback_preserves_signed_bytes_and_executes() {
868        use sha2::{Digest, Sha256};
869        use std::os::unix::fs::{MetadataExt, PermissionsExt};
870        let storage = tempfile::tempdir().unwrap();
871        let executable = std::env::current_exe().unwrap();
872        let mut source = std::fs::File::open(&executable).unwrap();
873        let destination = storage.path().join("aft");
874        materialize(&executable, &mut source, &destination, |_, _| {
875            Err(io::Error::from_raw_os_error(libc::EXDEV))
876        })
877        .unwrap();
878        let digest = |path: &Path| {
879            let mut file = std::fs::File::open(path).unwrap();
880            let mut hash = Sha256::new();
881            io::copy(&mut file, &mut hash).unwrap();
882            hash.finalize()
883        };
884        assert_eq!(digest(&executable), digest(&destination));
885        let copied = std::fs::metadata(&destination).unwrap();
886        assert_ne!(source.metadata().unwrap().ino(), copied.ino());
887        assert_eq!(copied.permissions().mode() & 0o777, 0o500);
888        let output = std::process::Command::new(&destination)
889            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
890            .output()
891            .unwrap();
892        assert!(output.status.success(), "{output:?}");
893        assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
894    }
895
896    /// The daemon's own executable keeps exactly one name: its pin is a separate
897    /// file, so macOS cannot report the daemon by a pin or task-image path.
898    #[cfg(target_os = "macos")]
899    #[test]
900    fn pinned_executable_pin_is_a_separate_file_from_the_running_image() {
901        use std::os::unix::fs::{MetadataExt, PermissionsExt};
902        let storage = tempfile::tempdir().unwrap();
903        let executable = storage.path().join("deploy");
904        std::fs::copy(std::env::current_exe().unwrap(), &executable).unwrap();
905        let mut source = std::fs::File::open(&executable).unwrap();
906        let destination = storage.path().join("aft");
907        materialize(&executable, &mut source, &destination, link_image).unwrap();
908        let held = source.metadata().unwrap();
909        let pinned = std::fs::metadata(&destination).unwrap();
910        assert_ne!(held.ino(), pinned.ino(), "the pin is a hard link");
911        assert_eq!(held.nlink(), 1, "the running image gained a second name");
912        assert_eq!(pinned.permissions().mode() & 0o777, 0o500);
913        assert_eq!(
914            std::fs::read(&executable).unwrap(),
915            std::fs::read(&destination).unwrap()
916        );
917        let output = std::process::Command::new(&destination)
918            .args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
919            .output()
920            .unwrap();
921        assert!(output.status.success(), "{output:?}");
922    }
923
924    /// Linking the running image, even once, changes its inode change time and
925    /// link count. Keep the storage on the test binary's own mount so that a
926    /// hard link would succeed if `prepare` or `task_image` made one.
927    #[cfg(target_os = "linux")]
928    #[test]
929    fn pinned_executable_prepare_and_task_image_leave_the_running_image_unchanged() {
930        use std::os::unix::fs::MetadataExt;
931        let image = linux_image_path();
932        let beside = std::env::current_exe().unwrap();
933        let beside = beside.parent().unwrap();
934        let storage = tempfile::tempdir_in(beside).unwrap();
935        let task = tempfile::tempdir_in(beside).unwrap();
936        let before = std::fs::metadata(&image).unwrap();
937        let pin = prepare(storage.path()).unwrap();
938        pin.task_image(task.path()).unwrap();
939        let pinned = std::fs::metadata(&pin.executable).unwrap();
940        let after = std::fs::metadata(&image).unwrap();
941        assert_ne!(
942            (before.dev(), before.ino()),
943            (pinned.dev(), pinned.ino()),
944            "the pin is a hard link to the running image"
945        );
946        assert_eq!(
947            before.nlink(),
948            after.nlink(),
949            "the running image gained a name"
950        );
951        assert_eq!(
952            (before.ctime(), before.ctime_nsec()),
953            (after.ctime(), after.ctime_nsec()),
954            "the running image's inode change time moved"
955        );
956        pin.cleanup_at_exit();
957    }
958
959    #[cfg(all(unix, not(target_os = "linux")))]
960    #[test]
961    fn pinned_executable_hard_link_holds_original_inode_after_replacement() {
962        use std::os::unix::fs::MetadataExt;
963        let storage = tempfile::tempdir().unwrap();
964        let source_path = storage.path().join("deploy");
965        let destination = storage.path().join("aft");
966        std::fs::write(&source_path, b"original image").unwrap();
967        let mut source = std::fs::File::open(&source_path).unwrap();
968        materialize(&source_path, &mut source, &destination, |from, to| {
969            std::fs::hard_link(from, to)
970        })
971        .unwrap();
972        assert_eq!(
973            source.metadata().unwrap().ino(),
974            destination.metadata().unwrap().ino()
975        );
976        let replacement = storage.path().join("new-build");
977        std::fs::write(&replacement, b"replacement image").unwrap();
978        std::fs::rename(replacement, &source_path).unwrap();
979        assert_eq!(std::fs::read(&destination).unwrap(), b"original image");
980        assert_eq!(std::fs::read(&source_path).unwrap(), b"replacement image");
981    }
982}