Skip to main content

merry_process/process_runner/
execution.rs

1use super::background::{self, BackgroundSupervisor};
2#[cfg(any(target_os = "linux", target_os = "macos"))]
3use super::permissions::WorkspaceProcessRunner;
4#[cfg(any(target_os = "linux", target_os = "macos"))]
5use crate::confinement::{self, SandboxLaunch};
6#[cfg(any(target_os = "linux", target_os = "macos"))]
7use merry_runtime::{BackgroundProcessControl, ProcessRunner, ProcessRunnerFuture};
8use merry_runtime::{
9    ProcessActionIntent, ProcessRunnerContext, ProcessRunnerError, ProcessRunnerOutput,
10};
11use std::io;
12#[cfg(any(target_os = "linux", target_os = "macos"))]
13use std::{fs, process::Stdio, sync::Arc};
14
15#[cfg(any(target_os = "linux", target_os = "macos"))]
16impl ProcessRunner for WorkspaceProcessRunner {
17    fn run<'a>(
18        &'a self,
19        intent: ProcessActionIntent,
20        context: ProcessRunnerContext,
21    ) -> ProcessRunnerFuture<'a> {
22        Box::pin(async move {
23            if context.cancellation_token().is_cancelled() {
24                return Err(ProcessRunnerError::Cancelled);
25            }
26            let runner = self.clone();
27            let plan_intent = intent.clone();
28            let launch = tokio::task::spawn_blocking(move || runner.plan_for(&plan_intent))
29                .await
30                .map_err(|error| {
31                    ProcessRunnerError::infrastructure(format!("sandbox planning failed: {error}"))
32                })??;
33            let background = self.background.clone();
34            run_sandbox_launch(launch, intent, context, background).await
35        })
36    }
37
38    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
39        Some(Arc::new(self.background.clone()))
40    }
41}
42
43#[cfg(any(target_os = "linux", target_os = "macos"))]
44async fn run_sandbox_launch(
45    launch: SandboxLaunch,
46    intent: ProcessActionIntent,
47    context: ProcessRunnerContext,
48    background: BackgroundSupervisor,
49) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
50    if context.cancellation_token().is_cancelled() {
51        return Err(ProcessRunnerError::Cancelled);
52    }
53    // On macOS, invoke `/usr/bin/sandbox-exec` directly instead of re-execing
54    // the running `merry` binary. Overwriting the running binary on disk
55    // (for example `cp -p target/release/merry ~/.cargo/bin/merry`) invalidates
56    // its kernel code signature cache on macOS and causes any re-exec of
57    // `current_exe()` to die immediately with SIGKILL.
58    #[cfg(target_os = "macos")]
59    if confinement::explicit_helper_program().is_none() {
60        let command = confinement::direct_seatbelt_command(&launch);
61        return run_spawned_process(
62            command,
63            intent,
64            context,
65            "/usr/bin/sandbox-exec".to_owned(),
66            background,
67        )
68        .await;
69    }
70    let policy = confinement::write_policy(&launch)?;
71    let helper = confinement::helper_program();
72    let mut command = tokio::process::Command::new(&helper);
73    command
74        .env(confinement::helper_env_name(), "1")
75        .env(confinement::policy_env_name(), &policy)
76        .stdin(Stdio::null())
77        .stdout(Stdio::piped())
78        .stderr(Stdio::piped())
79        .kill_on_drop(true);
80    let backend_program = helper.to_string_lossy().into_owned();
81    let result = run_spawned_process(command, intent, context, backend_program, background).await;
82    let _ = fs::remove_file(policy);
83    result
84}
85
86pub(super) async fn run_spawned_process(
87    mut command: tokio::process::Command,
88    intent: ProcessActionIntent,
89    context: ProcessRunnerContext,
90    program_for_error: String,
91    background: BackgroundSupervisor,
92) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
93    // A new group makes session-end and cancellation kill the command and its
94    // children without signaling Merry's own group.
95    #[cfg(unix)]
96    command.process_group(0);
97    // On Windows, detach from the parent console without `DETACHED_PROCESS`
98    // (which breaks stdio pipe inheritance for grandchildren like cmd -> node).
99    #[cfg(windows)]
100    {
101        use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW};
102        command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
103    }
104    let mut child = command.spawn().map_err(|source| {
105        if source.kind() == io::ErrorKind::NotFound {
106            ProcessRunnerError::infrastructure(format!(
107                "process executable `{program_for_error}` was not found"
108            ))
109        } else {
110            ProcessRunnerError::infrastructure(format!(
111                "failed to start process executable `{program_for_error}`: {source}"
112            ))
113        }
114    })?;
115    #[cfg(windows)]
116    let windows_job = child.id().and_then(
117        |pid| match super::windows_job::WindowsProcessJob::for_pid(pid) {
118            Ok(job) => Some(job),
119            Err(error) => {
120                tracing::debug!(
121                    pid,
122                    error = %error,
123                    "failed to attach Windows child process to job object"
124                );
125                None
126            }
127        },
128    );
129    let stdout = child.stdout.take().ok_or_else(|| {
130        ProcessRunnerError::infrastructure("process stdout pipe was not available")
131    })?;
132    let stderr = child.stderr.take().ok_or_else(|| {
133        ProcessRunnerError::infrastructure("process stderr pipe was not available")
134    })?;
135    background::finish_process(
136        background::SpawnedProcess {
137            child,
138            #[cfg(windows)]
139            windows_job,
140            stdout,
141            stderr,
142            program_for_error,
143        },
144        intent,
145        context,
146        background,
147    )
148    .await
149}