summaryrefslogtreecommitdiffstats
path: root/xpcom/threads/Mutex.h
blob: 346e946166050c332721145ed20ccab2f24cc5c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_Mutex_h
#define mozilla_Mutex_h

#include "mozilla/BlockingResourceBase.h"
#include "mozilla/ThreadSafety.h"
#include "mozilla/PlatformMutex.h"
#include "nsISupports.h"

//
// Provides:
//
//  - Mutex, a non-recursive mutex
//  - MutexAutoLock, an RAII class for ensuring that Mutexes are properly
//    locked and unlocked
//  - MutexAutoUnlock, complementary sibling to MutexAutoLock
//
//  - OffTheBooksMutex, a non-recursive mutex that doesn't do leak checking
//  - OffTheBooksMutexAuto{Lock,Unlock} - Like MutexAuto{Lock,Unlock}, but for
//    an OffTheBooksMutex.
//
// Using MutexAutoLock/MutexAutoUnlock etc. is MUCH preferred to making bare
// calls to Lock and Unlock.
//
namespace mozilla {

/**
 * OffTheBooksMutex is identical to Mutex, except that OffTheBooksMutex doesn't
 * include leak checking.  Sometimes you want to intentionally "leak" a mutex
 * until shutdown; in these cases, OffTheBooksMutex is for you.
 */
class MOZ_CAPABILITY("mutex") OffTheBooksMutex : public detail::MutexImpl,
                                                 BlockingResourceBase {
 public:
  /**
   * @param aName A name which can reference this lock
   * @returns If failure, nullptr
   *          If success, a valid Mutex* which must be destroyed
   *          by Mutex::DestroyMutex()
   **/
  explicit OffTheBooksMutex(const char* aName)
      : BlockingResourceBase(aName, eMutex)
#ifdef DEBUG
        ,
        mOwningThread(nullptr)
#endif
  {
  }

  ~OffTheBooksMutex() {
#ifdef DEBUG
    MOZ_ASSERT(!mOwningThread, "destroying a still-owned lock!");
#endif
  }

#ifndef DEBUG
  /**
   * Lock this mutex.
   **/
  void Lock() MOZ_CAPABILITY_ACQUIRE() { this->lock(); }

  /**
   * Try to lock this mutex, returning true if we were successful.
   **/
  [[nodiscard]] bool TryLock() MOZ_TRY_ACQUIRE(true) { return this->tryLock(); }

  /**
   * Unlock this mutex.
   **/
  void Unlock() MOZ_CAPABILITY_RELEASE() { this->unlock(); }

  /**
   * Assert that the current thread owns this mutex in debug builds.
   *
   * Does nothing in non-debug builds.
   **/
  void AssertCurrentThreadOwns() const MOZ_ASSERT_CAPABILITY(this) {}

  /**
   * Assert that the current thread does not own this mutex.
   *
   * Note that this function is not implemented for debug builds *and*
   * non-debug builds due to difficulties in dealing with memory ordering.
   *
   * It is therefore mostly useful as documentation.
   **/
  void AssertNotCurrentThreadOwns() const MOZ_ASSERT_CAPABILITY(!this) {}

#else
  void Lock() MOZ_CAPABILITY_ACQUIRE();

  [[nodiscard]] bool TryLock() MOZ_TRY_ACQUIRE(true);
  void Unlock() MOZ_CAPABILITY_RELEASE();

  void AssertCurrentThreadOwns() const MOZ_ASSERT_CAPABILITY(this);
  void AssertNotCurrentThreadOwns() const MOZ_ASSERT_CAPABILITY(!this) {
    // FIXME bug 476536
  }
#endif  // ifndef DEBUG

 private:
  OffTheBooksMutex() = delete;
  OffTheBooksMutex(const OffTheBooksMutex&) = delete;
  OffTheBooksMutex& operator=(const OffTheBooksMutex&) = delete;

  friend class OffTheBooksCondVar;

#ifdef DEBUG
  PRThread* mOwningThread;
#endif
};

/**
 * Mutex
 * When possible, use MutexAutoLock/MutexAutoUnlock to lock/unlock this
 * mutex within a scope, instead of calling Lock/Unlock directly.
 */
class Mutex : public OffTheBooksMutex {
 public:
  explicit Mutex(const char* aName) : OffTheBooksMutex(aName) {
    MOZ_COUNT_CTOR(Mutex);
  }

