@@ -415,19 +415,39 @@ runtime_exception_handler(EXCEPTION_POINTERS *exce_info)
415415}
416416#endif /* end of BH_PLATFORM_WINDOWS */
417417
418+ #ifdef BH_PLATFORM_WINDOWS
419+ static PVOID runtime_exception_handler_handle = NULL ;
420+ static int32 runtime_exception_handler_ref_count = 0 ;
421+ static korp_mutex runtime_exception_handler_lock = NULL ;
422+ #endif
423+
418424static bool
419425runtime_signal_init ()
420426{
421427#ifndef BH_PLATFORM_WINDOWS
422428 return os_thread_signal_init (runtime_signal_handler ) == 0 ? true : false;
423429#else
424- if (os_thread_signal_init () != 0 )
430+ os_mutex_lock (& runtime_exception_handler_lock );
431+
432+ if (os_thread_signal_init () != 0 ) {
433+ os_mutex_unlock (& runtime_exception_handler_lock );
425434 return false;
435+ }
426436
427- if (!AddVectoredExceptionHandler (1 , runtime_exception_handler )) {
437+ if (runtime_exception_handler_ref_count == 0 ) {
438+ runtime_exception_handler_handle =
439+ AddVectoredExceptionHandler (1 , runtime_exception_handler );
440+ }
441+
442+ if (!runtime_exception_handler_handle ) {
428443 os_thread_signal_destroy ();
444+ os_mutex_unlock (& runtime_exception_handler_lock );
429445 return false;
430446 }
447+
448+ runtime_exception_handler_ref_count ++ ;
449+
450+ os_mutex_unlock (& runtime_exception_handler_lock );
431451#endif
432452 return true;
433453}
@@ -436,7 +456,25 @@ static void
436456runtime_signal_destroy ()
437457{
438458#ifdef BH_PLATFORM_WINDOWS
439- RemoveVectoredExceptionHandler (runtime_exception_handler );
459+ os_mutex_lock (& runtime_exception_handler_lock );
460+
461+ if (runtime_exception_handler_ref_count > 0 ) {
462+ runtime_exception_handler_ref_count -- ;
463+ }
464+
465+ if (runtime_exception_handler_ref_count == 0
466+ && runtime_exception_handler_handle ) {
467+ if (RemoveVectoredExceptionHandler (runtime_exception_handler_handle )) {
468+ runtime_exception_handler_handle = NULL ;
469+ }
470+ else {
471+ /* Keep the handle so future init/destroy cycles can retry remove.
472+ * Clearing it here may leave a live callback registered forever. */
473+ runtime_exception_handler_ref_count = 1 ;
474+ }
475+ }
476+
477+ os_mutex_unlock (& runtime_exception_handler_lock );
440478#endif
441479 os_thread_signal_destroy ();
442480}
0 commit comments