Debian Codegraph @

mozglue/baseprofiler/public/BaseProfiler.h

raw
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // The Gecko Profiler is an always-on profiler that takes fast and low overhead
8 // samples of the program execution using only userspace functionality for
9 // portability. The goal of this module is to provide performance data in a
10 // generic cross-platform way without requiring custom tools or kernel support.
11 //
12 // Samples are collected to form a timeline with optional timeline event
13 // (markers) used for filtering. The samples include both native stacks and
14 // platform-independent "label stack" frames.
15
16 #ifndef BaseProfiler_h
17 #define BaseProfiler_h
18
19 // This file is safe to include unconditionally, and only defines
20 // empty macros if MOZ_GECKO_PROFILER is not set.
21
22 // These headers are also safe to include unconditionally, with empty macros if
23 // MOZ_GECKO_PROFILER is not set.
24 // If your file only uses particular APIs (e.g., only markers), please consider
25 // including only the needed headers instead of this one, to reduce compilation
26 // dependencies.
27 #include "mozilla/BaseProfilerCounts.h"
28 #include "mozilla/BaseProfilerLabels.h"
29 #include "mozilla/BaseProfilerMarkers.h"
30 #include "mozilla/BaseProfilerState.h"
31
32 #ifndef MOZ_GECKO_PROFILER
33
34 # include "mozilla/UniquePtr.h"
35
36 // This file can be #included unconditionally. However, everything within this
37 // file must be guarded by a #ifdef MOZ_GECKO_PROFILER, *except* for the
38 // following macros and functions, which encapsulate the most common operations
39 // and thus avoid the need for many #ifdefs.
40
41 # define AUTO_BASE_PROFILER_INIT \
42 ::mozilla::baseprofiler::profiler_init_main_thread_id()
43
44 # define BASE_PROFILER_REGISTER_THREAD(name)
45 # define BASE_PROFILER_UNREGISTER_THREAD()
46 # define AUTO_BASE_PROFILER_REGISTER_THREAD(name)
47
48 # define AUTO_BASE_PROFILER_THREAD_SLEEP
49 # define AUTO_BASE_PROFILER_THREAD_WAKE
50
51 // Function stubs for when MOZ_GECKO_PROFILER is not defined.
52
53 namespace mozilla {
54
55 namespace baseprofiler {
56 // This won't be used, it's just there to allow the empty definition of
57 // `profiler_get_backtrace`.
58 struct ProfilerBacktrace {};
59 using UniqueProfilerBacktrace = UniquePtr<ProfilerBacktrace>;
60
61 // Get/Capture-backtrace functions can return nullptr or false, the result
62 // should be fed to another empty macro or stub anyway.
63
64 static inline UniqueProfilerBacktrace profiler_get_backtrace() {
65 return nullptr;
66 }
67
68 static inline bool profiler_capture_backtrace_into(
69 ProfileChunkedBuffer& aChunkedBuffer, StackCaptureOptions aCaptureOptions) {
70 return false;
71 }
72
73 static inline UniquePtr<ProfileChunkedBuffer> profiler_capture_backtrace() {
74 return nullptr;
75 }
76
77 static inline void profiler_init(void* stackTop) {}
78
79 static inline void profiler_shutdown() {}
80
81 } // namespace baseprofiler
82 } // namespace mozilla
83
84 #else // !MOZ_GECKO_PROFILER
85
86 # include "BaseProfilingStack.h"
87
88 # include "mozilla/Assertions.h"
89 # include "mozilla/Atomics.h"
90 # include "mozilla/Attributes.h"
91 # include "mozilla/BaseProfilerRAIIMacro.h"
92 # include "mozilla/Maybe.h"
93 # include "mozilla/PowerOfTwo.h"
94 # include "mozilla/TimeStamp.h"
95 # include "mozilla/UniquePtr.h"
96
97 # include <functional>
98 # include <stdint.h>
99 # include <string>
100
101 namespace mozilla {
102
103 class MallocAllocPolicy;
104 class ProfileChunkedBuffer;
105 enum class StackCaptureOptions;
106 template <class T, size_t MinInlineCapacity, class AllocPolicy>
107 class Vector;
108
109 namespace baseprofiler {
110
111 class ProfilerBacktrace;
112 class SpliceableJSONWriter;
113
114 //---------------------------------------------------------------------------
115 // Start and stop the profiler
116 //---------------------------------------------------------------------------
117
118 static constexpr PowerOfTwo32 BASE_PROFILER_DEFAULT_ENTRIES =
119 # if !defined(GP_PLAT_arm_android)
120 MakePowerOfTwo32<16 * 1024 * 1024>(); // 16M entries = 128MiB
121 # else
122 MakePowerOfTwo32<4 * 1024 * 1024>(); // 4M entries = 32MiB
123 # endif
124
125 // Startup profiling usually need to capture more data, especially on slow
126 // systems.
127 // Note: Keep in sync with GeckoThread.maybeStartGeckoProfiler:
128 // https://searchfox.org/mozilla-central/source/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoThread.java
129 static constexpr PowerOfTwo32 BASE_PROFILER_DEFAULT_STARTUP_ENTRIES =
130 # if !defined(GP_PLAT_arm_android)
131 mozilla::MakePowerOfTwo32<64 * 1024 * 1024>(); // 64M entries = 512MiB
132 # else
133 mozilla::MakePowerOfTwo32<16 * 1024 * 1024>(); // 16M entries = 128MiB
134 # endif
135
136 // Note: Keep in sync with GeckoThread.maybeStartGeckoProfiler:
137 // https://searchfox.org/mozilla-central/source/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoThread.java
138 # define BASE_PROFILER_DEFAULT_INTERVAL 1 /* millisecond */
139 # define BASE_PROFILER_MAX_INTERVAL 5000 /* milliseconds */
140
141 // Initialize the profiler. If MOZ_PROFILER_STARTUP is set the profiler will
142 // also be started. This call must happen before any other profiler calls
143 // (except profiler_start(), which will call profiler_init() if it hasn't
144 // already run).
145 MFBT_API void profiler_init(void* stackTop);
146
147 # define AUTO_BASE_PROFILER_INIT \
148 ::mozilla::baseprofiler::AutoProfilerInit PROFILER_RAII
149
150 // Clean up the profiler module, stopping it if required. This function may
151 // also save a shutdown profile if requested. No profiler calls should happen
152 // after this point and all profiling stack labels should have been popped.
153 MFBT_API void profiler_shutdown();
154
155 // Start the profiler -- initializing it first if necessary -- with the
156 // selected options. Stops and restarts the profiler if it is already active.
157 // After starting the profiler is "active". The samples will be recorded in a
158 // circular buffer.
159 // "aCapacity" is the maximum number of 8-byte entries in the profiler's
160 // circular buffer.
161 // "aInterval" the sampling interval, measured in millseconds.
162 // "aFeatures" is the feature set. Features unsupported by this
163 // platform/configuration are ignored.
164 // "aFilters" is the list of thread filters. Threads that do not match any
165 // of the filters are not profiled. A filter matches a thread if
166 // (a) the thread name contains the filter as a case-insensitive
167 // substring, or
168 // (b) the filter is of the form "pid:<n>" where n is the process
169 // id of the process that the thread is running in.
170 // "aDuration" is the duration of entries in the profiler's circular buffer.
171 MFBT_API void profiler_start(PowerOfTwo32 aCapacity, double aInterval,
172 uint32_t aFeatures, const char** aFilters,
173 uint32_t aFilterCount,
174 const Maybe<double>& aDuration = Nothing());
175
176 // Stop the profiler and discard the profile without saving it. A no-op if the
177 // profiler is inactive. After stopping the profiler is "inactive".
178 MFBT_API void profiler_stop();
179
180 // If the profiler is inactive, start it. If it's already active, restart it if
181 // the requested settings differ from the current settings. Both the check and
182 // the state change are performed while the profiler state is locked.
183 // The only difference to profiler_start is that the current buffer contents are
184 // not discarded if the profiler is already running with the requested settings.
185 MFBT_API void profiler_ensure_started(
186 PowerOfTwo32 aCapacity, double aInterval, uint32_t aFeatures,
187 const char** aFilters, uint32_t aFilterCount,
188 const Maybe<double>& aDuration = Nothing());
189
190 //---------------------------------------------------------------------------
191 // Control the profiler
192 //---------------------------------------------------------------------------
193
194 // Register/unregister threads with the profiler. Both functions operate the
195 // same whether the profiler is active or inactive.
196 # define BASE_PROFILER_REGISTER_THREAD(name) \
197 do { \
198 char stackTop; \
199 ::mozilla::baseprofiler::profiler_register_thread(name, &stackTop); \
200 } while (0)
201 # define BASE_PROFILER_UNREGISTER_THREAD() \
202 ::mozilla::baseprofiler::profiler_unregister_thread()
203 MFBT_API ProfilingStack* profiler_register_thread(const char* name,
204 void* guessStackTop);
205 MFBT_API void profiler_unregister_thread();
206
207 // Registers a DOM Window (the JS global `window`) with the profiler. Each
208 // Window _roughly_ corresponds to a single document loaded within a
209 // browsing context. Both the Window Id and Browser Id are recorded to allow
210 // correlating different Windows loaded within the same tab or frame element.
211 //
212 // We register pages for each navigations but we do not register
213 // history.pushState or history.replaceState since they correspond to the same
214 // Inner Window ID. When a browsing context is first loaded, the first url
215 // loaded in it will be about:blank. Because of that, this call keeps the first
216 // non-about:blank registration of window and discards the previous one.
217 //
218 // "aTabID" is the BrowserId of that document belongs to.
219 // That's used to determine the tab of that page.
220 // "aInnerWindowID" is the ID of the `window` global object of that
221 // document.
222 // "aUrl" is the URL of the page.
223 // "aEmbedderInnerWindowID" is the inner window id of embedder. It's used to
224 // determine sub documents of a page.
225 MFBT_API void profiler_register_page(uint64_t aTabD, uint64_t aInnerWindowID,
226 const std::string& aUrl,
227 uint64_t aEmbedderInnerWindowID);
228
229 // Unregister page with the profiler.
230 //
231 // Take a Inner Window ID and unregister the page entry that has the same ID.
232 MFBT_API void profiler_unregister_page(uint64_t aRegisteredInnerWindowID);
233
234 // Remove all registered and unregistered pages in the profiler.
235 void profiler_clear_all_pages();
236
237 class BaseProfilerCount;
238 MFBT_API void profiler_add_sampled_counter(BaseProfilerCount* aCounter);
239 MFBT_API void profiler_remove_sampled_counter(BaseProfilerCount* aCounter);
240
241 // Register and unregister a thread within a scope.
242 # define AUTO_BASE_PROFILER_REGISTER_THREAD(name) \
243 ::mozilla::baseprofiler::AutoProfilerRegisterThread PROFILER_RAII(name)
244
245 // Pause and resume the profiler. No-ops if the profiler is inactive. While
246 // paused the profile will not take any samples and will not record any data
247 // into its buffers. The profiler remains fully initialized in this state.
248 // This feature will keep JavaScript profiling enabled, thus allowing toggling
249 // the profiler without invalidating the JIT.
250 MFBT_API void profiler_pause();
251 MFBT_API void profiler_resume();
252
253 // Only pause and resume the periodic sampling loop, including stack sampling,
254 // counters, and profiling overheads.
255 MFBT_API void profiler_pause_sampling();
256 MFBT_API void profiler_resume_sampling();
257
258 // These functions tell the profiler that a thread went to sleep so that we can
259 // avoid sampling it while it's sleeping. Calling profiler_thread_sleep()
260 // twice without an intervening profiler_thread_wake() is an error. All three
261 // functions operate the same whether the profiler is active or inactive.
262 MFBT_API void profiler_thread_sleep();
263 MFBT_API void profiler_thread_wake();
264
265 // Mark a thread as asleep/awake within a scope.
266 # define AUTO_BASE_PROFILER_THREAD_SLEEP \
267 ::mozilla::baseprofiler::AutoProfilerThreadSleep PROFILER_RAII
268 # define AUTO_BASE_PROFILER_THREAD_WAKE \
269 ::mozilla::baseprofiler::AutoProfilerThreadWake PROFILER_RAII
270
271 //---------------------------------------------------------------------------
272 // Get information from the profiler
273 //---------------------------------------------------------------------------
274
275 // Get the params used to start the profiler. Returns 0 and an empty vector
276 // (via outparams) if the profile is inactive. It's possible that the features
277 // returned may be slightly different to those requested due to required
278 // adjustments.
279 MFBT_API void profiler_get_start_params(
280 int* aEntrySize, Maybe<double>* aDuration, double* aInterval,
281 uint32_t* aFeatures, Vector<const char*, 0, MallocAllocPolicy>* aFilters);
282
283 // The number of milliseconds since the process started. Operates the same
284 // whether the profiler is active or inactive.
285 MFBT_API double profiler_time();
286
287 // An object of this class is passed to profiler_suspend_and_sample_thread().
288 // For each stack frame, one of the Collect methods will be called.
289 class ProfilerStackCollector {
290 public:
291 // Some collectors need to worry about possibly overwriting previous
292 // generations of data. If that's not an issue, this can return Nothing,
293 // which is the default behaviour.
294 virtual Maybe<uint64_t> SamplePositionInBuffer() { return Nothing(); }
295 virtual Maybe<uint64_t> BufferRangeStart() { return Nothing(); }
296
297 // This method will be called once if the thread being suspended is the main
298 // thread. Default behaviour is to do nothing.
299 virtual void SetIsMainThread() {}
300
301 // WARNING: The target thread is suspended when the Collect methods are
302 // called. Do not try to allocate or acquire any locks, or you could
303 // deadlock. The target thread will have resumed by the time this function
304 // returns.
305
306 virtual void CollectNativeLeafAddr(void* aAddr) = 0;
307
308 virtual void CollectProfilingStackFrame(
309 const ProfilingStackFrame& aFrame) = 0;
310 };
311
312 // This method suspends the thread identified by aThreadId, samples its
313 // profiling stack, JS stack, and (optionally) native stack, passing the
314 // collected frames into aCollector. aFeatures dictates which compiler features
315 // are used. |Leaf| is the only relevant one.
316 // Use `aThreadId`=0 to sample the current thread.
317 MFBT_API void profiler_suspend_and_sample_thread(
318 int aThreadId, uint32_t aFeatures, ProfilerStackCollector& aCollector,
319 bool aSampleNative = true);
320
321 struct ProfilerBacktraceDestructor {
322 MFBT_API void operator()(ProfilerBacktrace*);
323 };
324
325 using UniqueProfilerBacktrace =
326 UniquePtr<ProfilerBacktrace, ProfilerBacktraceDestructor>;
327
328 // Immediately capture the current thread's call stack, store it in the provided
329 // buffer (usually to avoid allocations if you can construct the buffer on the
330 // stack). Returns false if unsuccessful, if the profiler is inactive, or if
331 // aCaptureOptions is NoStack.
332 MFBT_API bool profiler_capture_backtrace_into(
333 ProfileChunkedBuffer& aChunkedBuffer, StackCaptureOptions aCaptureOptions);
334
335 // Immediately capture the current thread's call stack, and return it in a
336 // ProfileChunkedBuffer (usually for later use in MarkerStack::TakeBacktrace()).
337 // May be null if unsuccessful, or if the profiler is inactive.
338 MFBT_API UniquePtr<ProfileChunkedBuffer> profiler_capture_backtrace();
339
340 // Immediately capture the current thread's call stack, and return it in a
341 // ProfilerBacktrace (usually for later use in marker function that take a
342 // ProfilerBacktrace). May be null if unsuccessful, or if the profiler is
343 // inactive.
344 MFBT_API UniqueProfilerBacktrace profiler_get_backtrace();
345
346 struct ProfilerStats {
347 unsigned n = 0;
348 double sum = 0;
349 double min = std::numeric_limits<double>::max();
350 double max = 0;
351 void Count(double v) {
352 ++n;
353 sum += v;
354 if (v < min) {
355 min = v;
356 }
357 if (v > max) {
358 max = v;
359 }
360 }
361 };
362
363 struct ProfilerBufferInfo {
364 // Index of the oldest entry.
365 uint64_t mRangeStart;
366 // Index of the newest entry.
367 uint64_t mRangeEnd;
368 // Buffer capacity in number of 8-byte entries.
369 uint32_t mEntryCount;
370 // Sampling stats: Interval (us) between successive samplings.
371 ProfilerStats mIntervalsUs;
372 // Sampling stats: Total duration (us) of each sampling. (Split detail below.)
373 ProfilerStats mOverheadsUs;
374 // Sampling stats: Time (us) to acquire the lock before sampling.
375 ProfilerStats mLockingsUs;
376 // Sampling stats: Time (us) to discard expired data.
377 ProfilerStats mCleaningsUs;
378 // Sampling stats: Time (us) to collect counter data.
379 ProfilerStats mCountersUs;
380 // Sampling stats: Time (us) to sample thread stacks.
381 ProfilerStats mThreadsUs;
382 };
383
384 // Get information about the current buffer status.
385 // Returns Nothing() if the profiler is inactive.
386 //
387 // This information may be useful to a user-interface displaying the current
388 // status of the profiler, allowing the user to get a sense for how fast the
389 // buffer is being written to, and how much data is visible.
390 MFBT_API Maybe<ProfilerBufferInfo> profiler_get_buffer_info();
391
392 } // namespace baseprofiler
393 } // namespace mozilla
394
395 namespace mozilla {
396 namespace baseprofiler {
397
398 //---------------------------------------------------------------------------
399 // Put profiling data into the profiler (markers)
400 //---------------------------------------------------------------------------
401
402 MFBT_API void profiler_add_js_marker(const char* aMarkerName,
403 const char* aMarkerText);
404
405 //---------------------------------------------------------------------------
406 // Output profiles
407 //---------------------------------------------------------------------------
408
409 // Set a user-friendly process name, used in JSON stream.
410 MFBT_API void profiler_set_process_name(const std::string& aProcessName,
411 const std::string* aETLDplus1);
412
413 // Get the profile encoded as a JSON string. A no-op (returning nullptr) if the
414 // profiler is inactive.
415 // If aIsShuttingDown is true, the current time is included as the process
416 // shutdown time in the JSON's "meta" object.
417 MFBT_API UniquePtr<char[]> profiler_get_profile(double aSinceTime = 0,
418 bool aIsShuttingDown = false,
419 bool aOnlyThreads = false);
420
421 // Write the profile for this process (excluding subprocesses) into aWriter.
422 // Returns false if the profiler is inactive.
423 MFBT_API bool profiler_stream_json_for_this_process(
424 SpliceableJSONWriter& aWriter, double aSinceTime = 0,
425 bool aIsShuttingDown = false, bool aOnlyThreads = false);
426
427 // Get the profile and write it into a file. A no-op if the profile is
428 // inactive.
429 // Prefixed with "base" to avoid clashing with Gecko Profiler's extern "C"
430 // profiler_save_profile_to_file when called from debugger.
431 MFBT_API void baseprofiler_save_profile_to_file(const char* aFilename);
432
433 //---------------------------------------------------------------------------
434 // RAII classes
435 //---------------------------------------------------------------------------
436
437 class MOZ_RAII AutoProfilerInit {
438 public:
439 explicit AutoProfilerInit() { profiler_init(this); }
440
441 ~AutoProfilerInit() { profiler_shutdown(); }
442
443 private:
444 };
445
446 // Convenience class to register and unregister a thread with the profiler.
447 // Needs to be the first object on the stack of the thread.
448 class MOZ_RAII AutoProfilerRegisterThread final {
449 public:
450 explicit AutoProfilerRegisterThread(const char* aName) {
451 profiler_register_thread(aName, this);
452 }
453
454 ~AutoProfilerRegisterThread() { profiler_unregister_thread(); }
455
456 private:
457 AutoProfilerRegisterThread(const AutoProfilerRegisterThread&) = delete;
458 AutoProfilerRegisterThread& operator=(const AutoProfilerRegisterThread&) =
459 delete;
460 };
461
462 class MOZ_RAII AutoProfilerThreadSleep {
463 public:
464 explicit AutoProfilerThreadSleep() { profiler_thread_sleep(); }
465
466 ~AutoProfilerThreadSleep() { profiler_thread_wake(); }
467
468 private:
469 };
470
471 // Temporarily wake up the profiling of a thread while servicing events such as
472 // Asynchronous Procedure Calls (APCs).
473 class MOZ_RAII AutoProfilerThreadWake {
474 public:
475 explicit AutoProfilerThreadWake()
476 : mIssuedWake(profiler_thread_is_sleeping()) {
477 if (mIssuedWake) {
478 profiler_thread_wake();
479 }
480 }
481
482 ~AutoProfilerThreadWake() {
483 if (mIssuedWake) {
484 MOZ_ASSERT(!profiler_thread_is_sleeping());
485 profiler_thread_sleep();
486 }
487 }
488
489 private:
490 bool mIssuedWake;
491 };
492
493 // Get the MOZ_PROFILER_STARTUP* environment variables that should be
494 // supplied to a child process that is about to be launched, in order
495 // to make that child process start with the same profiler settings as
496 // in the current process. The given function is invoked once for
497 // each variable to be set.
498 MFBT_API void GetProfilerEnvVarsForChildProcess(
499 std::function<void(const char* key, const char* value)>&& aSetEnv);
500
501 } // namespace baseprofiler
502 } // namespace mozilla
503
504 #endif // !MOZ_GECKO_PROFILER
505
506 #endif // BaseProfiler_h