From bc215111f74a7e55d4780e84d8d33adaac0960f0 Mon Sep 17 00:00:00 2001 From: Maksim Ivanov Date: Fri, 12 Apr 2024 18:55:27 +0000 Subject: [PATCH] Deterministically wait on hotplug_libusb shutdown Change HPStopHotPluggables() to actually wait until the background hotplug thread exits. This makes sure that the hotplug mechanism doesn't continue working throughout the daemon's shutdown process, and hence use-after-frees (if a reader is added/removed after the readerfactory is shut down), memory leaks etc. are prevented. Note: this is expected to make the "SYS_Sleep(1)" trick in pcscdaemon.c unnecessary, replacing it with a more reliable alternative. We don't delete the sleep in the same commit in case it turns out to be crucial for some other reason. --- src/hotplug_libusb.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/hotplug_libusb.c b/src/hotplug_libusb.c index 4738f770..5f27ddb3 100644 --- a/src/hotplug_libusb.c +++ b/src/hotplug_libusb.c @@ -576,7 +576,7 @@ LONG HPSearchHotPluggables(const char * hpDirPath) return -1; } - ThreadCreate(&usbNotifyThread, THREAD_ATTR_DETACHED, + ThreadCreate(&usbNotifyThread, 0, (PCSCLITE_THREAD_FUNCTION( )) HPEstablishUSBNotifications, pipefd); /* Wait for initial readers to setup */ @@ -596,6 +596,8 @@ LONG HPSearchHotPluggables(const char * hpDirPath) LONG HPStopHotPluggables(void) { + /* tell the rescan thread to shut down; it checks the ara kiri flag, but it + * might also need to be awaken from reading the rescan pipe */ AraKiriHotPlug = true; HPReCheckSerialReaders(); @@ -604,6 +606,8 @@ LONG HPStopHotPluggables(void) close(rescan_pipe[1]); rescan_pipe[1] = -1; } + /* wait for the rescan thread to complete its cleanup */ + pthread_join(usbNotifyThread, NULL); return 0; }