From a68ebc12934a65450434b52a8039792ddd2fc165 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 2 Dec 2026 22:15:47 +0900 Subject: [PATCH] fix(xcode): end a simulator run with how the app ended (#7456) A crashing app on the iOS Simulator ended its run with exit code 0. The run now takes the app's real exit status from the simulator, keeps a nonzero simctl launch status, and a logged exit status no longer overrides an explicit Stop. Fixes #7450 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-run/src/xcode.rs | 223 +++++++++++++++++++++++++++++++++++- 1 file changed, 222 insertions(+), 1 deletion(-) diff --git a/crates/ide-run/src/xcode.rs b/crates/ide-run/src/xcode.rs index efdff89055..19cec48760 100644 --- a/crates/ide-run/src/xcode.rs +++ b/crates/ide-run/src/xcode.rs @@ -351,6 +351,9 @@ fn sh_quote(s: &str) -> String { /// `simctl` is killed. With `wait_for_debugger` the /// app stays suspended until a debugger attaches; the script prints `: ` for it /// (simctl prints that line too, but holds it back until it exits when its output is a pipe). +/// `simctl` exits 0 however the app ended, so the run's exit status comes from the simulator's +/// log, watched from the start so that it is connected by the launch ([`watch_exits`], +/// [`report_exit`]). pub fn launch_script( build_args: &[String], udid: &str, @@ -361,12 +364,17 @@ pub fn launch_script( let build: Vec = build_args.iter().map(|a| sh_quote(a)).collect(); let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id)); format!( - "set -e\n\ + "{watch}\ + set -e\n\ xcodebuild {} build\n\ xcrun simctl bootstatus {udid} -b >/dev/null\n\ open -a Simulator 2>/dev/null || open -a DeviceHub 2>/dev/null || true\n\ xcrun simctl install {udid} {app}\n\ set +e\n\ + kill -0 $watcher 2>/dev/null || watch\n\ + tries=0\n\ + while [ ! -s \"$exits\" ] && [ $tries -lt 10 ]; do sleep 0.2; tries=$((tries + 1)); done\n\ + touch \"$launched\"; tracked=$(grep -cF \"Now tracking process: [app<\"{bundle_id}\"(\" \"$exits\")\n\ xcrun simctl launch --console-pty --terminate-running-process{wait} {udid} {bundle_id} \"$@\" &\n\ launch=$!\n\ trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\ @@ -381,13 +389,71 @@ pub fn launch_script( sleep 0.2\n\ done\n\ if [ -n \"$stopped\" ]; then wait $launch 2>/dev/null; s=$?; [ $s -eq 127 ] || status=$s; fi\n\ + {report}\ exit $status\n", build.join(" "), + watch = watch_exits(&udid), + report = report_exit(&bundle_id), wait = if wait_for_debugger { " --wait-for-debugger" } else { "" }, announce = if wait_for_debugger { announce_suspended(&udid, &bundle_id) } else { String::new() }, ) } +/// Script lines that start, before the build, a `log stream` of the simulator's `runningboardd` +/// (`udid` already quoted for `sh`): it logs each app it starts tracking (`Now tracking process: +/// [app:pid]`) and each app's wait status when it ends (`[app:pid] +/// termination reported by launchd (domain, code, status)`). `watch` starts it again before the +/// launch when it ended (the simulator was not booted yet); the launch waits at most 2 s for it +/// to connect (print its header). It is killed however the script ends, a Stop's SIGINT during +/// the build included (a background job ignores SIGINT, and dash runs no `EXIT` trap when a +/// signal ends it). +fn watch_exits(udid: &str) -> String { + format!( + "exits=$(mktemp); launched=$(mktemp)\n\ + watch() {{ xcrun simctl spawn {udid} log stream --style compact --predicate 'process == \"runningboardd\" AND (eventMessage CONTAINS \"termination reported by launchd\" OR eventMessage BEGINSWITH \"Now tracking process\")' >\"$exits\" 2>/dev/null & watcher=$!; }}\n\ + watch\n\ + unwatch() {{ kill $watcher 2>/dev/null; rm -f \"$exits\" \"$launched\"; }}\n\ + trap unwatch EXIT\n\ + trap 'unwatch; trap - INT; kill -INT $$' INT\n\ + trap 'unwatch; trap - TERM; kill -TERM $$' TERM\n" + ) +} + +/// Script lines that run after a successful `simctl launch` without a Stop: the app is the first copy +/// of `bundle_id` (quoted for `sh`) the simulator started tracking after the launch began +/// (`$tracked` copies before it); they wait up to 5 s total for it and its wait status. +/// A signal ends the run with `128 + signal` and +/// says so on stderr: `App terminated (SIGKILL)` for a kill (from the app switcher, say), else +/// `App crashed (SIGTRAP)` followed, once the simulator wrote it (at most 10 s), by a link to +/// the crash report for that pid. +fn report_exit(bundle_id: &str) -> String { + format!( + "if [ \"$status\" -eq 0 ] && [ -z \"$stopped\" ]; then\n\ + tries=0\n\ + while [ \"$(grep -cF \"Now tracking process: [app<\"{bundle_id}\"(\" \"$exits\")\" -le \"$tracked\" ] && [ $tries -lt 25 ] && [ -z \"$stopped\" ]; do sleep 0.2; tries=$((tries + 1)); done\n\ + pid=$(grep -F \"Now tracking process: [app<\"{bundle_id}\"(\" \"$exits\" | sed -n \"$((tracked + 1))p\" | sed -n 's/.*>:\\([0-9][0-9]*\\)].*/\\1/p')\n\ + while [ -n \"$pid\" ] && ! grep -qF \">:$pid] termination reported by launchd\" \"$exits\" && [ $tries -lt 25 ] && [ -z \"$stopped\" ]; do sleep 0.2; tries=$((tries + 1)); done\n\ + w=\n\ + [ -z \"$pid\" ] || w=$(grep -F \">:$pid] termination reported by launchd\" \"$exits\" | tail -n 1 | sed -n 's/.*, \\([0-9][0-9]*\\))$/\\1/p')\n\ + if [ -z \"$stopped\" ] && [ -n \"$w\" ] && [ $((w & 127)) -ne 0 ]; then\n\ + sig=$((w & 127)); status=$((128 + sig))\n\ + case $sig in\n\ + 1|2|9|15) echo \"App terminated (SIG$(kill -l $sig))\" >&2 ;;\n\ + *) echo \"App crashed (SIG$(kill -l $sig))\" >&2\n\ + tries=0; report=\n\ + while [ -z \"$report\" ] && [ $tries -lt 50 ] && [ -z \"$stopped\" ]; do\n\ + report=$(find \"$HOME/Library/Logs/DiagnosticReports\" -name '*.ips' -newer \"$launched\" -exec grep -lE \"\\\"pid\\\" *: *$pid[^0-9]\" {{}} + 2>/dev/null | head -n 1)\n\ + [ -n \"$report\" ] || {{ sleep 0.2; tries=$((tries + 1)); }}\n\ + done\n\ + if [ -n \"$report\" ]; then echo \"Crash report: $report:1\" >&2\n\ + elif [ -z \"$stopped\" ]; then echo 'No crash report yet: the simulator writes it to ~/Library/Logs/DiagnosticReports later' >&2; fi ;;\n\ + esac\n\ + elif [ -z \"$stopped\" ] && [ -n \"$w\" ]; then status=$((w >> 8 & 255))\n\ + fi\n\ + fi\n" + ) +} + /// Script lines that wait for the app to show up suspended (`ps` state `T`) under its installed /// bundle, then print `: ` (both already quoted for `sh`). fn announce_suspended(udid: &str, bundle_id: &str) -> String { @@ -1473,6 +1539,15 @@ mod tests { "xcrun", "[ \"$2\" = launch ] || exit 0\ntrap 'echo terminated >> \"$LOG\"; exit 0' TERM\nwhile :; do sleep 0.05; done\n", ); + // The log stream runs alongside the other calls: it logs its arguments to its own file. + let xcrun = dir.path().join("xcrun"); + let body = fs::read_to_string(&xcrun).unwrap().replacen( + "#!/bin/sh\n", + "#!/bin/sh\n[ \"$2\" != spawn ] || { printf ' [%s]' \"$@\" > \"$LOG.spawn\"; echo 'Filtering the log data'; \ + while :; do sleep 0.05; done; }\n", + 1, + ); + fs::write(&xcrun, body).unwrap(); let build = ["-project".to_owned(), "My App.xcodeproj".to_owned(), "-scheme".to_owned(), "It's".to_owned()]; let script = launch_script(&build, "U1", Path::new("/dd/My App.app"), "dev.example.App", false); let mut child = std::process::Command::new("/bin/sh") @@ -1498,6 +1573,12 @@ mod tests { xcrun [simctl] [launch] [--console-pty] [--terminate-running-process] [U1] [dev.example.App] [--greeting] [hi there]\n\ terminated\n" ); + assert_eq!( + fs::read_to_string(dir.path().join("log.spawn")).unwrap(), + " [simctl] [spawn] [U1] [log] [stream] [--style] [compact] [--predicate] \ + [process == \"runningboardd\" AND (eventMessage CONTAINS \"termination reported by launchd\" \ + OR eventMessage BEGINSWITH \"Now tracking process\")]" + ); } /// A Stop whose SIGTERM `simctl launch` never acts on (the app was held by a debugger) still @@ -1669,4 +1750,144 @@ mod tests { assert!(child.wait().unwrap().success()); assert!(!launch_script(&[], "U1", Path::new("/A.app"), "a.b", false).contains("--wait-for-debugger")); } + + /// `simctl launch` exits 0 however the app ended: the run takes the app's wait status from the + /// simulator's log instead. A crash says so and links the app's crash report, a kill is not + /// called a crash, an exit code passes through, and without a logged status the run ends as + /// `simctl` did. + #[cfg(unix)] + #[test] + fn a_run_ends_with_how_the_app_ended() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let reports = dir.path().join("Library/Logs/DiagnosticReports"); + fs::create_dir_all(&reports).unwrap(); + let stub = |tool: &str, body: &str| { + let path = dir.path().join(tool); + fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + }; + stub("xcodebuild", ""); + stub("open", ""); + // `log stream` prints its header and an earlier copy of the app (pid 40); once the app + // was launched, its start (pid 42), the end of the earlier copy (the install closed it) + // and `$EXIT_LINE`. The crashed app's report (and one of another pid) show up in the + // reports folder. + stub( + "xcrun", + "case \"$2\" in\n\ + spawn) echo $$ > \"$HOME/watcher\"\n\ + printf 'Filtering the log data\\nNow tracking process: [app:40]\\n'\n\ + while [ ! -f \"$HOME/launched\" ]; do sleep 0.05; done\n\ + printf 'Now tracking process: [app:42]\\n'\n\ + printf '[app:40] termination reported by launchd (2, 9, 9)\\n'\n\ + [ -z \"$EXIT_LINE\" ] || echo \"$EXIT_LINE\"\n\ + while :; do sleep 0.05; done ;;\n\ + launch) touch \"$HOME/launched\"; echo 'Fatal error: Index out of range' >&2\n\ + [ -z \"$REPORT\" ] || {\n\ + printf '{}\\n{\\n \"pid\" : 4200,\\n}' > \"$HOME/Library/Logs/DiagnosticReports/Other.ips\"\n\ + printf '{}\\n{\\n \"pid\" : 42,\\n}' > \"$HOME/Library/Logs/DiagnosticReports/$REPORT\"; }\n\ + exit \"$SIMCTL_STATUS\" ;;\n\ + esac\n", + ); + let script = launch_script(&[], "U1", Path::new("/dd/A.app"), "dev.example.App", false); + let run = |exit_line: &str, report: &str, simctl_status: i32| { + let _ = fs::remove_file(dir.path().join("launched")); + for entry in fs::read_dir(&reports).unwrap() { + fs::remove_file(entry.unwrap().path()).unwrap(); + } + let out = std::process::Command::new("/bin/sh") + .args(["-c", &script, "xcode-run"]) + .env("PATH", format!("{}:/usr/bin:/bin", dir.path().display())) + .env("HOME", dir.path()) + .env("EXIT_LINE", exit_line) + .env("REPORT", report) + .env("SIMCTL_STATUS", simctl_status.to_string()) + .output() + .unwrap(); + assert_ended(&dir.path().join("watcher")); + (out.status.code(), String::from_utf8_lossy(&out.stderr).into_owned()) + }; + let ended = + |status: u32| format!("[app:42] termination reported by launchd (2, 5, {status})"); + + let report = reports.join("A-2026-12-02-160707.ips"); + assert_eq!( + run(&ended(5), "A-2026-12-02-160707.ips", 0), + ( + Some(133), + format!( + "Fatal error: Index out of range\nApp crashed (SIGTRAP)\nCrash report: {}:1\n", + report.display() + ) + ) + ); + assert_eq!( + run(&ended(9), "", 0).1, + "Fatal error: Index out of range\nApp terminated (SIGKILL)\n", + "a kill is no crash and has no report to wait for" + ); + assert_eq!(run(&ended(9), "", 0).0, Some(137)); + assert_eq!(run(&ended(3 << 8), "", 0), (Some(3), "Fatal error: Index out of range\n".to_owned())); + assert_eq!(run(&ended(0), "", 0), (Some(0), "Fatal error: Index out of range\n".to_owned())); + assert_eq!(run(&ended(0), "", 42), (Some(42), "Fatal error: Index out of range\n".to_owned())); + assert_eq!(run("", "", 0), (Some(0), "Fatal error: Index out of range\n".to_owned())); + } + + /// Waits up to 2 s for the process whose pid `file` holds to be gone. + #[cfg(unix)] + fn assert_ended(file: &Path) { + let pid: i32 = fs::read_to_string(file).unwrap().trim().parse().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while unsafe { libc::kill(pid, 0) } == 0 { + assert!(std::time::Instant::now() < deadline, "the log stream {pid} outlived the run"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + } + + /// The log stream starts before the build and ends with the run however it ends: a failed + /// build, or a Stop (SIGINT to the run's process group, which a background job ignores) + /// during the build. The run still ends as the build did. + #[cfg(unix)] + #[test] + fn the_log_stream_ends_with_a_failed_or_stopped_build() { + use std::os::unix::fs::PermissionsExt; + use std::os::unix::process::{CommandExt, ExitStatusExt}; + let dir = tempfile::tempdir().unwrap(); + let stub = |tool: &str, body: &str| { + let path = dir.path().join(tool); + fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + }; + stub("xcrun", "[ \"$2\" = spawn ] || exit 0\necho $$ > \"$HOME/watcher\"\nwhile :; do sleep 0.05; done\n"); + stub( + "xcodebuild", + "while [ ! -f \"$HOME/watcher\" ]; do sleep 0.02; done\ntouch \"$HOME/building\"\n[ -z \"$FAIL\" ] || exit 65\nwhile :; do sleep 0.05; done\n", + ); + let script = launch_script(&[], "U1", Path::new("/dd/A.app"), "dev.example.App", false); + let run = |fail: &str| { + let _ = fs::remove_file(dir.path().join("building")); + let _ = fs::remove_file(dir.path().join("watcher")); + std::process::Command::new("/bin/sh") + .args(["-c", &script, "xcode-run"]) + .env("PATH", format!("{}:/usr/bin:/bin", dir.path().display())) + .env("HOME", dir.path()) + .env("FAIL", fail) + .process_group(0) + .spawn() + .unwrap() + }; + + assert_eq!(run("1").wait().unwrap().code(), Some(65)); + assert_ended(&dir.path().join("watcher")); + + let mut child = run(""); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !dir.path().join("building").exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + unsafe { libc::kill(-(child.id() as i32), libc::SIGINT) }; + assert_eq!(child.wait().unwrap().signal(), Some(libc::SIGINT)); + assert_ended(&dir.path().join("watcher")); + } }