From 66987911fdf299f8af589b18076a3a631e247563 Mon Sep 17 00:00:00 2001 From: Nika Layzell Date: Tue, 11 Oct 2022 23:06:08 +0000 Subject: [PATCH] Bug 1794012 - Add a static main thread capability for the thread safety analysis, r=xpcom-reviewers,kmag This acts like the `EventTargetCapability` type, but is global and specific to the main thread. Differential Revision: https://phabricator.services.mozilla.com/D158872 --- xpcom/threads/EventTargetCapability.h | 4 ++++ xpcom/threads/MainThreadUtils.h | 18 ++++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/xpcom/threads/EventTargetCapability.h b/xpcom/threads/EventTargetCapability.h index 455e4a3a4e8f..626d03a8ee58 100644 --- a/xpcom/threads/EventTargetCapability.h +++ b/xpcom/threads/EventTargetCapability.h @@ -48,6 +48,10 @@ namespace mozilla { // uint32_t mMediaCount MOZ_GUARDED_BY(mTargetCapability) = 0; // EventTargetCapability mTargetCapability; // }; +// +// NOTE: If you need a thread-safety capability for specifically the main +// thread, the static `mozilla::sMainThreadCapability` capability exists, and +// can be asserted using `AssertIsOnMainThread()`. template class MOZ_CAPABILITY EventTargetCapability final { diff --git a/xpcom/threads/MainThreadUtils.h b/xpcom/threads/MainThreadUtils.h index f4afa47234aa..b365086ff2c2 100644 --- a/xpcom/threads/MainThreadUtils.h +++ b/xpcom/threads/MainThreadUtils.h @@ -7,6 +7,7 @@ #ifndef MainThreadUtils_h_ #define MainThreadUtils_h_ +#include "mozilla/ThreadSafety.h" #include "nscore.h" class nsIThread; @@ -27,10 +28,23 @@ bool NS_IsMainThread(); namespace mozilla { +/** + * A dummy static capability for the thread safety analysis which can be + * required by functions and members using `MOZ_REQUIRE(sMainThreadCapability)` + * and `MOZ_GUARDED_BY(sMainThreadCapability)` and asserted using + * `AssertIsOnMainThread()`. + * + * If you want a thread-safety-analysis capability for a non-main thread, + * consider using the `EventTargetCapability` type. + */ +class MOZ_CAPABILITY MainThreadCapability final {}; +constexpr MainThreadCapability sMainThreadCapability; + # ifdef DEBUG -void AssertIsOnMainThread(); +void AssertIsOnMainThread() MOZ_ASSERT_CAPABILITY(sMainThreadCapability); # else -inline void AssertIsOnMainThread() {} +inline void AssertIsOnMainThread() + MOZ_ASSERT_CAPABILITY(sMainThreadCapability) {} # endif } // namespace mozilla