  MOZ_COUNTED_DTOR(Mutex)

 private:
  Mutex() = delete;
  Mutex(const Mutex&) = delete;
  Mutex& operator=(const Mutex&) = delete;
};

/**
 * MutexSingleWriter
 *
 * Mutex where a single writer exists, so that reads from the same thread
 * will not generate data races or consistency issues.
 *
 * When possible, use MutexAutoLock/MutexAutoUnlock to lock/unlock this
 * mutex within a scope, instead of calling Lock/Unlock directly.
 *
 * This requires an object implementing Mutex's SingleWriterLockOwner, so
 * we can do correct-thread checks.
 */
// Subclass this in the object owning the mutex
class SingleWriterLockOwner {
 public:
  SingleWriterLockOwner() = default;
  ~SingleWriterLockOwner() = default;

  virtual bool OnWritingThread() const = 0;
};

class MutexSingleWriter : public OffTheBooksMutex {
 public:
  // aOwner should be the object that contains the mutex, typically.  We
  // will use that object (which must have a lifetime the same or greater
  // than this object) to verify that we're running on the correct thread,
  // typically only in DEBUG builds
  explicit MutexSingleWriter(const char* aName, SingleWriterLockOwner* aOwner)
      : OffTheBooksMutex(aName)
#ifdef DEBUG
        ,
        mOwner(aOwner)
#endif
  {
    MOZ_COUNT_CTOR(MutexSingleWriter);
    MOZ_ASSERT(mOwner);
  }

  MOZ_COUNTED_DTOR(MutexSingleWriter)

  /**
   * Statically assert that we're on the only thread that modifies data
   * guarded by this Mutex.  This allows static checking for the pattern of
   * having a single thread modify a set of data, and read it (under lock)
   * on other threads, and reads on the thread that modifies it doesn't
   * require a lock.  This doesn't solve the issue of some data under the
   * Mutex following this pattern, and other data under the mutex being
   * written from multiple threads.
   *
   * We could set the writing thread and dynamically check it in debug
   * builds, but this doesn't.  We could also use thread-safety/capability
   * system to provide direct thread assertions.
   **/
  void AssertOnWritingThread() const MOZ_ASSERT_CAPABILITY(this) {
    MOZ_ASSERT(mOwner->OnWritingThread());
  }
  void AssertOnWritingThreadOrHeld() const MOZ_ASSERT_CAPABILITY(this) {
#ifdef DEBUG
    if (!mOwner->OnWritingThread()) {
      AssertCurrentThreadOwns();
    }
#endif
  }

 private:
#ifdef DEBUG
  SingleWriterLockOwner* mOwner MOZ_UNSAFE_REF(
      "This is normally the object that contains the MonitorSingleWriter, so "
      "we don't want to hold a reference to ourselves");
#endif

  MutexSingleWriter() = delete;
  MutexSingleWriter(const MutexSingleWriter&) = delete;
  MutexSingleWriter& operator=(const MutexSingleWriter&) = delete;
};

namespace detail {
template <typename T>
class MOZ_RAII BaseAutoUnlock;

/**
 * MutexAutoLock
 * Acquires the Mutex when it enters scope, and releases it when it leaves
 * scope.
 *
 * MUCH PREFERRED to bare calls to Mutex.Lock and Unlock.
 */
template <typename T>
class MOZ_RAII MOZ_SCOPED_CAPABILITY BaseAutoLock {
 public:
  /**
   * Constructor
   * The constructor aquires the given lock.  The destructor
   * releases the lock.
   *
   * @param aLock A valid mozilla::Mutex* returned by
   *              mozilla::Mutex::NewMutex.
   **/
  explicit BaseAutoLock(T aLock) MOZ_CAPABILITY_ACQUIRE(aLock) : mLock(aLock) {
    mLock.Lock();
  }

