From 730f8fd3b7b3d0f9e64744445fad87303cbe095d Mon Sep 17 00:00:00 2001 From: Cristi N Date: Mon, 26 Dec 2022 11:45:33 +0100 Subject: [PATCH 1/2] fix: avoid race condition when starting bgw thread - specifically on Windows: the `sentry_thread_spawn` macro is defined as follows: ``` # define sentry__thread_spawn(ThreadId, Func, Data) \ (*ThreadId = CreateThread(NULL, 0, Func, Data, 0, NULL), \ *ThreadId == INVALID_HANDLE_VALUE ? 1 : 0) ``` We can see that `ThreadId` is initialized with the value returned by `CreateThread`, but the new thread might be running before `CreateThread` returns. In this change a new function `sentry__thread_get_current_threadid` is added, which returns the current thread id in a reliable way. --- src/sentry_sync.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/sentry_sync.c b/src/sentry_sync.c index a6b6380a1..e81d776c2 100644 --- a/src/sentry_sync.c +++ b/src/sentry_sync.c @@ -20,6 +20,12 @@ typedef struct { } THREADNAME_INFO; # pragma pack(pop) +sentry_threadid_t +sentry__thread_get_current_threadid() +{ + return GetCurrentThread(); +} + int sentry__thread_setname(sentry_threadid_t thread_id, const char *thread_name) { @@ -61,6 +67,12 @@ sentry__thread_setname(sentry_threadid_t thread_id, const char *thread_name) return 0; } #else +sentry_threadid_t +sentry__thread_get_current_threadid() +{ + return pthread_self(); +} + int sentry__thread_setname(sentry_threadid_t thread_id, const char *thread_name) { @@ -218,7 +230,12 @@ worker_thread(void *data) // should be called inside thread itself because of MSVC issues and mac // https://randomascii.wordpress.com/2015/10/26/thread-naming-in-windows-time-for-something-better/ - if (sentry__thread_setname(bgw->thread_id, bgw->thread_name)) { + // Additionally, `bgw->thread_id` cannot be used reliably because it is + // subject to initialization race condition: current thread might be running + // before `bgw->thread_id` is initialized in the thread that started the + // background worker. + if (sentry__thread_setname( + sentry__thread_get_current_threadid(), bgw->thread_name)) { SENTRY_WARN("failed to set background worker thread name"); } From 78cdcf6507ac1d998f338c310f691d3811fe114d Mon Sep 17 00:00:00 2001 From: Cristi N Date: Sun, 8 Jan 2023 10:41:05 +0100 Subject: [PATCH 2/2] Updated CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7fd7d29f..6c94cbe46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ **Fixes**: - Better error messages in `sentry_transport_curl`. ([#777](https://github.com/getsentry/sentry-native/pull/777)) +- Fix sporadic crash on Windows due to race condition when initializing bgw thread id. ([#785](https://github.com/getsentry/sentry-native/pull/785)) **Internal**: