Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions host/simax/simax.m
Original file line number Diff line number Diff line change
Expand Up @@ -2411,16 +2411,16 @@ static void serve(int fd) {
// this runs outside the @try below: a timeout that is no number ("timeout": []) must not raise here
id tv = req[@"timeout"];
double timeout = [tv isKindOfClass:[NSNumber class]] ? [tv doubleValue] : 5.0;
if (!(timeout >= 0.1)) timeout = 0.1;
if (!(timeout >= 0.05)) timeout = 0.05;
if (timeout > 600) timeout = 600;
__block NSData* answer = nil;
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
uint64_t t0 = clock_gettime_nsec_np(CLOCK_MONOTONIC);
dispatch_async(dispatch_get_main_queue(), ^{
uint64_t t1 = clock_gettime_nsec_np(CLOCK_MONOTONIC);
@try {
// Let the socket worker return its timeout if this write is already overdue.
if ([req[@"op"] isEqual:@"insert_bound"] && (t1 - t0) >= timeout * NSEC_PER_SEC) return;
// Drop any queued request whose caller already timed out so cold launches do not accumulate stale tree walks.
if ((t1 - t0) >= (uint64_t)(timeout * (double)NSEC_PER_SEC)) return;
handle(req, ^(NSDictionary* r) {
NSMutableDictionary* m = [r mutableCopy];
m[@"wait_ms"] = @((t1 - t0) / 1000000);
Expand All @@ -2447,16 +2447,8 @@ static void serve(int fd) {
}

static void* listen_thread(void* arg) {
struct sockaddr_un a = { 0 };
int s = socket(AF_UNIX, SOCK_STREAM, 0);
a.sun_family = AF_UNIX;
strlcpy(a.sun_path, g_path, sizeof(a.sun_path));
unlink(g_path);
if (bind(s, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(s, 4) != 0) {
alog("cannot listen on %s: errno %d", g_path, errno);
close(s);
return NULL;
}
int s = (int)(intptr_t)arg;
if (s < 0) return NULL;
alog("listening on %s", g_path);
for (;;) {
// Darling's accept() needs an address buffer (simhid listen_thread)
Expand Down Expand Up @@ -2506,9 +2498,29 @@ static void cleanup(void) {
}

static void start(void) {
struct sockaddr_un a = { 0 };
int s = socket(AF_UNIX, SOCK_STREAM, 0);
if (s < 0) {
alog("cannot create socket for %s: errno %d", g_path, errno);
return;
}
a.sun_family = AF_UNIX;
strlcpy(a.sun_path, g_path, sizeof(a.sun_path));
unlink(g_path);
// Bind and listen synchronously before writing .fg so host snapshots never observe a .fg marker before the socket is accepting.
if (bind(s, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(s, 4) != 0) {
alog("cannot listen on %s: errno %d", g_path, errno);
close(s);
return;
}
atexit(cleanup);
pthread_t t;
pthread_create(&t, NULL, listen_thread, NULL);
if (pthread_create(&t, NULL, listen_thread, (void*)(intptr_t)s) != 0) {
alog("cannot spawn listen_thread for %s: errno %d", g_path, errno);
close(s);
cleanup();
return;
}
pthread_detach(t);
NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
for (NSString* n in @[ UIApplicationWillEnterForegroundNotification, UIApplicationDidBecomeActiveNotification ])
Expand Down
134 changes: 130 additions & 4 deletions tools/launcher/core/src/ax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,15 @@ enum AskReply {
ClosedEmpty,
}

fn guest_timeout_secs(timeout: Duration) -> f64 {
let secs = timeout.as_secs_f64();
if secs > 0.5 {
(secs - 0.3).max(0.2)
} else {
(secs * 0.6).max(0.05)
}
}

fn ask_reply(sock: &Path, req: &Value, timeout: Duration) -> Result<AskReply> {
let mut s = match connect_nb(sock) {
Ok(s) => s,
Expand All @@ -534,8 +543,8 @@ fn ask_reply(sock: &Path, req: &Value, timeout: Duration) -> Result<AskReply> {
s.set_read_timeout(Some(timeout))?;
s.set_write_timeout(Some(Duration::from_secs(1)))?;
let mut r = req.clone();
// the guest answers "busy" a little before we give up
r["timeout"] = json!((timeout.as_secs_f64() - 0.3).max(0.2));
// the guest answers "busy" strictly before our socket read deadline expires
r["timeout"] = json!(guest_timeout_secs(timeout));
s.write_all(format!("{r}\n").as_bytes())?;
let mut line = String::new();
BufReader::new(s).read_line(&mut line).context("no answer")?;
Expand Down Expand Up @@ -1192,9 +1201,14 @@ fn snapshot_once_with_guest_states(
UnresponsiveFg::LiveIncomplete => {}
}
// no answer at all: hung, or suspended (an extension RunningBoard suspended keeps its .fg: it draws
// nothing either). Said once (the first time), then it gets a short timeout until it answers again.
// nothing either). Keep live non-wallpaper foreground apps out of the 80 ms stuck fast-fail set so a
// slow cold-launching app can recover on the next full-timeout snapshot instead of getting trapped.
mark_incomplete(&mut snap, "fg_timeout");
st.stuck.insert(pid);
let live_fg_app = !is_wallpaper(&fg_b)
&& live_guest.as_ref().is_some_and(|states| matches!(states.get(&pid), Some('R' | 'S' | 'D')));
if !live_fg_app {
st.stuck.insert(pid);
}
let who =
format!("{fg_b} (pid {pid}: {})", if was_stuck.contains(&pid) { "still no answer".to_string() } else { format!("no answer in {:.1} s", timeout.as_secs_f64()) });
if std::env::var_os("X86SIM_AX_DEBUG").is_some() {
Expand Down Expand Up @@ -3447,4 +3461,116 @@ mod tests {
let _ = server.join();
let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn live_slow_foreground_app_recovers_after_timeout() {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixListener;

assert!(guest_timeout_secs(Duration::from_millis(80)) < 0.08);
assert!(guest_timeout_secs(Duration::from_millis(400)) < 0.4);
assert!(guest_timeout_secs(Duration::from_secs(6)) < 6.0);

let dir = std::env::temp_dir().join(format!("x86sim-ax-slow-fg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let inst = Instance {
id: "fixture-slowfg".into(),
dir: dir.clone(),
name: "test".into(),
model: String::new(),
model_id: String::new(),
runtime_dir: String::new(),
runtime_root: dir.clone(),
runtime_present: true,
unavailable: None,
ios: String::new(),
platform: "ios".into(),
build: String::new(),
screen: (390, 844),
scale: 3.0,
corner: 0.0,
ring: dir.join("simfb.ring"),
inner: None,
sock: dir.join("simhid.sock"),
state_dir: dir.clone(),
prefix: dir.clone(),
log_dir: dir.clone(),
is_default: false,
udid: "fixture-slowfg".into(),
created: 0,
};

let sb_sock = dir.join("x86sim-ax-fixture-slowfg-100.sock");
let sb_fg = dir.join("x86sim-ax-fixture-slowfg-100.fg");
std::fs::write(&sb_fg, "com.apple.springboard\n").unwrap();
let sb_listener = UnixListener::bind(&sb_sock).unwrap();
let sb_server = std::thread::spawn(move || {
for stream in sb_listener.incoming().take(2) {
let mut stream = stream.unwrap();
let mut line = String::new();
let _ = BufReader::new(&stream).read_line(&mut line);
let reply = json!({
"pid": 100,
"bundle": "com.apple.springboard",
"state": "active",
"partial": false,
"locked": false,
"suspended": [],
"screen": [390.0, 844.0, 3.0],
"windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0], "screen": [390.0, 844.0, 3.0]}],
"elements": []
});
let _ = stream.write_all(format!("{reply}\n").as_bytes());
}
});

let slow_sock = dir.join("x86sim-ax-fixture-slowfg-200.sock");
let slow_fg = dir.join("x86sim-ax-fixture-slowfg-200.fg");
std::fs::write(&slow_fg, "com.example.slow\n").unwrap();
let listener = UnixListener::bind(&slow_sock).unwrap();
let (first_done_tx, first_done_rx) = std::sync::mpsc::channel();
let server = std::thread::spawn(move || {
for (idx, stream) in listener.incoming().take(2).enumerate() {
let mut stream = stream.unwrap();
let mut line = String::new();
let _ = BufReader::new(&stream).read_line(&mut line);
if idx == 0 {
// Exceeds snapshot #1 timeout (350 ms) to simulate slow cold launch.
std::thread::sleep(Duration::from_millis(450));
let _ = first_done_tx.send(());
continue;
}
// Exceeds old 80 ms stuck timeout, well below 350 ms snapshot #2 timeout.
std::thread::sleep(Duration::from_millis(160));
let reply = json!({
"pid": 200,
"bundle": "com.example.slow",
"state": "active",
"partial": false,
"screen": [390.0, 844.0, 3.0],
"windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0], "screen": [390.0, 844.0, 3.0]}],
"elements": [{"oid": "0x2", "role": "button", "label": "Ready", "focused": false, "enabled": true, "frame": [10.0, 20.0, 120.0, 40.0]}]
});
let _ = stream.write_all(format!("{reply}\n").as_bytes());
}
});

let opts = SnapOpts { no_ocr: true, timeout_ms: 350, ..Default::default() };
let states = HashMap::from([(100, 'S'), (200, 'S')]);
let s1 = snapshot_once_with_guest_states(&inst, opts, Some(states.clone())).unwrap();
assert!(s1.foreground_incomplete);
assert_eq!(s1.incomplete_reason.as_deref(), Some("fg_timeout"));
first_done_rx.recv().unwrap();

// Snapshot #2 must NOT be trapped at 80 ms; the 160 ms healthy reply must succeed.
let s2 = snapshot_once_with_guest_states(&inst, opts, Some(states)).unwrap();
assert!(!s2.foreground_incomplete, "unexpected incomplete_reason={:?}", s2.incomplete_reason);
assert!(s2.front.contains(&"com.example.slow".to_string()));
assert_eq!(s2.elements.len(), 1);

let _ = sb_server.join();
let _ = server.join();
let _ = std::fs::remove_dir_all(&dir);
}
}
Loading