  ~BaseAutoLock(void) MOZ_CAPABILITY_RELEASE() { mLock.Unlock(); }

  // Assert that aLock is the mutex passed to the constructor and that the
  // current thread owns the mutex.  In coding patterns such as:
  //
  // void LockedMethod(const BaseAutoLock<T>& aProofOfLock)
  // {
  //   aProofOfLock.AssertOwns(mMutex);
  //   ...
  // }
  //
  // Without this assertion, it could be that mMutex is not actually
  // locked. It's possible to have code like:
  //
  // BaseAutoLock lock(someMutex);
  // ...
  // BaseAutoUnlock unlock(someMutex);
  // ...
  // LockedMethod(lock);
  //
  // and in such a case, simply asserting that the mutex pointers match is not
  // sufficient; mutex ownership must be asserted as well.
  //
  // Note that if you are going to use the coding pattern presented above, you
  // should use this method in preference to using AssertCurrentThreadOwns on
  // the mutex you expected to be held, since this method provides stronger
  // guarantees.
  void AssertOwns(const T& aMutex) const MOZ_ASSERT_CAPABILITY(aMutex) {
    MOZ_ASSERT(&aMutex == &mLock);
    mLock.AssertCurrentThreadOwns();
  }

 private:
  BaseAutoLock() = delete;
  BaseAutoLock(BaseAutoLock&) = delete;
  BaseAutoLock& operator=(BaseAutoLock&) = delete;
  static void* operator new(size_t) noexcept(true);

  friend class BaseAutoUnlock<T>;

  T mLock;
};

template <typename MutexType>
BaseAutoLock(MutexType&) -> BaseAutoLock<MutexType&>;
}  // namespace detail

typedef detail::BaseAutoLock<Mutex&> MutexAutoLock;
typedef detail::BaseAutoLock<MutexSingleWriter&> MutexSingleWriterAutoLock;
typedef detail::BaseAutoLock<OffTheBooksMutex&> OffTheBooksMutexAutoLock;

// Use if we've done AssertOnWritingThread(), and then later need to take the
// lock to write to a protected member. Instead of
//    MutexSingleWriterAutoLock lock(mutex)
// use
//    MutexSingleWriterAutoLockOnThread(lock, mutex)
#define MutexSingleWriterAutoLockOnThread(lock, mutex) \
  MOZ_PUSH_IGNORE_THREAD_SAFETY                        \
  MutexSingleWriterAutoLock lock(mutex);               \
  MOZ_POP_THREAD_SAFETY

namespace detail {
/**
 * ReleasableMutexAutoLock
 * Acquires the Mutex when it enters scope, and releases it when it leaves
 * scope. Allows calling Unlock (and Lock) as an alternative to
 * MutexAutoUnlock; this can avoid an extra lock/unlock pair.
 *
 */
template <typename T>
class MOZ_RAII MOZ_SCOPED_CAPABILITY ReleasableBaseAutoLock {
 public:
  /**
   * Constructor
   * The constructor aquires the given lock.  The destructor
   * releases the lock.
   *
   * @param aLock A valid mozilla::Mutex& returned by
   *              mozilla::Mutex::NewMutex.
   **/
  explicit ReleasableBaseAutoLock(T aLock) MOZ_CAPABILITY_ACQUIRE(aLock)
      : mLock(aLock) {
    mLock.Lock();
    mLocked = true;
  }

  ~ReleasableBaseAutoLock(void) MOZ_CAPABILITY_RELEASE() {
    if (mLocked) {
      Unlock();
    }
  }

  void AssertOwns(const T& aMutex) const MOZ_ASSERT_CAPABILITY(aMutex) {
    MOZ_ASSERT(&aMutex == &mLock);
    mLock.AssertCurrentThreadOwns();
  }

  // Allow dropping the lock prematurely; for example to support something like:
  // clang-format off
  // MutexAutoLock lock(mMutex);
  // ...
  // if (foo) {
  //   lock.Unlock();
  //   MethodThatCantBeCalledWithLock()
  //   return;
  // }
  // clang-format on
  void Unlock() MOZ_CAPABILITY_RELEASE() {
    MOZ_ASSERT(mLocked);
    mLock.Unlock();
    mLocked = false;
  }
  void Lock() MOZ_CAPABILITY_ACQUIRE() {
    MOZ_ASSERT(!mLocked);
    mLock.Lock();
    mLocked = true;
  }

 private:
  ReleasableBaseAutoLock() = delete;
  ReleasableBaseAutoLock(ReleasableBaseAutoLock&) = delete;
  ReleasableBaseAutoLock& operator=(ReleasableBaseAutoLock&) = delete;
  static void* operator new(size_t) noexcept(true);

  bool mLocked;
  T mLock;
};

template <typename MutexType>
ReleasableBaseAutoLock(MutexType&) -> ReleasableBaseAutoLock<MutexType&>;
}  // namespace detail

typedef detail::ReleasableBaseAutoLock<Mutex&> ReleasableMutexAutoLock;

namespace detail {
/**
 * BaseAutoUnlock
 * Releases the Mutex when it enters scope, and re-acquires it when it leaves
 * scope.
 *
 * MUCH PREFERRED to bare calls to Mutex.Unlock and Lock.
 */
template <typename T>
class MOZ_RAII MOZ_SCOPED_CAPABILITY BaseAutoUnlock {
 public:
  explicit BaseAutoUnlock(T aLock) MOZ_SCOPED_UNLOCK_RELEASE(aLock)
      : mLock(aLock) {
    mLock.Unlock();
  }

  explicit BaseAutoUnlock(BaseAutoLock<T>& aAutoLock)
      /* MOZ_CAPABILITY_RELEASE(aAutoLock.mLock) */
      : mLock(aAutoLock.mLock) {
    NS_ASSERTION(mLock, "null lock");
    mLock->Unlock();
  }

  ~BaseAutoUnlock() MOZ_SCOPED_UNLOCK_REACQUIRE() { mLock.Lock(); }

 private:
  BaseAutoUnlock() = delete;
  BaseAutoUnlock(BaseAutoUnlock&) = delete;
  BaseAutoUnlock& operator=(BaseAutoUnlock&) = delete;
  static void* operator new(size_t) noexcept(true);

  T mLock;
};

template <typename MutexType>
BaseAutoUnlock(MutexType&) -> BaseAutoUnlock<MutexType&>;
}  // namespace detail

typedef detail::BaseAutoUnlock<Mutex&> MutexAutoUnlock;
typedef detail::BaseAutoUnlock<MutexSingleWriter&> MutexSingleWriterAutoUnlock;
typedef detail::BaseAutoUnlock<OffTheBooksMutex&> OffTheBooksMutexAutoUnlock;

namespace detail {
/**
 * BaseAutoTryLock
 * Tries to acquire the Mutex when it enters scope, and releases it when it
 * leaves scope.
 *
 * MUCH PREFERRED to bare calls to Mutex.TryLock and Unlock.
 */
template <typename T>
class MOZ_RAII MOZ_SCOPED_CAPABILITY BaseAutoTryLock {
 public:
  explicit BaseAutoTryLock(T& aLock) MOZ_CAPABILITY_ACQUIRE(aLock)
      : mLock(aLock.TryLock() ? &aLock : nullptr) {}

  ~BaseAutoTryLock() MOZ_CAPABILITY_RELEASE() {
    if (mLock) {
      mLock->Unlock();
      mLock = nullptr;
    }
  }

  explicit operator bool() const { return mLock; }

 private:
  BaseAutoTryLock(BaseAutoTryLock&) = delete;
  BaseAutoTryLock& operator=(BaseAutoTryLock&) = delete;
  static void* operator new(size_t) noexcept(true);

  T* mLock;
};
}  // namespace detail

typedef detail::BaseAutoTryLock<Mutex> MutexAutoTryLock;
typedef detail::BaseAutoTryLock<OffTheBooksMutex> OffTheBooksMutexAutoTryLock;

}  // namespace mozilla

#endif  // ifndef mozilla_Mutex_h