From e478ab408ed8db9003a25fe166e87237ba149dfd Mon Sep 17 00:00:00 2001 From: Sorvigolova Date: Wed, 21 Oct 2026 20:56:59 +0400 Subject: Fix hang in usbmuxd_events_unsubscribe() right after subscribing If usbmuxd_events_unsubscribe() is called before the device monitor thread has connected to usbmuxd, listenfd is still -1, so there is nothing to shut down. Where thread_cancel() is not available (Windows, or builds without pthread_cancel) unsubscribe then relies on clearing `running`, but device_monitor() sets `running = 1` and `cancelling = 0` itself when it starts and overwrites that. The thread goes on to connect, sends Listen and blocks in receive_packet() forever, so thread_join() never returns. This is easy to hit with ideviceinstaller on Windows with a network device and redirected stdout: the command completes before idevice_wait_for_command_to_complete() subscribes, so subscribe and unsubscribe happen back to back and the tool hangs on exit. Fix this by: - initializing `running`/`cancelling` in usbmuxd_events_subscribe() under listener_mutex before the monitor thread is created; - publishing listenfd in device_monitor() under the same mutex, and only if no cancellation was requested in the meantime (otherwise close the new socket and exit); - setting `cancelling`/`running` and shutting down listenfd under the mutex in usbmuxd_events_unsubscribe(), and only if the socket exists. --- src/libusbmuxd.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/libusbmuxd.c b/src/libusbmuxd.c index 705ceff..5e56c50 100644 --- a/src/libusbmuxd.c +++ b/src/libusbmuxd.c @@ -1118,16 +1118,24 @@ static void device_monitor_cleanup(void* data) */ static void *device_monitor(void *data) { - running = 1; collection_init(&devices); - cancelling = 0; #ifdef HAVE_THREAD_CLEANUP thread_cleanup_push(device_monitor_cleanup, NULL); #endif do { - listenfd = usbmuxd_listen(); + int sfd = usbmuxd_listen(); + mutex_lock(&listener_mutex); + if (cancelling) { + mutex_unlock(&listener_mutex); + if (sfd >= 0) { + socket_close(sfd); + } + break; + } + listenfd = sfd; + mutex_unlock(&listener_mutex); if (listenfd < 0) { continue; } @@ -1182,6 +1190,8 @@ int usbmuxd_events_subscribe(usbmuxd_subscription_context_t *context, usbmuxd_ev collection_add(&listeners, *context); if (devmon == THREAD_T_NULL || !thread_alive(devmon)) { + running = 1; + cancelling = 0; mutex_unlock(&listener_mutex); int res = thread_new(&devmon, device_monitor, NULL); if (res != 0) { @@ -1231,8 +1241,13 @@ int usbmuxd_events_unsubscribe(usbmuxd_subscription_context_t context) if (num == 0) { int res = 0; + mutex_lock(&listener_mutex); cancelling = 1; - socket_shutdown(listenfd, SHUT_RDWR); + running = 0; + if (listenfd >= 0) { + socket_shutdown(listenfd, SHUT_RDWR); + } + mutex_unlock(&listener_mutex); if (thread_alive(devmon)) { if (thread_cancel(devmon) < 0) { running = 0; -- cgit v1.1-32-gdbae