Skip to content

Fix hang in usbmuxd_events_unsubscribe() right after subscribing - #158

Closed
Sorvigolova wants to merge 1 commit into
libimobiledevice:masterfrom
Sorvigolova:fix-unsubscribe-race
Closed

Sorvigolova wants to merge 1 commit into
libimobiledevice:masterfrom
Sorvigolova:fix-unsubscribe-race

Conversation

@Sorvigolova

Copy link
Copy Markdown
Contributor

Problem

usbmuxd_events_unsubscribe() can hang forever in thread_join() when it is
called shortly after usbmuxd_events_subscribe(), before the device monitor
thread has connected to usbmuxd.

Sequence:

  1. usbmuxd_events_subscribe() starts device_monitor().
  2. usbmuxd_events_unsubscribe() runs before the thread has connected:
    listenfd is still -1, so socket_shutdown() does nothing.
    thread_cancel() returns -1 on Windows (and without pthread_cancel),
    so unsubscribe sets running = 0 and calls thread_join().
  3. device_monitor() starts and sets running = 1 and cancelling = 0,
    overwriting the cancel request. It then connects, sends Listen and blocks
    in receive_packet() waiting for events that never come.
  4. Nothing shuts down the new socket, so thread_join() never returns.

How it shows up

ideviceinstaller on Windows with a network (Wi-Fi) device hangs when stdout is
redirected, e.g.

ideviceinstaller -n --udid <UDID> list > out.txt

The same command without redirection works, and over USB it works either way.
With fast output to a file the browse command completes before
idevice_wait_for_command_to_complete() subscribes to device events, so
subscribe and unsubscribe run back to back and hit the race. This also affects
GUI front-ends that read the tools' output through a pipe.

Fix

  • running and cancelling are initialized by usbmuxd_events_subscribe()
    under listener_mutex before the thread is created, instead of by the
    thread itself.
  • device_monitor() publishes listenfd under the same mutex, and only if no
    cancellation was requested in the meantime. Otherwise it closes the new
    socket and exits.
  • usbmuxd_events_unsubscribe() sets cancelling/running and shuts down
    listenfd under the mutex, and only if the socket exists.

So either unsubscribe sees the published socket and shuts it down, or the
thread sees cancelling before it starts waiting. There is no window in
between.

Testing

Reproducer: a loop of usbmuxd_events_subscribe() immediately followed by
usbmuxd_events_unsubscribe(), against a minimal fake usbmuxd that answers
Listen after a short delay and then stays silent. Built on Linux with glue
and libusbmuxd configured without pthread_cancel, so thread_cancel()
behaves as on Windows.

Fake usbmuxd reply delay Gap between subscribe/unsubscribe Before After
20 ms 0 hangs at iteration 1 300 cycles OK
5 ms 0 hangs at iteration 39 100 cycles OK
50 ms 0 hangs at iteration 29 100 cycles OK
0 / 5 / 50 ms 1 ms, 20 ms, 200 ms OK OK

Also tested on Windows (MSYS2/MinGW64 build) with ideviceinstaller and a
network device: ideviceinstaller -n ... list > out.txt no longer hangs.
Behavior over USB and with a console is unchanged.

Reproducer used for the table above:

race_test.c
/*
 * Reproducer: usbmuxd_events_subscribe() immediately followed by
 * usbmuxd_events_unsubscribe(). Reports a hang if unsubscribe does not return.
 *
 * Build (Linux, libusbmuxd/glue built WITHOUT pthread_cancel to mimic Windows):
 *   cc race_test.c -I<libusbmuxd>/include libusbmuxd-2.0.a \
 *      libimobiledevice-glue-1.0.a libplist-2.0.a -lpthread -lm -o race_test
 * Run against the fake usbmuxd (fake_usbmuxd.py):
 *   USBMUXD_SOCKET_ADDRESS=127.0.0.1:27099 ./race_test 300
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <usbmuxd.h>

static volatile int iter = 0;

static void on_alarm(int sig)
{
	(void)sig;
	printf("HANG in usbmuxd_events_unsubscribe() at iteration %d\n", iter);
	fflush(stdout);
	_exit(2);
}

static void cb(const usbmuxd_event_t *event, void *user_data)
{
	(void)event;
	(void)user_data;
}

int main(int argc, char **argv)
{
	int n = (argc > 1) ? atoi(argv[1]) : 100;
	signal(SIGALRM, on_alarm);
	for (iter = 1; iter <= n; iter++) {
		usbmuxd_subscription_context_t ctx = NULL;
		if (usbmuxd_events_subscribe(&ctx, cb, NULL) != 0) {
			printf("subscribe failed\n");
			return 1;
		}
		alarm(5);
		usbmuxd_events_unsubscribe(ctx);
		alarm(0);
	}
	printf("OK: %d subscribe/unsubscribe cycles, no hang\n", n);
	return 0;
}
fake_usbmuxd.py
#!/usr/bin/env python3
# Minimal usbmuxd stand-in for the reproducer: answers "Listen" with Result 0
# after a short delay (like a busy usbmuxd / Apple Mobile Device Service),
# then stays silent. Usage: fake_usbmuxd.py PORT [DELAY_SECONDS]
import plistlib, socket, struct, sys, threading, time

port = int(sys.argv[1])
delay = float(sys.argv[2]) if len(sys.argv) > 2 else 0.02

def handle(conn):
    try:
        hdr = b''
        while len(hdr) < 16:
            data = conn.recv(16 - len(hdr))
            if not data:
                return
            hdr += data
        length, _version, _message, tag = struct.unpack('<IIII', hdr)
        rest = length - 16
        while rest > 0:
            data = conn.recv(rest)
            if not data:
                return
            rest -= len(data)
        time.sleep(delay)
        body = plistlib.dumps({'MessageType': 'Result', 'Number': 0})
        conn.sendall(struct.pack('<IIII', 16 + len(body), 1, 8, tag) + body)
        while conn.recv(4096):
            pass
    except OSError:
        pass
    finally:
        conn.close()

srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('127.0.0.1', port))
srv.listen(64)
while True:
    conn, _ = srv.accept()
    threading.Thread(target=handle, args=(conn,), daemon=True).start()

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.
@nikias

nikias commented Nov 15, 2026

Copy link
Copy Markdown
Member

Merged with e478ab4

@nikias nikias closed this Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants