summaryrefslogtreecommitdiffstats
path: root/tools/profiler/public/ProfilerThreadRegistration.h
blob: 3fb931987dc840e6690a1258cdbf5edc734f94a0 (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
/* -*- Mode: C++; tab-width: 2; 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 ProfilerThreadRegistration_h
#define ProfilerThreadRegistration_h

#include "mozilla/BaseProfilerDetail.h"
#include "mozilla/ProfilerThreadRegistrationData.h"
#include "mozilla/ThreadLocal.h"

namespace mozilla::profiler {

class ThreadRegistry;

// To use as RAII object, or through RegisterThread/UnregisterThread.
// Automatically registers itself with TLS and Profiler.
// It can be safely nested, but nested instances are just ignored.
// See Get.../With... functions for how to access the data.
class ThreadRegistration {
 private:
  using DataMutex = baseprofiler::detail::BaseProfilerMutex;
  using DataLock = baseprofiler::detail::BaseProfilerAutoLock;

 public:
  // Constructor to use as RAII auto-registration object.
  // It stores itself in the TLS (its effective owner), and gives its pointer to
  // the Profiler.
  ThreadRegistration(const char* aName, const void* aStackTop);

  // Destruction reverses construction: Remove pointer from the Profiler (except
  // for the main thread, because it should be done by the profiler itself) and
  // from the TLS.
  ~ThreadRegistration();

  // Manual construction&destruction, if RAII is not possible or too expensive
  // in stack space.
  // RegisterThread() *must* be paired with exactly one UnregisterThread() on
  // the same thread. (Extra UnregisterThread() calls are handled safely, but
  // they may cause profiling of this thread to stop earlier than expected.)
  static ProfilingStack* RegisterThread(const char* aName,
                                        const void* aStackTop);
  static void UnregisterThread();

  [[nodiscard]] static bool IsRegistered() { return GetFromTLS(); }

  // Prevent copies&moves.
  ThreadRegistration(const ThreadRegistration&) = delete;
  ThreadRegistration& operator=(const ThreadRegistration&) = delete;

  // Aliases to data accessors (removing the ThreadRegistration prefix).

  using UnlockedConstReader = ThreadRegistrationUnlockedConstReader;
  using UnlockedConstReaderAndAtomicRW =
      ThreadRegistrationUnlockedConstReaderAndAtomicRW;
  using UnlockedRWForLockedProfiler =
      ThreadRegistrationUnlockedRWForLockedProfiler;
  using UnlockedReaderAndAtomicRWOnThread =
      ThreadRegistrationUnlockedReaderAndAtomicRWOnThread;
  using LockedRWFromAnyThread = ThreadRegistrationLockedRWFromAnyThread;
  using LockedRWOnThread = ThreadRegistrationLockedRWOnThread;

  // On-thread access from the TLS, providing the following data accessors:
  // UnlockedConstReader, UnlockedConstReaderAndAtomicRW,
  // UnlockedRWForLockedProfiler, UnlockedReaderAndAtomicRWOnThread, and
  // LockedRWOnThread.
  // (See ThreadRegistry class for OFF-thread access.)

  // Reference-like class pointing at the ThreadRegistration for the current
  // thread.
  class OnThreadRef {
   public:
    // const UnlockedConstReader

    [[nodiscard]] const UnlockedConstReader& UnlockedConstReaderCRef() const {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedConstReader(F&& aF) const {
      return std::forward<F>(aF)(UnlockedConstReaderCRef());
    }

    // const UnlockedConstReaderAndAtomicRW

    [[nodiscard]] const UnlockedConstReaderAndAtomicRW&
    UnlockedConstReaderAndAtomicRWCRef() const {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedConstReaderAndAtomicRW(F&& aF) const {
      return std::forward<F>(aF)(UnlockedConstReaderAndAtomicRWCRef());
    }

    // UnlockedConstReaderAndAtomicRW

    [[nodiscard]] UnlockedConstReaderAndAtomicRW&
    UnlockedConstReaderAndAtomicRWRef() {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedConstReaderAndAtomicRW(F&& aF) {
      return std::forward<F>(aF)(UnlockedConstReaderAndAtomicRWRef());
    }

    // const UnlockedRWForLockedProfiler

    [[nodiscard]] const UnlockedRWForLockedProfiler&
    UnlockedRWForLockedProfilerCRef() const {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedRWForLockedProfiler(F&& aF) const {
      return std::forward<F>(aF)(UnlockedRWForLockedProfilerCRef());
    }

    // UnlockedRWForLockedProfiler

    [[nodiscard]] UnlockedRWForLockedProfiler&
    UnlockedRWForLockedProfilerRef() {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedRWForLockedProfiler(F&& aF) {
      return std::forward<F>(aF)(UnlockedRWForLockedProfilerRef());
    }

    // const UnlockedReaderAndAtomicRWOnThread

    [[nodiscard]] const UnlockedReaderAndAtomicRWOnThread&
    UnlockedReaderAndAtomicRWOnThreadCRef() const {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedReaderAndAtomicRWOnThread(F&& aF) const {
      return std::forward<F>(aF)(UnlockedReaderAndAtomicRWOnThreadCRef());
    }

    // UnlockedReaderAndAtomicRWOnThread

    [[nodiscard]] UnlockedReaderAndAtomicRWOnThread&
    UnlockedReaderAndAtomicRWOnThreadRef() {
      return mThreadRegistration->mData;
    }

    template <typename F>
    auto WithUnlockedReaderAndAtomicRWOnThread(F&& aF) {
      return std::forward<F>(aF)(UnlockedReaderAndAtomicRWOnThreadRef());
    }

    // const LockedRWOnThread through ConstRWOnThreadWithLock

    // Locking order: Profiler, ThreadRegistry, ThreadRegistration.
    class ConstRWOnThreadWithLock {
     public:
      [[nodiscard]] const LockedRWOnThread& DataCRef() const {
        return mLockedRWOnThread;
      }
      [[nodiscard]] const LockedRWOnThread* operator->() const {
        return &mLockedRWOnThread;
      }

     private:
      friend class OnThreadRef;
      ConstRWOnThreadWithLock(const LockedRWOnThread& aLockedRWOnThread,
                              DataMutex& aDataMutex)
          : mLockedRWOnThread(aLockedRWOnThread), mDataLock(aDataMutex) {}

      const LockedRWOnThread& mLockedRWOnThread;
      DataLock mDataLock;
    };

    [[nodiscard]] ConstRWOnThreadWithLock ConstLockedRWOnThread() const {
      return ConstRWOnThreadWithLock{mThreadRegistration->mData,
                                     mThreadRegistration->mDataMutex};
    }

    template <typename F>
    auto WithConstLockedRWOnThread(F&& aF) const {
      ConstRWOnThreadWithLock lockedData = ConstLockedRWOnThread();
      return std::forward<F>(aF)(lockedData.DataCRef());
    }

    // LockedRWOnThread through RWOnThreadWithLock

    // Locking order: Profiler, ThreadRegistry, ThreadRegistration.
    class RWOnThreadWithLock {
     public:
      [[nodiscard]] const LockedRWOnThread& DataCRef() const {
        return mLockedRWOnThread;
      }
      [[nodiscard]] LockedRWOnThread& DataRef() { return mLockedRWOnThread; }
      [[nodiscard]] const LockedRWOnThread* operator->() const {
        return &mLockedRWOnThread;
      }
      [[nodiscard]] LockedRWOnThread* operator->() {
        return &mLockedRWOnThread;
      }

     private:
      friend class OnThreadRef;
      RWOnThreadWithLock(LockedRWOnThread& aLockedRWOnThread,
                         DataMutex& aDataMutex)
          : mLockedRWOnThread(aLockedRWOnThread), mDataLock(aDataMutex) {}

      LockedRWOnThread& mLockedRWOnThread;
      DataLock mDataLock;
    };

    [[nodiscard]] RWOnThreadWithLock GetLockedRWOnThread() {
      return RWOnThreadWithLock{mThreadRegistration->mData,
                                mThreadRegistration->mDataMutex};
    }

    template <typename F>
    auto WithLockedRWOnThread(F&& aF) {
      RWOnThreadWithLock lockedData = GetLockedRWOnThread();
      return std::forward<F>(aF)(lockedData.DataRef());
    }

    // This is needed to allow OnThreadPtr::operator-> to return a temporary
    // OnThreadRef object, for which `->` must work; Here it provides a pointer
    // to itself, so that the next follow-up `->` will work as member accessor.
    OnThreadRef* operator->() && { return this; }

   private:
    // Only ThreadRegistration should construct an OnThreadRef.
    friend class ThreadRegistration;
    explicit OnThreadRef(ThreadRegistration& aThreadRegistration)
        : mThreadRegistration(&aThreadRegistration) {}

    // Allow ThreadRegistry to read mThreadRegistration.
    friend class ThreadRegistry;

    // Guaranted to be non-null by construction from a reference.
    ThreadRegistration* mThreadRegistration;
  };

  // Pointer-like class pointing at the ThreadRegistration for the current
  // thread, if one was registered.
  class OnThreadPtr {
   public:
    [[nodiscard]] explicit operator bool() const { return mThreadRegistration; }

    // Note that this resolves to a temporary OnThreadRef object, which has all
    // the allowed data accessors.
    [[nodiscard]] OnThreadRef operator*() const {
      MOZ_ASSERT(mThreadRegistration);
      return OnThreadRef(*mThreadRegistration);
    }

    // Note that this resolves to a temporary OnThreadRef object, which also
    // overloads operator-> and has all the allowed data accessors.
    [[nodiscard]] OnThreadRef operator->() const {
      MOZ_ASSERT(mThreadRegistration);
      return OnThreadRef(*mThreadRegistration);
    }

   private:
    friend class ThreadRegistration;
    explicit OnThreadPtr(ThreadRegistration* aThreadRegistration)
        : mThreadRegistration(aThreadRegistration) {}

    ThreadRegistration* mThreadRegistration;
  };

  [[nodiscard]] static OnThreadPtr GetOnThreadPtr() {
    return OnThreadPtr{GetFromTLS()};
  }

  // Call `F(OnThreadRef)`.
  template <typename F>
  static void WithOnThreadRef(F&& aF) {
    const auto* tls = GetTLS();
    if (tls) {
      ThreadRegistration* tr = tls->get();
      if (tr) {
        std::forward<F>(aF)(OnThreadRef{*tr});
      }
    }
  }

  // Call `F(OnThreadRef)`.
  template <typename F, typename FallbackReturn>
  [[nodiscard]] static auto WithOnThreadRefOr(F&& aF,
                                              FallbackReturn&& aFallbackReturn)
      -> decltype(std::forward<F>(aF)(std::declval<OnThreadRef>())) {
    const auto* tls = GetTLS();
    if (tls) {
      ThreadRegistration* tr = tls->get();
      if (tr) {
        return std::forward<F>(aF)(OnThreadRef{*tr});
      }
    }
    return std::forward<FallbackReturn>(aFallbackReturn);
  }

  [[nodiscard]] static bool IsDataMutexLockedOnCurrentThread() {
    if (const ThreadRegistration* tr = GetFromTLS(); tr) {
      return tr->mDataMutex.IsLockedOnCurrentThread();
    }
    return false;
  }

  size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
    DataLock lock(mDataMutex);
    return mData.SizeOfExcludingThis(aMallocSizeOf);
  }

  size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
    // aMallocSizeOf can only be used on head-allocated objects. Stack
    // allocations and static objects are not counted.
    return (mIsOnHeap ? aMallocSizeOf(this) : 0) +
           SizeOfExcludingThis(aMallocSizeOf);
  }

 private:
  friend class ThreadRegistry;

  // This is what is embedded inside ThreadRegistration.
  // References to sub-classes will be provided, to limit access as appropriate.
  class EmbeddedData final : public LockedRWOnThread {
   private:
    // Only ThreadRegistration can construct (its embedded) `mData`.
    friend class ThreadRegistration;
    EmbeddedData(const char* aName, const void* aStackTop)
        : LockedRWOnThread(aName, aStackTop) {}
  };
  EmbeddedData mData;

  // Used when writing on self thread, and for any access from any thread.
  // Locking order: Profiler, ThreadRegistry, ThreadRegistration.
  mutable DataMutex mDataMutex;

  // In case of nested (non-RAII) registrations. Only accessed on thread.
  int mOtherRegistrations = 0;

  // Set to true if allocated by `RegisterThread()`. Otherwise we assume that it
  // is on the stack.
  bool mIsOnHeap = false;

  // Only accessed by ThreadRegistry on this thread.
  bool mIsRegistryLockedSharedOnThisThread = false;

  static MOZ_THREAD_LOCAL(ThreadRegistration*) tlsThreadRegistration;

  [[nodiscard]] static decltype(tlsThreadRegistration)* GetTLS() {
    static const bool initialized = tlsThreadRegistration.init();
    return initialized ? &tlsThreadRegistration : nullptr;
  }

  [[nodiscard]] static ThreadRegistration* GetFromTLS() {
    const auto tls = GetTLS();
    return tls ? tls->get() : nullptr;
  }
};

}  // namespace mozilla::profiler

#endif  // ProfilerThreadRegistration_h