Debian Codegraph @

mozglue/baseprofiler/core/platform.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; 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 // There are three kinds of samples done by the profiler.
8 //
9 // - A "periodic" sample is the most complex kind. It is done in response to a
10 // timer while the profiler is active. It involves writing a stack trace plus
11 // a variety of other values (memory measurements, responsiveness
12 // measurements, etc.) into the main ProfileBuffer. The sampling is done from
13 // off-thread, and so SuspendAndSampleAndResumeThread() is used to get the
14 // register values.
15 //
16 // - A "synchronous" sample is a simpler kind. It is done in response to an API
17 // call (profiler_get_backtrace()). It involves writing a stack trace and
18 // little else into a temporary ProfileBuffer, and wrapping that up in a
19 // ProfilerBacktrace that can be subsequently used in a marker. The sampling
20 // is done on-thread, and so REGISTERS_SYNC_POPULATE() is used to get the
21 // register values.
22 //
23 // - A "backtrace" sample is the simplest kind. It is done in response to an
24 // API call (profiler_suspend_and_sample_thread()). It involves getting a
25 // stack trace via a ProfilerStackCollector; it does not write to a
26 // ProfileBuffer. The sampling is done from off-thread, and so uses
27 // SuspendAndSampleAndResumeThread() to get the register values.
28
29 #include "platform.h"
30
31 #include <algorithm>
32 #include <errno.h>
33 #include <fstream>
34 #include <ostream>
35 #include <set>
36 #include <sstream>
37 #include <string_view>
38
39 // #include "memory_hooks.h"
40 #include "mozilla/ArrayUtils.h"
41 #include "mozilla/AutoProfilerLabel.h"
42 #include "mozilla/BaseAndGeckoProfilerDetail.h"
43 #include "mozilla/BaseProfilerDetail.h"
44 #include "mozilla/DoubleConversion.h"
45 #include "mozilla/Printf.h"
46 #include "mozilla/ProfilerBufferSize.h"
47 #include "mozilla/ProfileBufferChunkManagerSingle.h"
48 #include "mozilla/ProfileBufferChunkManagerWithLocalLimit.h"
49 #include "mozilla/ProfileChunkedBuffer.h"
50 #include "mozilla/Services.h"
51 #include "mozilla/Span.h"
52 #include "mozilla/StackWalk.h"
53 #ifdef XP_WIN
54 # include "mozilla/StackWalkThread.h"
55 # include "mozilla/WindowsStackWalkInitialization.h"
56 #endif
57 #include "mozilla/StaticPtr.h"
58 #include "mozilla/ThreadLocal.h"
59 #include "mozilla/TimeStamp.h"
60
61 #include "mozilla/UniquePtr.h"
62 #include "mozilla/Vector.h"
63 #include "prdtoa.h"
64 #include "prtime.h"
65
66 #include "BaseProfiler.h"
67 #include "BaseProfilingCategory.h"
68 #include "PageInformation.h"
69 #include "ProfiledThreadData.h"
70 #include "ProfilerBacktrace.h"
71 #include "ProfileBuffer.h"
72 #include "RegisteredThread.h"
73 #include "SharedLibraries.h"
74 #include "ThreadInfo.h"
75 #include "VTuneProfiler.h"
76
77 // Win32 builds always have frame pointers, so FramePointerStackWalk() always
78 // works.
79 #if defined(GP_PLAT_x86_windows)
80 # define HAVE_NATIVE_UNWIND
81 # define USE_FRAME_POINTER_STACK_WALK
82 #endif
83
84 // Win64 builds always omit frame pointers, so we use the slower
85 // MozStackWalk(), which works in that case.
86 #if defined(GP_PLAT_amd64_windows)
87 # define HAVE_NATIVE_UNWIND
88 # define USE_MOZ_STACK_WALK
89 #endif
90
91 // AArch64 Win64 doesn't seem to use frame pointers, so we use the slower
92 // MozStackWalk().
93 #if defined(GP_PLAT_arm64_windows)
94 # define HAVE_NATIVE_UNWIND
95 # define USE_MOZ_STACK_WALK
96 #endif
97
98 // Mac builds use FramePointerStackWalk(). Even if we build without
99 // frame pointers, we'll still get useful stacks in system libraries
100 // because those always have frame pointers.
101 // We don't use MozStackWalk() on Mac.
102 #if defined(GP_OS_darwin)
103 # define HAVE_NATIVE_UNWIND
104 # define USE_FRAME_POINTER_STACK_WALK
105 #endif
106
107 // We can only stackwalk without expensive initialization on platforms which
108 // support FramePointerStackWalk or MozStackWalk. LUL Stackwalking requires
109 // initializing LUL, and EHABIStackWalk requires initializing EHABI, both of
110 // which can be expensive.
111 #if defined(USE_FRAME_POINTER_STACK_WALK) || defined(USE_MOZ_STACK_WALK)
112 # define HAVE_FASTINIT_NATIVE_UNWIND
113 #endif
114
115 #ifdef MOZ_VALGRIND
116 # include <valgrind/memcheck.h>
117 #else
118 # define VALGRIND_MAKE_MEM_DEFINED(_addr, _len) ((void)0)
119 #endif
120
121 #if defined(GP_OS_linux) || defined(GP_OS_android) || defined(GP_OS_freebsd)
122 # include <ucontext.h>
123 #endif
124
125 namespace mozilla {
126 namespace baseprofiler {
127
128 using detail::RacyFeatures;
129
130 bool LogTest(int aLevelToTest) {
131 static const int maxLevel = getenv("MOZ_BASE_PROFILER_VERBOSE_LOGGING") ? 5
132 : getenv("MOZ_BASE_PROFILER_DEBUG_LOGGING") ? 4
133 : getenv("MOZ_BASE_PROFILER_LOGGING") ? 3
134 : 0;
135 return aLevelToTest <= maxLevel;
136 }
137
138 void PrintToConsole(const char* aFmt, ...) {
139 va_list args;
140 va_start(args, aFmt);
141 #if defined(ANDROID)
142 __android_log_vprint(ANDROID_LOG_INFO, "Gecko", aFmt, args);
143 #else
144 vfprintf(stderr, aFmt, args);
145 #endif
146 va_end(args);
147 }
148
149 ProfileChunkedBuffer& profiler_get_core_buffer() {
150 // This needs its own mutex, because it is used concurrently from functions
151 // guarded by gPSMutex as well as others without safety (e.g.,
152 // profiler_add_marker). It is *not* used inside the critical section of the
153 // sampler, because mutexes cannot be used there.
154 static ProfileChunkedBuffer sProfileChunkedBuffer{
155 ProfileChunkedBuffer::ThreadSafety::WithMutex};
156 return sProfileChunkedBuffer;
157 }
158
159 Atomic<int, MemoryOrdering::Relaxed> gSkipSampling;
160
161 constexpr static bool ValidateFeatures() {
162 int expectedFeatureNumber = 0;
163
164 // Feature numbers should start at 0 and increase by 1 each.
165 #define CHECK_FEATURE(n_, str_, Name_, desc_) \
166 if ((n_) != expectedFeatureNumber) { \
167 return false; \
168 } \
169 ++expectedFeatureNumber;
170
171 BASE_PROFILER_FOR_EACH_FEATURE(CHECK_FEATURE)
172
173 #undef CHECK_FEATURE
174
175 return true;
176 }
177
178 static_assert(ValidateFeatures(), "Feature list is invalid");
179
180 // Return all features that are available on this platform.
181 static uint32_t AvailableFeatures() {
182 uint32_t features = 0;
183
184 #define ADD_FEATURE(n_, str_, Name_, desc_) \
185 ProfilerFeature::Set##Name_(features);
186
187 // Add all the possible features.
188 BASE_PROFILER_FOR_EACH_FEATURE(ADD_FEATURE)
189
190 #undef ADD_FEATURE
191
192 // Now remove features not supported on this platform/configuration.
193 ProfilerFeature::ClearJava(features);
194 ProfilerFeature::ClearJS(features);
195 ProfilerFeature::ClearScreenshots(features);
196 #if !defined(HAVE_NATIVE_UNWIND)
197 ProfilerFeature::ClearStackWalk(features);
198 #endif
199 #if !defined(GP_OS_windows)
200 ProfilerFeature::ClearNoTimerResolutionChange(features);
201 #endif
202
203 return features;
204 }
205
206 // Default features common to all contexts (even if not available).
207 static constexpr uint32_t DefaultFeatures() {
208 return ProfilerFeature::Java | ProfilerFeature::JS |
209 ProfilerFeature::StackWalk | ProfilerFeature::CPUUtilization |
210 ProfilerFeature::ProcessCPU;
211 }
212
213 // Extra default features when MOZ_PROFILER_STARTUP is set (even if not
214 // available).
215 static constexpr uint32_t StartupExtraDefaultFeatures() {
216 // Enable mainthreadio by default for startup profiles as startup is heavy on
217 // I/O operations, and main thread I/O is really important to see there.
218 return ProfilerFeature::MainThreadIO | ProfilerFeature::IPCMessages;
219 }
220
221 // The auto-lock/unlock mutex that guards accesses to CorePS and ActivePS.
222 // Use `PSAutoLock lock;` to take the lock until the end of the enclosing block.
223 // External profilers may use this same lock for their own data, but as the lock
224 // is non-recursive, *only* `f(PSLockRef, ...)` functions below should be
225 // called, to avoid double-locking.
226 class MOZ_RAII PSAutoLock {
227 public:
228 PSAutoLock() : mLock(gPSMutex) {}
229
230 PSAutoLock(const PSAutoLock&) = delete;
231 void operator=(const PSAutoLock&) = delete;
232
233 [[nodiscard]] static bool IsLockedOnCurrentThread() {
234 return gPSMutex.IsLockedOnCurrentThread();
235 }
236
237 private:
238 static detail::BaseProfilerMutex gPSMutex;
239 detail::BaseProfilerAutoLock mLock;
240 };
241
242 MOZ_RUNINIT detail::BaseProfilerMutex PSAutoLock::gPSMutex{
243 "Base Profiler mutex"};
244
245 // Only functions that take a PSLockRef arg can access CorePS's and ActivePS's
246 // fields.
247 typedef const PSAutoLock& PSLockRef;
248
249 #define PS_GET(type_, name_) \
250 static type_ name_(PSLockRef) { \
251 MOZ_ASSERT(sInstance); \
252 return sInstance->m##name_; \
253 }
254
255 #define PS_GET_LOCKLESS(type_, name_) \
256 static type_ name_() { \
257 MOZ_ASSERT(sInstance); \
258 return sInstance->m##name_; \
259 }
260
261 #define PS_GET_AND_SET(type_, name_) \
262 PS_GET(type_, name_) \
263 static void Set##name_(PSLockRef, type_ a##name_) { \
264 MOZ_ASSERT(sInstance); \
265 sInstance->m##name_ = a##name_; \
266 }
267
268 // All functions in this file can run on multiple threads unless they have an
269 // NS_IsMainThread() assertion.
270
271 // This class contains the profiler's core global state, i.e. that which is
272 // valid even when the profiler is not active. Most profile operations can't do
273 // anything useful when this class is not instantiated, so we release-assert
274 // its non-nullness in all such operations.
275 //
276 // Accesses to CorePS are guarded by gPSMutex. Getters and setters take a
277 // PSAutoLock reference as an argument as proof that the gPSMutex is currently
278 // locked. This makes it clear when gPSMutex is locked and helps avoid
279 // accidental unlocked accesses to global state. There are ways to circumvent
280 // this mechanism, but please don't do so without *very* good reason and a
281 // detailed explanation.
282 //
283 // The exceptions to this rule:
284 //
285 // - mProcessStartTime, because it's immutable;
286 //
287 // - each thread's RacyRegisteredThread object is accessible without locking via
288 // TLSRegisteredThread::RacyRegisteredThread().
289 class CorePS {
290 private:
291 CorePS() : mProcessStartTime(TimeStamp::ProcessCreation()) {}
292
293 ~CorePS() {}
294
295 public:
296 static void Create(PSLockRef aLock) {
297 MOZ_ASSERT(!sInstance);
298 sInstance = new CorePS();
299 }
300
301 static void Destroy(PSLockRef aLock) {
302 MOZ_ASSERT(sInstance);
303 delete sInstance;
304 sInstance = nullptr;
305 }
306
307 // Unlike ActivePS::Exists(), CorePS::Exists() can be called without gPSMutex
308 // being locked. This is because CorePS is instantiated so early on the main
309 // thread that we don't have to worry about it being racy.
310 static bool Exists() { return !!sInstance; }
311
312 static void AddSizeOf(PSLockRef, MallocSizeOf aMallocSizeOf,
313 size_t& aProfSize, size_t& aLulSize) {
314 MOZ_ASSERT(sInstance);
315
316 aProfSize += aMallocSizeOf(sInstance);
317
318 for (auto& registeredThread : sInstance->mRegisteredThreads) {
319 aProfSize += registeredThread->SizeOfIncludingThis(aMallocSizeOf);
320 }
321
322 for (auto& registeredPage : sInstance->mRegisteredPages) {
323 aProfSize += registeredPage->SizeOfIncludingThis(aMallocSizeOf);
324 }
325
326 // Measurement of the following things may be added later if DMD finds it
327 // is worthwhile:
328 // - CorePS::mRegisteredThreads itself (its elements' children are
329 // measured above)
330 // - CorePS::mRegisteredPages itself (its elements' children are
331 // measured above)
332 // - CorePS::mInterposeObserver
333 }
334
335 // No PSLockRef is needed for this field because it's immutable.
336 PS_GET_LOCKLESS(const TimeStamp&, ProcessStartTime)
337
338 PS_GET(const Vector<UniquePtr<RegisteredThread>>&, RegisteredThreads)
339
340 static void AppendRegisteredThread(
341 PSLockRef, UniquePtr<RegisteredThread>&& aRegisteredThread) {
342 MOZ_ASSERT(sInstance);
343 MOZ_RELEASE_ASSERT(
344 sInstance->mRegisteredThreads.append(std::move(aRegisteredThread)));
345 }
346
347 static void RemoveRegisteredThread(PSLockRef,
348 RegisteredThread* aRegisteredThread) {
349 MOZ_ASSERT(sInstance);
350 // Remove aRegisteredThread from mRegisteredThreads.
351 for (UniquePtr<RegisteredThread>& rt : sInstance->mRegisteredThreads) {
352 if (rt.get() == aRegisteredThread) {
353 sInstance->mRegisteredThreads.erase(&rt);
354 return;
355 }
356 }
357 }
358
359 PS_GET(Vector<RefPtr<PageInformation>>&, RegisteredPages)
360
361 static void AppendRegisteredPage(PSLockRef,
362 RefPtr<PageInformation>&& aRegisteredPage) {
363 MOZ_ASSERT(sInstance);
364 struct RegisteredPageComparator {
365 PageInformation* aA;
366 bool operator()(PageInformation* aB) const { return aA->Equals(aB); }
367 };
368
369 auto foundPageIter = std::find_if(
370 sInstance->mRegisteredPages.begin(), sInstance->mRegisteredPages.end(),
371 RegisteredPageComparator{aRegisteredPage.get()});
372
373 if (foundPageIter != sInstance->mRegisteredPages.end()) {
374 if ((*foundPageIter)->Url() == "about:blank") {
375 // When a BrowsingContext is loaded, the first url loaded in it will be
376 // about:blank, and if the principal matches, the first document loaded
377 // in it will share an inner window. That's why we should delete the
378 // intermittent about:blank if they share the inner window.
379 sInstance->mRegisteredPages.erase(foundPageIter);
380 } else {
381 // Do not register the same page again.
382 return;
383 }
384 }
385 MOZ_RELEASE_ASSERT(
386 sInstance->mRegisteredPages.append(std::move(aRegisteredPage)));
387 }
388
389 static void RemoveRegisteredPage(PSLockRef,
390 uint64_t aRegisteredInnerWindowID) {
391 MOZ_ASSERT(sInstance);
392 // Remove RegisteredPage from mRegisteredPages by given inner window ID.
393 sInstance->mRegisteredPages.eraseIf([&](const RefPtr<PageInformation>& rd) {
394 return rd->InnerWindowID() == aRegisteredInnerWindowID;
395 });
396 }
397
398 static void ClearRegisteredPages(PSLockRef) {
399 MOZ_ASSERT(sInstance);
400 sInstance->mRegisteredPages.clear();
401 }
402
403 PS_GET(const Vector<BaseProfilerCount*>&, Counters)
404
405 static void AppendCounter(PSLockRef, BaseProfilerCount* aCounter) {
406 MOZ_ASSERT(sInstance);
407 // we don't own the counter; they may be stored in static objects
408 MOZ_RELEASE_ASSERT(sInstance->mCounters.append(aCounter));
409 }
410
411 static void RemoveCounter(PSLockRef, BaseProfilerCount* aCounter) {
412 // we may be called to remove a counter after the profiler is stopped or
413 // late in shutdown.
414 if (sInstance) {
415 auto* counter = std::find(sInstance->mCounters.begin(),
416 sInstance->mCounters.end(), aCounter);
417 MOZ_RELEASE_ASSERT(counter != sInstance->mCounters.end());
418 sInstance->mCounters.erase(counter);
419 }
420 }
421
422 PS_GET_AND_SET(const std::string&, ProcessName)
423 PS_GET_AND_SET(const std::string&, ETLDplus1)
424
425 private:
426 // The singleton instance
427 static CorePS* sInstance;
428
429 // The time that the process started.
430 const TimeStamp mProcessStartTime;
431
432 // Info on all the registered threads.
433 // ThreadIds in mRegisteredThreads are unique.
434 Vector<UniquePtr<RegisteredThread>> mRegisteredThreads;
435
436 // Info on all the registered pages.
437 // InnerWindowIDs in mRegisteredPages are unique.
438 Vector<RefPtr<PageInformation>> mRegisteredPages;
439
440 // Non-owning pointers to all active counters
441 Vector<BaseProfilerCount*> mCounters;
442
443 // Process name, provided by child process initialization code.
444 std::string mProcessName;
445 // Private name, provided by child process initialization code (eTLD+1 in
446 // fission)
447 std::string mETLDplus1;
448 };
449
450 CorePS* CorePS::sInstance = nullptr;
451
452 class SamplerThread;
453
454 static SamplerThread* NewSamplerThread(PSLockRef aLock, uint32_t aGeneration,
455 double aInterval, uint32_t aFeatures);
456
457 struct LiveProfiledThreadData {
458 RegisteredThread* mRegisteredThread;
459 UniquePtr<ProfiledThreadData> mProfiledThreadData;
460 };
461
462 // The buffer size is provided as a number of "entries", this is their size in
463 // bytes.
464 constexpr static uint32_t scBytesPerEntry = 8;
465
466 // This class contains the profiler's global state that is valid only when the
467 // profiler is active. When not instantiated, the profiler is inactive.
468 //
469 // Accesses to ActivePS are guarded by gPSMutex, in much the same fashion as
470 // CorePS.
471 //
472 class ActivePS {
473 private:
474 constexpr static uint32_t ChunkSizeForEntries(uint32_t aEntries) {
475 return uint32_t(std::min(size_t(ClampToAllowedEntries(aEntries)) *
476 scBytesPerEntry / scMinimumNumberOfChunks,
477 size_t(scMaximumChunkSize)));
478 }
479
480 static uint32_t AdjustFeatures(uint32_t aFeatures, uint32_t aFilterCount) {
481 // Filter out any features unavailable in this platform/configuration.
482 aFeatures &= AvailableFeatures();
483
484 // Some features imply others.
485 if (aFeatures & ProfilerFeature::FileIOAll) {
486 aFeatures |= ProfilerFeature::MainThreadIO | ProfilerFeature::FileIO;
487 } else if (aFeatures & ProfilerFeature::FileIO) {
488 aFeatures |= ProfilerFeature::MainThreadIO;
489 }
490
491 return aFeatures;
492 }
493
494 ActivePS(PSLockRef aLock, const TimeStamp& aProfilingStartTime,
495 PowerOfTwo32 aCapacity, double aInterval, uint32_t aFeatures,
496 const char** aFilters, uint32_t aFilterCount,
497 const Maybe<double>& aDuration)
498 : mProfilingStartTime(aProfilingStartTime),
499 mGeneration(sNextGeneration++),
500 mCapacity(aCapacity),
501 mDuration(aDuration),
502 mInterval(aInterval),
503 mFeatures(AdjustFeatures(aFeatures, aFilterCount)),
504 mProfileBufferChunkManager(
505 MakeUnique<ProfileBufferChunkManagerWithLocalLimit>(
506 size_t(ClampToAllowedEntries(aCapacity.Value())) *
507 scBytesPerEntry,
508 ChunkSizeForEntries(aCapacity.Value()))),
509 mProfileBuffer([this]() -> ProfileChunkedBuffer& {
510 ProfileChunkedBuffer& buffer = profiler_get_core_buffer();
511 buffer.SetChunkManager(*mProfileBufferChunkManager);
512 return buffer;
513 }()),
514 // The new sampler thread doesn't start sampling immediately because the
515 // main loop within Run() is blocked until this function's caller
516 // unlocks gPSMutex.
517 mSamplerThread(
518 NewSamplerThread(aLock, mGeneration, aInterval, aFeatures)),
519 mIsPaused(false),
520 mIsSamplingPaused(false) {
521 // Deep copy and lower-case aFilters.
522 MOZ_ALWAYS_TRUE(mFilters.resize(aFilterCount));
523 MOZ_ALWAYS_TRUE(mFiltersLowered.resize(aFilterCount));
524 for (uint32_t i = 0; i < aFilterCount; ++i) {
525 mFilters[i] = aFilters[i];
526 mFiltersLowered[i].reserve(mFilters[i].size());
527 std::transform(mFilters[i].cbegin(), mFilters[i].cend(),
528 std::back_inserter(mFiltersLowered[i]), ::tolower);
529 }
530 }
531
532 ~ActivePS() {
533 if (mProfileBufferChunkManager) {
534 // We still control the chunk manager, remove it from the core buffer.
535 profiler_get_core_buffer().ResetChunkManager();
536 }
537 }
538
539 bool ThreadSelected(const char* aThreadName) {
540 if (mFiltersLowered.empty()) {
541 return true;
542 }
543
544 std::string name = aThreadName;
545 std::transform(name.begin(), name.end(), name.begin(), ::tolower);
546
547 for (const auto& filter : mFiltersLowered) {
548 if (filter == "*") {
549 return true;
550 }
551
552 // Crude, non UTF-8 compatible, case insensitive substring search
553 if (name.find(filter) != std::string::npos) {
554 return true;
555 }
556
557 // If the filter is "pid:<my pid>", profile all threads.
558 if (mozilla::profiler::detail::FilterHasPid(filter.c_str())) {
559 return true;
560 }
561 }
562
563 return false;
564 }
565
566 public:
567 static void Create(PSLockRef aLock, const TimeStamp& aProfilingStartTime,
568 PowerOfTwo32 aCapacity, double aInterval,
569 uint32_t aFeatures, const char** aFilters,
570 uint32_t aFilterCount, const Maybe<double>& aDuration) {
571 MOZ_ASSERT(!sInstance);
572 sInstance = new ActivePS(aLock, aProfilingStartTime, aCapacity, aInterval,
573 aFeatures, aFilters, aFilterCount, aDuration);
574 }
575
576 [[nodiscard]] static SamplerThread* Destroy(PSLockRef aLock) {
577 MOZ_ASSERT(sInstance);
578 auto samplerThread = sInstance->mSamplerThread;
579 delete sInstance;
580 sInstance = nullptr;
581
582 return samplerThread;
583 }
584
585 static bool Exists(PSLockRef) { return !!sInstance; }
586
587 static bool Equals(PSLockRef, PowerOfTwo32 aCapacity,
588 const Maybe<double>& aDuration, double aInterval,
589 uint32_t aFeatures, const char** aFilters,
590 uint32_t aFilterCount) {
591 MOZ_ASSERT(sInstance);
592 if (sInstance->mCapacity != aCapacity ||
593 sInstance->mDuration != aDuration ||
594 sInstance->mInterval != aInterval ||
595 sInstance->mFeatures != aFeatures ||
596 sInstance->mFilters.length() != aFilterCount) {
597 return false;
598 }
599
600 for (uint32_t i = 0; i < sInstance->mFilters.length(); ++i) {
601 if (strcmp(sInstance->mFilters[i].c_str(), aFilters[i]) != 0) {
602 return false;
603 }
604 }
605 return true;
606 }
607
608 static size_t SizeOf(PSLockRef, MallocSizeOf aMallocSizeOf) {
609 MOZ_ASSERT(sInstance);
610
611 size_t n = aMallocSizeOf(sInstance);
612
613 n += sInstance->mProfileBuffer.SizeOfExcludingThis(aMallocSizeOf);
614
615 // Measurement of the following members may be added later if DMD finds it
616 // is worthwhile:
617 // - mLiveProfiledThreads (both the array itself, and the contents)
618 // - mDeadProfiledThreads (both the array itself, and the contents)
619 //
620
621 return n;
622 }
623
624 static UniquePtr<ProfileBufferChunkManagerWithLocalLimit>
625 ExtractBaseProfilerChunkManager(PSLockRef) {
626 MOZ_ASSERT(sInstance);
627 return std::move(sInstance->mProfileBufferChunkManager);
628 }
629
630 static bool ShouldProfileThread(PSLockRef aLock, ThreadInfo* aInfo) {
631 MOZ_ASSERT(sInstance);
632 return sInstance->ThreadSelected(aInfo->Name());
633 }
634
635 PS_GET_LOCKLESS(TimeStamp, ProfilingStartTime)
636
637 PS_GET(uint32_t, Generation)
638
639 PS_GET(PowerOfTwo32, Capacity)
640
641 PS_GET(Maybe<double>, Duration)
642
643 PS_GET(double, Interval)
644
645 PS_GET(uint32_t, Features)
646
647 #define PS_GET_FEATURE(n_, str_, Name_, desc_) \
648 static bool Feature##Name_(PSLockRef) { \
649 MOZ_ASSERT(sInstance); \
650 return ProfilerFeature::Has##Name_(sInstance->mFeatures); \
651 }
652
653 BASE_PROFILER_FOR_EACH_FEATURE(PS_GET_FEATURE)
654
655 #undef PS_GET_FEATURE
656
657 PS_GET(const Vector<std::string>&, Filters)
658 PS_GET(const Vector<std::string>&, FiltersLowered)
659
660 static void FulfillChunkRequests(PSLockRef) {
661 MOZ_ASSERT(sInstance);
662 if (sInstance->mProfileBufferChunkManager) {
663 sInstance->mProfileBufferChunkManager->FulfillChunkRequests();
664 }
665 }
666
667 static ProfileBuffer& Buffer(PSLockRef) {
668 MOZ_ASSERT(sInstance);
669 return sInstance->mProfileBuffer;
670 }
671
672 static const Vector<LiveProfiledThreadData>& LiveProfiledThreads(PSLockRef) {
673 MOZ_ASSERT(sInstance);
674 return sInstance->mLiveProfiledThreads;
675 }
676
677 // Returns an array containing (RegisteredThread*, ProfiledThreadData*) pairs
678 // for all threads that should be included in a profile, both for threads
679 // that are still registered, and for threads that have been unregistered but
680 // still have data in the buffer.
681 // For threads that have already been unregistered, the RegisteredThread
682 // pointer will be null.
683 // The returned array is sorted by thread register time.
684 // Do not hold on to the return value across thread registration or profiler
685 // restarts.
686 static Vector<std::pair<RegisteredThread*, ProfiledThreadData*>>
687 ProfiledThreads(PSLockRef) {
688 MOZ_ASSERT(sInstance);
689 Vector<std::pair<RegisteredThread*, ProfiledThreadData*>> array;
690 MOZ_RELEASE_ASSERT(
691 array.initCapacity(sInstance->mLiveProfiledThreads.length() +
692 sInstance->mDeadProfiledThreads.length()));
693 for (auto& t : sInstance->mLiveProfiledThreads) {
694 MOZ_RELEASE_ASSERT(array.append(
695 std::make_pair(t.mRegisteredThread, t.mProfiledThreadData.get())));
696 }
697 for (auto& t : sInstance->mDeadProfiledThreads) {
698 MOZ_RELEASE_ASSERT(
699 array.append(std::make_pair((RegisteredThread*)nullptr, t.get())));
700 }
701
702 std::sort(array.begin(), array.end(),
703 [](const std::pair<RegisteredThread*, ProfiledThreadData*>& a,
704 const std::pair<RegisteredThread*, ProfiledThreadData*>& b) {
705 return a.second->Info()->RegisterTime() <
706 b.second->Info()->RegisterTime();
707 });
708 return array;
709 }
710
711 static Vector<RefPtr<PageInformation>> ProfiledPages(PSLockRef aLock) {
712 MOZ_ASSERT(sInstance);
713 Vector<RefPtr<PageInformation>> array;
714 for (auto& d : CorePS::RegisteredPages(aLock)) {
715 MOZ_RELEASE_ASSERT(array.append(d));
716 }
717 for (auto& d : sInstance->mDeadProfiledPages) {
718 MOZ_RELEASE_ASSERT(array.append(d));
719 }
720 // We don't need to sort the pages like threads since we won't show them
721 // as a list.
722 return array;
723 }
724
725 // Do a linear search through mLiveProfiledThreads to find the
726 // ProfiledThreadData object for a RegisteredThread.
727 static ProfiledThreadData* GetProfiledThreadData(
728 PSLockRef, RegisteredThread* aRegisteredThread) {
729 MOZ_ASSERT(sInstance);
730 for (const LiveProfiledThreadData& thread :
731 sInstance->mLiveProfiledThreads) {
732 if (thread.mRegisteredThread == aRegisteredThread) {
733 return thread.mProfiledThreadData.get();
734 }
735 }
736 return nullptr;
737 }
738
739 static ProfiledThreadData* AddLiveProfiledThread(
740 PSLockRef, RegisteredThread* aRegisteredThread,
741 UniquePtr<ProfiledThreadData>&& aProfiledThreadData) {
742 MOZ_ASSERT(sInstance);
743 MOZ_RELEASE_ASSERT(
744 sInstance->mLiveProfiledThreads.append(LiveProfiledThreadData{
745 aRegisteredThread, std::move(aProfiledThreadData)}));
746
747 // Return a weak pointer to the ProfiledThreadData object.
748 return sInstance->mLiveProfiledThreads.back().mProfiledThreadData.get();
749 }
750
751 static void UnregisterThread(PSLockRef aLockRef,
752 RegisteredThread* aRegisteredThread) {
753 MOZ_ASSERT(sInstance);
754
755 DiscardExpiredDeadProfiledThreads(aLockRef);
756
757 // Find the right entry in the mLiveProfiledThreads array and remove the
758 // element, moving the ProfiledThreadData object for the thread into the
759 // mDeadProfiledThreads array.
760 // The thread's RegisteredThread object gets destroyed here.
761 for (size_t i = 0; i < sInstance->mLiveProfiledThreads.length(); i++) {
762 LiveProfiledThreadData& thread = sInstance->mLiveProfiledThreads[i];
763 if (thread.mRegisteredThread == aRegisteredThread) {
764 thread.mProfiledThreadData->NotifyUnregistered(
765 sInstance->mProfileBuffer.BufferRangeEnd());
766 MOZ_RELEASE_ASSERT(sInstance->mDeadProfiledThreads.append(
767 std::move(thread.mProfiledThreadData)));
768 sInstance->mLiveProfiledThreads.erase(
769 &sInstance->mLiveProfiledThreads[i]);
770 return;
771 }
772 }
773 }
774
775 PS_GET_AND_SET(bool, IsPaused)
776
777 // True if sampling is paused (though generic `SetIsPaused()` or specific
778 // `SetIsSamplingPaused()`).
779 static bool IsSamplingPaused(PSLockRef lock) {
780 MOZ_ASSERT(sInstance);
781 return IsPaused(lock) || sInstance->mIsSamplingPaused;
782 }
783
784 static void SetIsSamplingPaused(PSLockRef, bool aIsSamplingPaused) {
785 MOZ_ASSERT(sInstance);
786 sInstance->mIsSamplingPaused = aIsSamplingPaused;
787 }
788
789 static void DiscardExpiredDeadProfiledThreads(PSLockRef) {
790 MOZ_ASSERT(sInstance);
791 uint64_t bufferRangeStart = sInstance->mProfileBuffer.BufferRangeStart();
792 // Discard any dead threads that were unregistered before bufferRangeStart.
793 sInstance->mDeadProfiledThreads.eraseIf(
794 [bufferRangeStart](
795 const UniquePtr<ProfiledThreadData>& aProfiledThreadData) {
796 Maybe<uint64_t> bufferPosition =
797 aProfiledThreadData->BufferPositionWhenUnregistered();
798 MOZ_RELEASE_ASSERT(bufferPosition,
799 "should have unregistered this thread");
800 return *bufferPosition < bufferRangeStart;
801 });
802 }
803
804 static void UnregisterPage(PSLockRef aLock,
805 uint64_t aRegisteredInnerWindowID) {
806 MOZ_ASSERT(sInstance);
807 auto& registeredPages = CorePS::RegisteredPages(aLock);
808 for (size_t i = 0; i < registeredPages.length(); i++) {
809 RefPtr<PageInformation>& page = registeredPages[i];
810 if (page->InnerWindowID() == aRegisteredInnerWindowID) {
811 page->NotifyUnregistered(sInstance->mProfileBuffer.BufferRangeEnd());
812 MOZ_RELEASE_ASSERT(
813 sInstance->mDeadProfiledPages.append(std::move(page)));
814 registeredPages.erase(&registeredPages[i--]);
815 }
816 }
817 }
818
819 static void DiscardExpiredPages(PSLockRef) {
820 MOZ_ASSERT(sInstance);
821 uint64_t bufferRangeStart = sInstance->mProfileBuffer.BufferRangeStart();
822 // Discard any dead pages that were unregistered before
823 // bufferRangeStart.
824 sInstance->mDeadProfiledPages.eraseIf(
825 [bufferRangeStart](const RefPtr<PageInformation>& aProfiledPage) {
826 Maybe<uint64_t> bufferPosition =
827 aProfiledPage->BufferPositionWhenUnregistered();
828 MOZ_RELEASE_ASSERT(bufferPosition,
829 "should have unregistered this page");
830 return *bufferPosition < bufferRangeStart;
831 });
832 }
833
834 static void ClearUnregisteredPages(PSLockRef) {
835 MOZ_ASSERT(sInstance);
836 sInstance->mDeadProfiledPages.clear();
837 }
838
839 static void ClearExpiredExitProfiles(PSLockRef) {
840 MOZ_ASSERT(sInstance);
841 uint64_t bufferRangeStart = sInstance->mProfileBuffer.BufferRangeStart();
842 // Discard exit profiles that were gathered before our buffer RangeStart.
843 sInstance->mExitProfiles.eraseIf(
844 [bufferRangeStart](const ExitProfile& aExitProfile) {
845 return aExitProfile.mBufferPositionAtGatherTime < bufferRangeStart;
846 });
847 }
848
849 static void AddExitProfile(PSLockRef aLock, const std::string& aExitProfile) {
850 MOZ_ASSERT(sInstance);
851
852 ClearExpiredExitProfiles(aLock);
853
854 MOZ_RELEASE_ASSERT(sInstance->mExitProfiles.append(
855 ExitProfile{aExitProfile, sInstance->mProfileBuffer.BufferRangeEnd()}));
856 }
857
858 static Vector<std::string> MoveExitProfiles(PSLockRef aLock) {
859 MOZ_ASSERT(sInstance);
860
861 ClearExpiredExitProfiles(aLock);
862
863 Vector<std::string> profiles;
864 MOZ_RELEASE_ASSERT(
865 profiles.initCapacity(sInstance->mExitProfiles.length()));
866 for (auto& profile : sInstance->mExitProfiles) {
867 MOZ_RELEASE_ASSERT(profiles.append(std::move(profile.mJSON)));
868 }
869 sInstance->mExitProfiles.clear();
870 return profiles;
871 }
872
873 private:
874 // The singleton instance.
875 static ActivePS* sInstance;
876
877 const TimeStamp mProfilingStartTime;
878
879 // We need to track activity generations. If we didn't we could have the
880 // following scenario.
881 //
882 // - profiler_stop() locks gPSMutex, de-instantiates ActivePS, unlocks
883 // gPSMutex, deletes the SamplerThread (which does a join).
884 //
885 // - profiler_start() runs on a different thread, locks gPSMutex,
886 // re-instantiates ActivePS, unlocks gPSMutex -- all before the join
887 // completes.
888 //
889 // - SamplerThread::Run() locks gPSMutex, sees that ActivePS is instantiated,
890 // and continues as if the start/stop pair didn't occur. Also
891 // profiler_stop() is stuck, unable to finish.
892 //
893 // By checking ActivePS *and* the generation, we can avoid this scenario.
894 // sNextGeneration is used to track the next generation number; it is static
895 // because it must persist across different ActivePS instantiations.
896 const uint32_t mGeneration;
897 static uint32_t sNextGeneration;
898
899 // The maximum number of 8-byte entries in mProfileBuffer.
900 const PowerOfTwo32 mCapacity;
901
902 // The maximum duration of entries in mProfileBuffer, in seconds.
903 const Maybe<double> mDuration;
904
905 // The interval between samples, measured in milliseconds.
906 const double mInterval;
907
908 // The profile features that are enabled.
909 const uint32_t mFeatures;
910
911 // Substrings of names of threads we want to profile.
912 Vector<std::string> mFilters;
913 Vector<std::string> mFiltersLowered;
914
915 // The chunk manager used by `mProfileBuffer` below.
916 // May become null if it gets transferred to the Gecko Profiler.
917 UniquePtr<ProfileBufferChunkManagerWithLocalLimit> mProfileBufferChunkManager;
918
919 // The buffer into which all samples are recorded.
920 ProfileBuffer mProfileBuffer;
921
922 // ProfiledThreadData objects for any threads that were profiled at any point
923 // during this run of the profiler:
924 // - mLiveProfiledThreads contains all threads that are still registered, and
925 // - mDeadProfiledThreads contains all threads that have already been
926 // unregistered but for which there is still data in the profile buffer.
927 Vector<LiveProfiledThreadData> mLiveProfiledThreads;
928 Vector<UniquePtr<ProfiledThreadData>> mDeadProfiledThreads;
929
930 // Info on all the dead pages.
931 // Registered pages are being moved to this array after unregistration.
932 // We are keeping them in case we need them in the profile data.
933 // We are removing them when we ensure that we won't need them anymore.
934 Vector<RefPtr<PageInformation>> mDeadProfiledPages;
935
936 // The current sampler thread. This class is not responsible for destroying
937 // the SamplerThread object; the Destroy() method returns it so the caller
938 // can destroy it.
939 SamplerThread* const mSamplerThread;
940
941 // Is the profiler fully paused?
942 bool mIsPaused;
943
944 // Is the profiler periodic sampling paused?
945 bool mIsSamplingPaused;
946
947 struct ExitProfile {
948 std::string mJSON;
949 uint64_t mBufferPositionAtGatherTime;
950 };
951 Vector<ExitProfile> mExitProfiles;
952 };
953
954 ActivePS* ActivePS::sInstance = nullptr;
955 uint32_t ActivePS::sNextGeneration = 0;
956
957 #undef PS_GET
958 #undef PS_GET_LOCKLESS
959 #undef PS_GET_AND_SET
960
961 namespace detail {
962
963 TimeStamp GetProfilingStartTime() {
964 if (!CorePS::Exists()) {
965 return {};
966 }
967 PSAutoLock lock;
968 if (!ActivePS::Exists(lock)) {
969 return {};
970 }
971 return ActivePS::ProfilingStartTime();
972 }
973
974 [[nodiscard]] MFBT_API UniquePtr<ProfileBufferChunkManagerWithLocalLimit>
975 ExtractBaseProfilerChunkManager() {
976 PSAutoLock lock;
977 if (MOZ_UNLIKELY(!ActivePS::Exists(lock))) {
978 return nullptr;
979 }
980 return ActivePS::ExtractBaseProfilerChunkManager(lock);
981 }
982
983 } // namespace detail
984
985 MFBT_DATA Atomic<uint32_t, MemoryOrdering::Relaxed>
986 RacyFeatures::sActiveAndFeatures(0);
987
988 /* static */
989 void RacyFeatures::SetActive(uint32_t aFeatures) {
990 sActiveAndFeatures = Active | aFeatures;
991 }
992
993 /* static */
994 void RacyFeatures::SetInactive() { sActiveAndFeatures = 0; }
995
996 /* static */
997 bool RacyFeatures::IsActive() { return uint32_t(sActiveAndFeatures) & Active; }
998
999 /* static */
1000 void RacyFeatures::SetPaused() { sActiveAndFeatures |= Paused; }
1001
1002 /* static */
1003 void RacyFeatures::SetUnpaused() { sActiveAndFeatures &= ~Paused; }
1004
1005 /* static */
1006 void RacyFeatures::SetSamplingPaused() { sActiveAndFeatures |= SamplingPaused; }
1007
1008 /* static */
1009 void RacyFeatures::SetSamplingUnpaused() {
1010 sActiveAndFeatures &= ~SamplingPaused;
1011 }
1012
1013 /* static */
1014 bool RacyFeatures::IsActiveWithFeature(uint32_t aFeature) {
1015 uint32_t af = sActiveAndFeatures; // copy it first
1016 return (af & Active) && (af & aFeature);
1017 }
1018
1019 /* static */
1020 bool RacyFeatures::IsActiveWithoutFeature(uint32_t aFeature) {
1021 uint32_t af = sActiveAndFeatures; // copy it first
1022 return (af & Active) && !(af & aFeature);
1023 }
1024
1025 /* static */
1026 bool RacyFeatures::IsActiveAndUnpaused() {
1027 uint32_t af = sActiveAndFeatures; // copy it first
1028 return (af & Active) && !(af & Paused);
1029 }
1030
1031 /* static */
1032 bool RacyFeatures::IsActiveAndSamplingUnpaused() {
1033 uint32_t af = sActiveAndFeatures; // copy it first
1034 return (af & Active) && !(af & (Paused | SamplingPaused));
1035 }
1036
1037 // Each live thread has a RegisteredThread, and we store a reference to it in
1038 // TLS. This class encapsulates that TLS.
1039 class TLSRegisteredThread {
1040 public:
1041 static bool Init(PSLockRef) {
1042 bool ok1 = sRegisteredThread.init();
1043 bool ok2 = AutoProfilerLabel::sProfilingStack.init();
1044 return ok1 && ok2;
1045 }
1046
1047 // Get the entire RegisteredThread. Accesses are guarded by gPSMutex.
1048 static class RegisteredThread* RegisteredThread(PSLockRef) {
1049 return sRegisteredThread.get();
1050 }
1051
1052 // Get only the RacyRegisteredThread. Accesses are not guarded by gPSMutex.
1053 static class RacyRegisteredThread* RacyRegisteredThread() {
1054 class RegisteredThread* registeredThread = sRegisteredThread.get();
1055 return registeredThread ? &registeredThread->RacyRegisteredThread()
1056 : nullptr;
1057 }
1058
1059 // Get only the ProfilingStack. Accesses are not guarded by gPSMutex.
1060 // RacyRegisteredThread() can also be used to get the ProfilingStack, but that
1061 // is marginally slower because it requires an extra pointer indirection.
1062 static ProfilingStack* Stack() {
1063 return AutoProfilerLabel::sProfilingStack.get();
1064 }
1065
1066 static void SetRegisteredThread(PSLockRef,
1067 class RegisteredThread* aRegisteredThread) {
1068 sRegisteredThread.set(aRegisteredThread);
1069 AutoProfilerLabel::sProfilingStack.set(
1070 aRegisteredThread
1071 ? &aRegisteredThread->RacyRegisteredThread().ProfilingStack()
1072 : nullptr);
1073 }
1074
1075 private:
1076 // This is a non-owning reference to the RegisteredThread;
1077 // CorePS::mRegisteredThreads is the owning reference. On thread
1078 // deregistration, this reference is cleared and the RegisteredThread is
1079 // destroyed.
1080 static MOZ_THREAD_LOCAL(class RegisteredThread*) sRegisteredThread;
1081 };
1082
1083 MOZ_THREAD_LOCAL(RegisteredThread*) TLSRegisteredThread::sRegisteredThread;
1084
1085 /* static */
1086 ProfilingStack* AutoProfilerLabel::GetProfilingStack() {
1087 return sProfilingStack.get();
1088 }
1089
1090 // Although you can access a thread's ProfilingStack via
1091 // TLSRegisteredThread::sRegisteredThread, we also have a second TLS pointer
1092 // directly to the ProfilingStack. Here's why.
1093 //
1094 // - We need to be able to push to and pop from the ProfilingStack in
1095 // AutoProfilerLabel.
1096 //
1097 // - The class functions are hot and must be defined in BaseProfiler.h so they
1098 // can be inlined.
1099 //
1100 // - We don't want to expose TLSRegisteredThread (and RegisteredThread) in
1101 // BaseProfiler.h.
1102 //
1103 // This second pointer isn't ideal, but does provide a way to satisfy those
1104 // constraints. TLSRegisteredThread is responsible for updating it.
1105 MOZ_THREAD_LOCAL(ProfilingStack*) AutoProfilerLabel::sProfilingStack;
1106
1107 namespace detail {
1108
1109 [[nodiscard]] MFBT_API TimeStamp GetThreadRegistrationTime() {
1110 if (!CorePS::Exists()) {
1111 return {};
1112 }
1113
1114 PSAutoLock lock;
1115
1116 RegisteredThread* registeredThread =
1117 TLSRegisteredThread::RegisteredThread(lock);
1118 if (!registeredThread) {
1119 return {};
1120 }
1121
1122 return registeredThread->Info()->RegisterTime();
1123 }
1124
1125 } // namespace detail
1126
1127 // The name of the main thread.
1128 static const char* const kMainThreadName = "GeckoMain";
1129
1130 ////////////////////////////////////////////////////////////////////////
1131 // BEGIN sampling/unwinding code
1132
1133 // Additional registers that have to be saved when thread is paused.
1134 #if defined(GP_PLAT_x86_linux) || defined(GP_PLAT_x86_android) || \
1135 defined(GP_ARCH_x86)
1136 # define UNWINDING_REGS_HAVE_ECX_EDX
1137 #elif defined(GP_PLAT_amd64_linux) || defined(GP_PLAT_amd64_android) || \
1138 defined(GP_PLAT_amd64_freebsd) || defined(GP_ARCH_amd64) || \
1139 defined(__x86_64__)
1140 # define UNWINDING_REGS_HAVE_R10_R12
1141 #elif defined(GP_PLAT_arm_linux) || defined(GP_PLAT_arm_android)
1142 # define UNWINDING_REGS_HAVE_LR_R7
1143 #elif defined(GP_PLAT_arm64_linux) || defined(GP_PLAT_arm64_android) || \
1144 defined(GP_PLAT_arm64_freebsd) || defined(GP_ARCH_arm64) || \
1145 defined(__aarch64__)
1146 # define UNWINDING_REGS_HAVE_LR_R11
1147 #endif
1148
1149 // The registers used for stack unwinding and a few other sampling purposes.
1150 // The ctor does nothing; users are responsible for filling in the fields.
1151 class Registers {
1152 public:
1153 Registers()
1154 : mPC{nullptr},
1155 mSP{nullptr},
1156 mFP{nullptr}
1157 #if defined(UNWINDING_REGS_HAVE_ECX_EDX)
1158 ,
1159 mEcx{nullptr},
1160 mEdx{nullptr}
1161 #elif defined(UNWINDING_REGS_HAVE_R10_R12)
1162 ,
1163 mR10{nullptr},
1164 mR12{nullptr}
1165 #elif defined(UNWINDING_REGS_HAVE_LR_R7)
1166 ,
1167 mLR{nullptr},
1168 mR7{nullptr}
1169 #elif defined(UNWINDING_REGS_HAVE_LR_R11)
1170 ,
1171 mLR{nullptr},
1172 mR11{nullptr}
1173 #endif
1174 {
1175 }
1176
1177 void Clear() { memset(this, 0, sizeof(*this)); }
1178
1179 // These fields are filled in by
1180 // Sampler::SuspendAndSampleAndResumeThread() for periodic and backtrace
1181 // samples, and by REGISTERS_SYNC_POPULATE for synchronous samples.
1182 Address mPC; // Instruction pointer.
1183 Address mSP; // Stack pointer.
1184 Address mFP; // Frame pointer.
1185 #if defined(UNWINDING_REGS_HAVE_ECX_EDX)
1186 Address mEcx; // Temp for return address.
1187 Address mEdx; // Temp for frame pointer.
1188 #elif defined(UNWINDING_REGS_HAVE_R10_R12)
1189 Address mR10; // Temp for return address.
1190 Address mR12; // Temp for frame pointer.
1191 #elif defined(UNWINDING_REGS_HAVE_LR_R7)
1192 Address mLR; // ARM link register, or temp for return address.
1193 Address mR7; // Temp for frame pointer.
1194 #elif defined(UNWINDING_REGS_HAVE_LR_R11)
1195 Address mLR; // ARM link register, or temp for return address.
1196 Address mR11; // Temp for frame pointer.
1197 #endif
1198
1199 #if defined(GP_OS_linux) || defined(GP_OS_android) || defined(GP_OS_freebsd)
1200 // This contains all the registers, which means it duplicates the four fields
1201 // above. This is ok.
1202 ucontext_t* mContext; // The context from the signal handler.
1203 #endif
1204 };
1205
1206 // Setting MAX_NATIVE_FRAMES too high risks the unwinder wasting a lot of time
1207 // looping on corrupted stacks.
1208 static const size_t MAX_NATIVE_FRAMES = 1024;
1209
1210 struct NativeStack {
1211 void* mPCs[MAX_NATIVE_FRAMES];
1212 void* mSPs[MAX_NATIVE_FRAMES];
1213 size_t mCount; // Number of frames filled.
1214
1215 NativeStack() : mPCs(), mSPs(), mCount(0) {}
1216 };
1217
1218 // Merges the profiling stack and native stack, outputting the details to
1219 // aCollector.
1220 static void MergeStacks(bool aIsSynchronous,
1221 const RegisteredThread& aRegisteredThread,
1222 const NativeStack& aNativeStack,
1223 ProfilerStackCollector& aCollector) {
1224 // WARNING: this function runs within the profiler's "critical section".
1225 // WARNING: this function might be called while the profiler is inactive, and
1226 // cannot rely on ActivePS.
1227
1228 const ProfilingStack& profilingStack =
1229 aRegisteredThread.RacyRegisteredThread().ProfilingStack();
1230 const ProfilingStackFrame* profilingStackFrames = profilingStack.frames;
1231 uint32_t profilingStackFrameCount = profilingStack.stackSize();
1232
1233 Maybe<uint64_t> samplePosInBuffer;
1234 if (!aIsSynchronous) {
1235 // aCollector.SamplePositionInBuffer() will return Nothing() when
1236 // profiler_suspend_and_sample_thread is called from the background hang
1237 // reporter.
1238 samplePosInBuffer = aCollector.SamplePositionInBuffer();
1239 }
1240 // While the profiling stack array is ordered oldest-to-youngest, the JS and
1241 // native arrays are ordered youngest-to-oldest. We must add frames to aInfo
1242 // oldest-to-youngest. Thus, iterate over the profiling stack forwards and JS
1243 // and native arrays backwards. Note: this means the terminating condition
1244 // jsIndex and nativeIndex is being < 0.
1245 uint32_t profilingStackIndex = 0;
1246 int32_t nativeIndex = aNativeStack.mCount - 1;
1247
1248 uint8_t* lastLabelFrameStackAddr = nullptr;
1249
1250 // Iterate as long as there is at least one frame remaining.
1251 while (profilingStackIndex != profilingStackFrameCount || nativeIndex >= 0) {
1252 // There are 1 to 3 frames available. Find and add the oldest.
1253 uint8_t* profilingStackAddr = nullptr;
1254 uint8_t* nativeStackAddr = nullptr;
1255
1256 if (profilingStackIndex != profilingStackFrameCount) {
1257 const ProfilingStackFrame& profilingStackFrame =
1258 profilingStackFrames[profilingStackIndex];
1259
1260 if (profilingStackFrame.isLabelFrame() ||
1261 profilingStackFrame.isSpMarkerFrame()) {
1262 lastLabelFrameStackAddr = (uint8_t*)profilingStackFrame.stackAddress();
1263 }
1264
1265 // Skip any JS_OSR frames. Such frames are used when the JS interpreter
1266 // enters a jit frame on a loop edge (via on-stack-replacement, or OSR).
1267 // To avoid both the profiling stack frame and jit frame being recorded
1268 // (and showing up twice), the interpreter marks the interpreter
1269 // profiling stack frame as JS_OSR to ensure that it doesn't get counted.
1270 if (profilingStackFrame.isOSRFrame()) {
1271 profilingStackIndex++;
1272 continue;
1273 }
1274
1275 MOZ_ASSERT(lastLabelFrameStackAddr);
1276 profilingStackAddr = lastLabelFrameStackAddr;
1277 }
1278
1279 if (nativeIndex >= 0) {
1280 nativeStackAddr = (uint8_t*)aNativeStack.mSPs[nativeIndex];
1281 }
1282
1283 // If there's a native stack frame which has the same SP as a profiling
1284 // stack frame, pretend we didn't see the native stack frame. Ditto for a
1285 // native stack frame which has the same SP as a JS stack frame. In effect
1286 // this means profiling stack frames or JS frames trump conflicting native
1287 // frames.
1288 if (nativeStackAddr && (profilingStackAddr == nativeStackAddr)) {
1289 nativeStackAddr = nullptr;
1290 nativeIndex--;
1291 MOZ_ASSERT(profilingStackAddr);
1292 }
1293
1294 // Sanity checks.
1295 MOZ_ASSERT_IF(profilingStackAddr, profilingStackAddr != nativeStackAddr);
1296 MOZ_ASSERT_IF(nativeStackAddr, nativeStackAddr != profilingStackAddr);
1297
1298 // Check to see if profiling stack frame is top-most.
1299 if (profilingStackAddr > nativeStackAddr) {
1300 MOZ_ASSERT(profilingStackIndex < profilingStackFrameCount);
1301 const ProfilingStackFrame& profilingStackFrame =
1302 profilingStackFrames[profilingStackIndex];
1303
1304 // Sp marker frames are just annotations and should not be recorded in
1305 // the profile.
1306 if (!profilingStackFrame.isSpMarkerFrame()) {
1307 if (aIsSynchronous && profilingStackFrame.categoryPair() ==
1308 ProfilingCategoryPair::PROFILER) {
1309 // For stacks captured synchronously (ie. marker stacks), stop
1310 // walking the stack as soon as we enter the profiler category,
1311 // to avoid showing profiler internal code in marker stacks.
1312 return;
1313 }
1314 aCollector.CollectProfilingStackFrame(profilingStackFrame);
1315 }
1316 profilingStackIndex++;
1317 continue;
1318 }
1319
1320 // If we reach here, there must be a native stack frame and it must be the
1321 // greatest frame.
1322 if (nativeStackAddr) {
1323 MOZ_ASSERT(nativeIndex >= 0);
1324 void* addr = (void*)aNativeStack.mPCs[nativeIndex];
1325 aCollector.CollectNativeLeafAddr(addr);
1326 }
1327 if (nativeIndex >= 0) {
1328 nativeIndex--;
1329 }
1330 }
1331 }
1332
1333 #if defined(GP_OS_windows) && defined(USE_MOZ_STACK_WALK)
1334 static HANDLE GetThreadHandle(PlatformData* aData);
1335 #endif
1336
1337 #if defined(USE_FRAME_POINTER_STACK_WALK) || defined(USE_MOZ_STACK_WALK)
1338 static void StackWalkCallback(uint32_t aFrameNumber, void* aPC, void* aSP,
1339 void* aClosure) {
1340 NativeStack* nativeStack = static_cast<NativeStack*>(aClosure);
1341 MOZ_ASSERT(nativeStack->mCount < MAX_NATIVE_FRAMES);
1342 nativeStack->mSPs[nativeStack->mCount] = aSP;
1343 nativeStack->mPCs[nativeStack->mCount] = aPC;
1344 nativeStack->mCount++;
1345 }
1346 #endif
1347
1348 #if defined(USE_FRAME_POINTER_STACK_WALK)
1349 static void DoFramePointerBacktrace(PSLockRef aLock,
1350 const RegisteredThread& aRegisteredThread,
1351 const Registers& aRegs,
1352 NativeStack& aNativeStack) {
1353 // WARNING: this function runs within the profiler's "critical section".
1354 // WARNING: this function might be called while the profiler is inactive, and
1355 // cannot rely on ActivePS.
1356
1357 // Start with the current function. We use 0 as the frame number here because
1358 // the FramePointerStackWalk() call below will use 1..N. This is a bit weird
1359 // but it doesn't matter because StackWalkCallback() doesn't use the frame
1360 // number argument.
1361 StackWalkCallback(/* frameNum */ 0, aRegs.mPC, aRegs.mSP, &aNativeStack);
1362
1363 uint32_t maxFrames = uint32_t(MAX_NATIVE_FRAMES - aNativeStack.mCount);
1364
1365 const void* stackEnd = aRegisteredThread.StackTop();
1366 if (aRegs.mFP >= aRegs.mSP && aRegs.mFP <= stackEnd) {
1367 FramePointerStackWalk(StackWalkCallback, maxFrames, &aNativeStack,
1368 reinterpret_cast<void**>(aRegs.mFP),
1369 const_cast<void*>(stackEnd));
1370 }
1371 }
1372 #endif
1373
1374 #if defined(USE_MOZ_STACK_WALK)
1375 static void DoMozStackWalkBacktrace(PSLockRef aLock,
1376 const RegisteredThread& aRegisteredThread,
1377 const Registers& aRegs,
1378 NativeStack& aNativeStack) {
1379 // WARNING: this function runs within the profiler's "critical section".
1380 // WARNING: this function might be called while the profiler is inactive, and
1381 // cannot rely on ActivePS.
1382
1383 // Start with the current function. We use 0 as the frame number here because
1384 // the MozStackWalkThread() call below will use 1..N. This is a bit weird but
1385 // it doesn't matter because StackWalkCallback() doesn't use the frame number
1386 // argument.
1387 StackWalkCallback(/* frameNum */ 0, aRegs.mPC, aRegs.mSP, &aNativeStack);
1388
1389 uint32_t maxFrames = uint32_t(MAX_NATIVE_FRAMES - aNativeStack.mCount);
1390
1391 HANDLE thread = GetThreadHandle(aRegisteredThread.GetPlatformData());
1392 MOZ_ASSERT(thread);
1393 MozStackWalkThread(StackWalkCallback, maxFrames, &aNativeStack, thread,
1394 /* context */ nullptr);
1395 }
1396 #endif
1397
1398 #ifdef USE_EHABI_STACKWALK
1399 static void DoEHABIBacktrace(PSLockRef aLock,
1400 const RegisteredThread& aRegisteredThread,
1401 const Registers& aRegs,
1402 NativeStack& aNativeStack) {
1403 // WARNING: this function runs within the profiler's "critical section".
1404 // WARNING: this function might be called while the profiler is inactive, and
1405 // cannot rely on ActivePS.
1406
1407 aNativeStack.mCount =
1408 EHABIStackWalk(aRegs.mContext->uc_mcontext,
1409 const_cast<void*>(aRegisteredThread.StackTop()),
1410 aNativeStack.mSPs, aNativeStack.mPCs, MAX_NATIVE_FRAMES);
1411 }
1412 #endif
1413
1414 #ifdef HAVE_NATIVE_UNWIND
1415 static void DoNativeBacktrace(PSLockRef aLock,
1416 const RegisteredThread& aRegisteredThread,
1417 const Registers& aRegs,
1418 NativeStack& aNativeStack) {
1419 // This method determines which stackwalker is used for periodic and
1420 // synchronous samples. (Backtrace samples are treated differently, see
1421 // profiler_suspend_and_sample_thread() for details). The only part of the
1422 // ordering that matters is that LUL must precede FRAME_POINTER, because on
1423 // Linux they can both be present.
1424 # if defined(USE_EHABI_STACKWALK)
1425 DoEHABIBacktrace(aLock, aRegisteredThread, aRegs, aNativeStack);
1426 # elif defined(USE_FRAME_POINTER_STACK_WALK)
1427 DoFramePointerBacktrace(aLock, aRegisteredThread, aRegs, aNativeStack);
1428 # elif defined(USE_MOZ_STACK_WALK)
1429 DoMozStackWalkBacktrace(aLock, aRegisteredThread, aRegs, aNativeStack);
1430 # else
1431 # error "Invalid configuration"
1432 # endif
1433 }
1434 #endif
1435
1436 // Writes some components shared by periodic and synchronous profiles to
1437 // ActivePS's ProfileBuffer. (This should only be called from DoSyncSample()
1438 // and DoPeriodicSample().)
1439 //
1440 // The grammar for entry sequences is in a comment above
1441 // ProfileBuffer::StreamSamplesToJSON.
1442 static inline void DoSharedSample(
1443 PSLockRef aLock, bool aIsSynchronous, RegisteredThread& aRegisteredThread,
1444 const Registers& aRegs, uint64_t aSamplePos, uint64_t aBufferRangeStart,
1445 ProfileBuffer& aBuffer,
1446 StackCaptureOptions aCaptureOptions = StackCaptureOptions::Full) {
1447 // WARNING: this function runs within the profiler's "critical section".
1448
1449 MOZ_ASSERT(!aBuffer.IsThreadSafe(),
1450 "Mutexes cannot be used inside this critical section");
1451
1452 MOZ_RELEASE_ASSERT(ActivePS::Exists(aLock));
1453
1454 ProfileBufferCollector collector(aBuffer, aSamplePos, aBufferRangeStart);
1455 NativeStack nativeStack;
1456 #if defined(HAVE_NATIVE_UNWIND)
1457 if (ActivePS::FeatureStackWalk(aLock) &&
1458 aCaptureOptions == StackCaptureOptions::Full) {
1459 DoNativeBacktrace(aLock, aRegisteredThread, aRegs, nativeStack);
1460
1461 MergeStacks(aIsSynchronous, aRegisteredThread, nativeStack, collector);
1462 } else
1463 #endif
1464 {
1465 MergeStacks(aIsSynchronous, aRegisteredThread, nativeStack, collector);
1466
1467 // We can't walk the whole native stack, but we can record the top frame.
1468 if (aCaptureOptions == StackCaptureOptions::Full) {
1469 aBuffer.AddEntry(ProfileBufferEntry::NativeLeafAddr((void*)aRegs.mPC));
1470 }
1471 }
1472 }
1473
1474 // Writes the components of a synchronous sample to the given ProfileBuffer.
1475 static void DoSyncSample(PSLockRef aLock, RegisteredThread& aRegisteredThread,
1476 const TimeStamp& aNow, const Registers& aRegs,
1477 ProfileBuffer& aBuffer,
1478 StackCaptureOptions aCaptureOptions) {
1479 // WARNING: this function runs within the profiler's "critical section".
1480
1481 MOZ_ASSERT(aCaptureOptions != StackCaptureOptions::NoStack,
1482 "DoSyncSample should not be called when no capture is needed");
1483
1484 const uint64_t bufferRangeStart = aBuffer.BufferRangeStart();
1485
1486 const uint64_t samplePos =
1487 aBuffer.AddThreadIdEntry(aRegisteredThread.Info()->ThreadId());
1488
1489 TimeDuration delta = aNow - CorePS::ProcessStartTime();
1490 aBuffer.AddEntry(ProfileBufferEntry::Time(delta.ToMilliseconds()));
1491
1492 DoSharedSample(aLock, /* aIsSynchronous = */ true, aRegisteredThread, aRegs,
1493 samplePos, bufferRangeStart, aBuffer, aCaptureOptions);
1494 }
1495
1496 // Writes the components of a periodic sample to ActivePS's ProfileBuffer.
1497 // The ThreadId entry is already written in the main ProfileBuffer, its location
1498 // is `aSamplePos`, we can write the rest to `aBuffer` (which may be different).
1499 static void DoPeriodicSample(PSLockRef aLock,
1500 RegisteredThread& aRegisteredThread,
1501 ProfiledThreadData& aProfiledThreadData,
1502 const Registers& aRegs, uint64_t aSamplePos,
1503 uint64_t aBufferRangeStart,
1504 ProfileBuffer& aBuffer) {
1505 // WARNING: this function runs within the profiler's "critical section".
1506
1507 DoSharedSample(aLock, /* aIsSynchronous = */ false, aRegisteredThread, aRegs,
1508 aSamplePos, aBufferRangeStart, aBuffer);
1509 }
1510
1511 #undef UNWINDING_REGS_HAVE_ECX_EDX
1512 #undef UNWINDING_REGS_HAVE_R10_R12
1513 #undef UNWINDING_REGS_HAVE_LR_R7
1514 #undef UNWINDING_REGS_HAVE_LR_R11
1515
1516 // END sampling/unwinding code
1517 ////////////////////////////////////////////////////////////////////////
1518
1519 ////////////////////////////////////////////////////////////////////////
1520 // BEGIN saving/streaming code
1521
1522 const static uint64_t kJS_MAX_SAFE_UINTEGER = +9007199254740991ULL;
1523
1524 static int64_t SafeJSInteger(uint64_t aValue) {
1525 return aValue <= kJS_MAX_SAFE_UINTEGER ? int64_t(aValue) : -1;
1526 }
1527
1528 static void AddSharedLibraryInfoToStream(JSONWriter& aWriter,
1529 const SharedLibrary& aLib) {
1530 aWriter.StartObjectElement();
1531 aWriter.IntProperty("start", SafeJSInteger(aLib.GetStart()));
1532 aWriter.IntProperty("end", SafeJSInteger(aLib.GetEnd()));
1533 aWriter.IntProperty("offset", SafeJSInteger(aLib.GetOffset()));
1534 aWriter.StringProperty("name", aLib.GetModuleName());
1535 aWriter.StringProperty("path", aLib.GetModulePath());
1536 aWriter.StringProperty("debugName", aLib.GetDebugName());
1537 aWriter.StringProperty("debugPath", aLib.GetDebugPath());
1538 aWriter.StringProperty("breakpadId", aLib.GetBreakpadId());
1539 aWriter.StringProperty("codeId", aLib.GetCodeId());
1540 aWriter.StringProperty("arch", aLib.GetArch());
1541 aWriter.EndObject();
1542 }
1543
1544 void AppendSharedLibraries(JSONWriter& aWriter) {
1545 SharedLibraryInfo info = SharedLibraryInfo::GetInfoForSelf();
1546 info.SortByAddress();
1547 for (size_t i = 0; i < info.GetSize(); i++) {
1548 AddSharedLibraryInfoToStream(aWriter, info.GetEntry(i));
1549 }
1550 }
1551
1552 static void StreamCategories(SpliceableJSONWriter& aWriter) {
1553 // Same order as ProfilingCategory. Format:
1554 // [
1555 // {
1556 // name: "Idle",
1557 // color: "transparent",
1558 // subcategories: ["Other"],
1559 // },
1560 // {
1561 // name: "Other",
1562 // color: "grey",
1563 // subcategories: [
1564 // "JSM loading",
1565 // "Subprocess launching",
1566 // "DLL loading"
1567 // ]
1568 // },
1569 // ...
1570 // ]
1571 for (const auto& categoryInfo : GetProfilingCategoryList()) {
1572 aWriter.Start();
1573 aWriter.StringProperty("name", MakeStringSpan(categoryInfo.mName));
1574 aWriter.StringProperty("color", MakeStringSpan(categoryInfo.mColor));
1575 aWriter.StartArrayProperty("subcategories");
1576 for (const auto& subcategoryName : categoryInfo.mSubcategoryNames) {
1577 aWriter.StringElement(MakeStringSpan(subcategoryName));
1578 }
1579 aWriter.EndArray();
1580 aWriter.EndObject();
1581 }
1582 }
1583
1584 static void StreamMarkerSchema(SpliceableJSONWriter& aWriter) {
1585 // Get an array view with all registered marker-type-specific functions.
1586 base_profiler_markers_detail::Streaming::LockedMarkerTypeFunctionsList
1587 markerTypeFunctionsArray;
1588 // List of streamed marker names, this is used to spot duplicates.
1589 std::set<std::string> names;
1590 // Stream the display schema for each different one. (Duplications may come
1591 // from the same code potentially living in different libraries.)
1592 for (const auto& markerTypeFunctions : markerTypeFunctionsArray) {
1593 auto name = markerTypeFunctions.mMarkerTypeNameFunction();
1594 // std::set.insert(T&&) returns a pair, its `second` is true if the element
1595 // was actually inserted (i.e., it was not there yet.)
1596 const bool didInsert =
1597 names.insert(std::string(name.data(), name.size())).second;
1598 if (didInsert) {
1599 markerTypeFunctions.mMarkerSchemaFunction().Stream(aWriter, name);
1600 }
1601 }
1602 }
1603
1604 static int64_t MicrosecondsSince1970();
1605
1606 static void MaybeWriteRawStartTimeValue(SpliceableJSONWriter& aWriter,
1607 const TimeStamp& aStartTime) {
1608 #ifdef XP_LINUX
1609 aWriter.DoubleProperty(
1610 "startTimeAsClockMonotonicNanosecondsSinceBoot",
1611 static_cast<double>(aStartTime.RawClockMonotonicNanosecondsSinceBoot()));
1612 #endif
1613
1614 #ifdef XP_DARWIN
1615 aWriter.DoubleProperty(
1616 "startTimeAsMachAbsoluteTimeNanoseconds",
1617 static_cast<double>(aStartTime.RawMachAbsoluteTimeNanoseconds()));
1618 #endif
1619
1620 #ifdef XP_WIN
1621 Maybe<uint64_t> startTimeQPC = aStartTime.RawQueryPerformanceCounterValue();
1622 if (startTimeQPC)
1623 aWriter.DoubleProperty("startTimeAsQueryPerformanceCounterValue",
1624 static_cast<double>(*startTimeQPC));
1625 #endif
1626 }
1627
1628 static void StreamMetaJSCustomObject(PSLockRef aLock,
1629 SpliceableJSONWriter& aWriter,
1630 bool aIsShuttingDown) {
1631 MOZ_RELEASE_ASSERT(CorePS::Exists() && ActivePS::Exists(aLock));
1632
1633 aWriter.IntProperty("version", GECKO_PROFILER_FORMAT_VERSION);
1634
1635 // The "startTime" field holds the number of milliseconds since midnight
1636 // January 1, 1970 GMT (the "Unix epoch"). This grotty code computes (Now -
1637 // (Now - ProcessStartTime)) to convert CorePS::ProcessStartTime() into that
1638 // form. Note: This start time, and the platform-specific "raw start time",
1639 // are the only absolute time values in the profile! All other timestamps are
1640 // relative to this startTime.
1641 TimeStamp startTime = CorePS::ProcessStartTime();
1642 TimeStamp now = TimeStamp::Now();
1643 double millisecondsSinceUnixEpoch =
1644 static_cast<double>(MicrosecondsSince1970()) / 1000.0;
1645 double millisecondsSinceStartTime = (now - startTime).ToMilliseconds();
1646 double millisecondsBetweenUnixEpochAndStartTime =
1647 millisecondsSinceUnixEpoch - millisecondsSinceStartTime;
1648 aWriter.DoubleProperty("startTime", millisecondsBetweenUnixEpochAndStartTime);
1649
1650 MaybeWriteRawStartTimeValue(aWriter, startTime);
1651
1652 aWriter.DoubleProperty("profilingStartTime", (ActivePS::ProfilingStartTime() -
1653 CorePS::ProcessStartTime())
1654 .ToMilliseconds());
1655
1656 if (const TimeStamp contentEarliestTime =
1657 ActivePS::Buffer(aLock)
1658 .UnderlyingChunkedBuffer()
1659 .GetEarliestChunkStartTimeStamp();
1660 !contentEarliestTime.IsNull()) {
1661 aWriter.DoubleProperty(
1662 "contentEarliestTime",
1663 (contentEarliestTime - CorePS::ProcessStartTime()).ToMilliseconds());
1664 } else {
1665 aWriter.NullProperty("contentEarliestTime");
1666 }
1667
1668 const double profilingEndTime = profiler_time();
1669 aWriter.DoubleProperty("profilingEndTime", profilingEndTime);
1670
1671 if (aIsShuttingDown) {
1672 aWriter.DoubleProperty("shutdownTime", profilingEndTime);
1673 } else {
1674 aWriter.NullProperty("shutdownTime");
1675 }
1676
1677 aWriter.StartArrayProperty("categories");
1678 StreamCategories(aWriter);
1679 aWriter.EndArray();
1680
1681 aWriter.StartArrayProperty("markerSchema");
1682 StreamMarkerSchema(aWriter);
1683 aWriter.EndArray();
1684
1685 if (!profiler_is_main_thread()) {
1686 // Leave the rest of the properties out if we're not on the main thread.
1687 // At the moment, the only case in which this function is called on a
1688 // background thread is if we're in a content process and are going to
1689 // send this profile to the parent process. In that case, the parent
1690 // process profile's "meta" object already has the rest of the properties,
1691 // and the parent process profile is dumped on that process's main thread.
1692 return;
1693 }
1694
1695 aWriter.DoubleProperty("interval", ActivePS::Interval(aLock));
1696 aWriter.IntProperty("stackwalk", ActivePS::FeatureStackWalk(aLock));
1697
1698 #ifdef DEBUG
1699 aWriter.IntProperty("debug", 1);
1700 #else
1701 aWriter.IntProperty("debug", 0);
1702 #endif
1703
1704 aWriter.IntProperty("gcpoison", 0);
1705
1706 aWriter.IntProperty("asyncstack", 0);
1707
1708 aWriter.IntProperty("processType", 0);
1709 }
1710
1711 static void StreamPages(PSLockRef aLock, SpliceableJSONWriter& aWriter) {
1712 MOZ_RELEASE_ASSERT(CorePS::Exists());
1713 ActivePS::DiscardExpiredPages(aLock);
1714 for (const auto& page : ActivePS::ProfiledPages(aLock)) {
1715 page->StreamJSON(aWriter);
1716 }
1717 }
1718
1719 static void locked_profiler_stream_json_for_this_process(
1720 PSLockRef aLock, SpliceableJSONWriter& aWriter, double aSinceTime,
1721 bool aIsShuttingDown, bool aOnlyThreads = false) {
1722 LOG("locked_profiler_stream_json_for_this_process");
1723
1724 MOZ_RELEASE_ASSERT(CorePS::Exists() && ActivePS::Exists(aLock));
1725
1726 AUTO_PROFILER_STATS(base_locked_profiler_stream_json_for_this_process);
1727
1728 const double collectionStartMs = profiler_time();
1729
1730 ProfileBuffer& buffer = ActivePS::Buffer(aLock);
1731
1732 // If there is a set "Window length", discard older data.
1733 Maybe<double> durationS = ActivePS::Duration(aLock);
1734 if (durationS.isSome()) {
1735 const double durationStartMs = collectionStartMs - *durationS * 1000;
1736 buffer.DiscardSamplesBeforeTime(durationStartMs);
1737 }
1738
1739 if (!aOnlyThreads) {
1740 // Put shared library info
1741 aWriter.StartArrayProperty("libs");
1742 AppendSharedLibraries(aWriter);
1743 aWriter.EndArray();
1744
1745 // Put meta data
1746 aWriter.StartObjectProperty("meta");
1747 {
1748 StreamMetaJSCustomObject(aLock, aWriter, aIsShuttingDown);
1749 }
1750 aWriter.EndObject();
1751
1752 // Put page data
1753 aWriter.StartArrayProperty("pages");
1754 {
1755 StreamPages(aLock, aWriter);
1756 }
1757 aWriter.EndArray();
1758
1759 buffer.StreamProfilerOverheadToJSON(aWriter, CorePS::ProcessStartTime(),
1760 aSinceTime);
1761 buffer.StreamCountersToJSON(aWriter, CorePS::ProcessStartTime(),
1762 aSinceTime);
1763
1764 // Lists the samples for each thread profile
1765 aWriter.StartArrayProperty("threads");
1766 }
1767
1768 // if aOnlyThreads is true, the only output will be the threads array items.
1769 {
1770 ActivePS::DiscardExpiredDeadProfiledThreads(aLock);
1771 Vector<std::pair<RegisteredThread*, ProfiledThreadData*>> threads =
1772 ActivePS::ProfiledThreads(aLock);
1773 for (auto& thread : threads) {
1774 ProfiledThreadData* profiledThreadData = thread.second;
1775 profiledThreadData->StreamJSON(
1776 buffer, aWriter, CorePS::ProcessName(aLock), CorePS::ETLDplus1(aLock),
1777 CorePS::ProcessStartTime(), aSinceTime);
1778 }
1779 }
1780
1781 if (!aOnlyThreads) {
1782 aWriter.EndArray();
1783
1784 aWriter.StartArrayProperty("pausedRanges");
1785 {
1786 buffer.StreamPausedRangesToJSON(aWriter, aSinceTime);
1787 }
1788 aWriter.EndArray();
1789 }
1790
1791 const double collectionEndMs = profiler_time();
1792
1793 // Record timestamps for the collection into the buffer, so that consumers
1794 // know why we didn't collect any samples for its duration.
1795 // We put these entries into the buffer after we've collected the profile,
1796 // so they'll be visible for the *next* profile collection (if they haven't
1797 // been overwritten due to buffer wraparound by then).
1798 buffer.AddEntry(ProfileBufferEntry::CollectionStart(collectionStartMs));
1799 buffer.AddEntry(ProfileBufferEntry::CollectionEnd(collectionEndMs));
1800 }
1801
1802 bool profiler_stream_json_for_this_process(SpliceableJSONWriter& aWriter,
1803 double aSinceTime,
1804 bool aIsShuttingDown,
1805 bool aOnlyThreads) {
1806 LOG("profiler_stream_json_for_this_process");
1807
1808 MOZ_RELEASE_ASSERT(CorePS::Exists());
1809
1810 PSAutoLock lock;
1811
1812 if (!ActivePS::Exists(lock)) {
1813 return false;
1814 }
1815
1816 locked_profiler_stream_json_for_this_process(lock, aWriter, aSinceTime,
1817 aIsShuttingDown, aOnlyThreads);
1818 return true;
1819 }
1820
1821 // END saving/streaming code
1822 ////////////////////////////////////////////////////////////////////////
1823
1824 static char FeatureCategory(uint32_t aFeature) {
1825 if (aFeature & DefaultFeatures()) {
1826 if (aFeature & AvailableFeatures()) {
1827 return 'D';
1828 }
1829 return 'd';
1830 }
1831
1832 if (aFeature & StartupExtraDefaultFeatures()) {
1833 if (aFeature & AvailableFeatures()) {
1834 return 'S';
1835 }
1836 return 's';
1837 }
1838
1839 if (aFeature & AvailableFeatures()) {
1840 return '-';
1841 }
1842 return 'x';
1843 }
1844
1845 static void PrintUsage() {
1846 PrintToConsole(
1847 "\n"
1848 "Profiler environment variable usage:\n"
1849 "\n"
1850 " MOZ_BASE_PROFILER_HELP\n"
1851 " If set to any value, prints this message.\n"
1852 " (Only BaseProfiler features are known here; Use MOZ_PROFILER_HELP\n"
1853 " for Gecko Profiler help, with more features).\n"
1854 "\n"
1855 " MOZ_BASE_PROFILER_{,DEBUG_,VERBOSE}LOGGING\n"
1856 " Enables BaseProfiler logging to stdout. The levels of logging\n"
1857 " available are MOZ_BASE_PROFILER_LOGGING' (least verbose),\n"
1858 " '..._DEBUG_LOGGING', '..._VERBOSE_LOGGING' (most verbose)\n"
1859 "\n"
1860 " MOZ_PROFILER_STARTUP\n"
1861 " If set to any value other than '' or '0'/'N'/'n', starts the\n"
1862 " profiler immediately on start-up.\n"
1863 " Useful if you want profile code that runs very early.\n"
1864 "\n"
1865 " MOZ_PROFILER_STARTUP_ENTRIES=<%u..%u>\n"
1866 " If MOZ_PROFILER_STARTUP is set, specifies the number of entries\n"
1867 " per process in the profiler's circular buffer when the profiler is\n"
1868 " first started.\n"
1869 " If unset, the platform default is used:\n"
1870 " %u entries per process, or %u when MOZ_PROFILER_STARTUP is set.\n"
1871 " (%u bytes per entry -> %u or %u total bytes per process)\n"
1872 " Optional units in bytes: KB, KiB, MB, MiB, GB, GiB\n"
1873 "\n"
1874 " MOZ_PROFILER_STARTUP_DURATION=<1..>\n"
1875 " If MOZ_PROFILER_STARTUP is set, specifies the maximum life time\n"
1876 " of entries in the the profiler's circular buffer when the profiler\n"
1877 " is first started, in seconds.\n"
1878 " If unset, the life time of the entries will only be restricted by\n"
1879 " MOZ_PROFILER_STARTUP_ENTRIES (or its default value), and no\n"
1880 " additional time duration restriction will be applied.\n"
1881 "\n"
1882 " MOZ_PROFILER_STARTUP_INTERVAL=<1..1000>\n"
1883 " If MOZ_PROFILER_STARTUP is set, specifies the sample interval,\n"
1884 " measured in milliseconds, when the profiler is first started.\n"
1885 " If unset, the platform default is used.\n"
1886 "\n"
1887 " MOZ_PROFILER_STARTUP_FEATURES_BITFIELD=<Number>\n"
1888 " If MOZ_PROFILER_STARTUP is set, specifies the profiling\n"
1889 " features, as the integer value of the features bitfield.\n"
1890 " If unset, the value from MOZ_PROFILER_STARTUP_FEATURES is used.\n"
1891 "\n"
1892 " MOZ_PROFILER_STARTUP_FEATURES=<Features>\n"
1893 " If MOZ_PROFILER_STARTUP is set, specifies the profiling\n"
1894 " features, as a comma-separated list of strings.\n"
1895 " Ignored if MOZ_PROFILER_STARTUP_FEATURES_BITFIELD is set.\n"
1896 " If unset, the platform default is used.\n"
1897 "\n"
1898 " Features: (x=unavailable, D/d=default/unavailable,\n"
1899 " S/s=MOZ_PROFILER_STARTUP extra "
1900 "default/unavailable)\n",
1901 unsigned(scMinimumBufferEntries), unsigned(scMaximumBufferEntries),
1902 unsigned(BASE_PROFILER_DEFAULT_ENTRIES.Value()),
1903 unsigned(BASE_PROFILER_DEFAULT_STARTUP_ENTRIES.Value()),
1904 unsigned(scBytesPerEntry),
1905 unsigned(BASE_PROFILER_DEFAULT_ENTRIES.Value() * scBytesPerEntry),
1906 unsigned(BASE_PROFILER_DEFAULT_STARTUP_ENTRIES.Value() *
1907 scBytesPerEntry));
1908
1909 #define PRINT_FEATURE(n_, str_, Name_, desc_) \
1910 PrintToConsole(" %c %7u: \"%s\" (%s)\n", \
1911 FeatureCategory(ProfilerFeature::Name_), \
1912 ProfilerFeature::Name_, str_, desc_);
1913
1914 BASE_PROFILER_FOR_EACH_FEATURE(PRINT_FEATURE)
1915
1916 #undef PRINT_FEATURE
1917
1918 PrintToConsole(
1919 " - \"default\" (All above D+S defaults)\n"
1920 "\n"
1921 " MOZ_PROFILER_STARTUP_FILTERS=<Filters>\n"
1922 " If MOZ_PROFILER_STARTUP is set, specifies the thread filters, as "
1923 "a\n"
1924 " comma-separated list of strings. A given thread will be sampled if\n"
1925 " any of the filters is a case-insensitive substring of the thread\n"
1926 " name. If unset, a default is used.\n"
1927 "\n"
1928 " MOZ_PROFILER_SHUTDOWN\n"
1929 " If set, the profiler saves a profile to the named file on shutdown.\n"
1930 "\n"
1931 " MOZ_PROFILER_SYMBOLICATE\n"
1932 " If set, the profiler will pre-symbolicate profiles.\n"
1933 " *Note* This will add a significant pause when gathering data, and\n"
1934 " is intended mainly for local development.\n"
1935 "\n"
1936 " MOZ_PROFILER_LUL_TEST\n"
1937 " If set to any value, runs LUL unit tests at startup.\n"
1938 "\n"
1939 " This platform %s native unwinding.\n"
1940 "\n",
1941 #if defined(HAVE_NATIVE_UNWIND)
1942 "supports"
1943 #else
1944 "does not support"
1945 #endif
1946 );
1947 }
1948
1949 ////////////////////////////////////////////////////////////////////////
1950 // BEGIN Sampler
1951
1952 #if defined(GP_OS_linux) || defined(GP_OS_android)
1953 struct SigHandlerCoordinator;
1954 #endif
1955
1956 // Sampler performs setup and teardown of the state required to sample with the
1957 // profiler. Sampler may exist when ActivePS is not present.
1958 //
1959 // SuspendAndSampleAndResumeThread must only be called from a single thread,
1960 // and must not sample the thread it is being called from. A separate Sampler
1961 // instance must be used for each thread which wants to capture samples.
1962
1963 // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
1964 //
1965 // With the exception of SamplerThread, all Sampler objects must be Disable-d
1966 // before releasing the lock which was used to create them. This avoids races
1967 // on linux with the SIGPROF signal handler.
1968
1969 class Sampler {
1970 public:
1971 // Sets up the profiler such that it can begin sampling.
1972 explicit Sampler(PSLockRef aLock);
1973
1974 // Disable the sampler, restoring it to its previous state. This must be
1975 // called once, and only once, before the Sampler is destroyed.
1976 void Disable(PSLockRef aLock);
1977
1978 // This method suspends and resumes the samplee thread. It calls the passed-in
1979 // function-like object aProcessRegs (passing it a populated |const
1980 // Registers&| arg) while the samplee thread is suspended.
1981 //
1982 // Func must be a function-like object of type `void()`.
1983 template <typename Func>
1984 void SuspendAndSampleAndResumeThread(
1985 PSLockRef aLock, const RegisteredThread& aRegisteredThread,
1986 const TimeStamp& aNow, const Func& aProcessRegs);
1987
1988 private:
1989 #if defined(GP_OS_linux) || defined(GP_OS_android) || defined(GP_OS_freebsd)
1990 // Used to restore the SIGPROF handler when ours is removed.
1991 struct sigaction mOldSigprofHandler;
1992
1993 // This process' ID. Needed as an argument for tgkill in
1994 // SuspendAndSampleAndResumeThread.
1995 BaseProfilerProcessId mMyPid;
1996
1997 // The sampler thread's ID. Used to assert that it is not sampling itself,
1998 // which would lead to deadlock.
1999 BaseProfilerThreadId mSamplerTid;
2000
2001 public:
2002 // This is the one-and-only variable used to communicate between the sampler
2003 // thread and the samplee thread's signal handler. It's static because the
2004 // samplee thread's signal handler is static.
2005 static struct SigHandlerCoordinator* sSigHandlerCoordinator;
2006 #endif
2007 };
2008
2009 // END Sampler
2010 ////////////////////////////////////////////////////////////////////////
2011
2012 ////////////////////////////////////////////////////////////////////////
2013 // BEGIN SamplerThread
2014
2015 // The sampler thread controls sampling and runs whenever the profiler is
2016 // active. It periodically runs through all registered threads, finds those
2017 // that should be sampled, then pauses and samples them.
2018
2019 class SamplerThread {
2020 public:
2021 // Creates a sampler thread, but doesn't start it.
2022 SamplerThread(PSLockRef aLock, uint32_t aActivityGeneration,
2023 double aIntervalMilliseconds, uint32_t aFeatures);
2024 ~SamplerThread();
2025
2026 // This runs on (is!) the sampler thread.
2027 void Run();
2028
2029 // This runs on the main thread.
2030 void Stop(PSLockRef aLock);
2031
2032 private:
2033 // This suspends the calling thread for the given number of microseconds.
2034 // Best effort timing.
2035 void SleepMicro(uint32_t aMicroseconds);
2036
2037 // The sampler used to suspend and sample threads.
2038 Sampler mSampler;
2039
2040 // The activity generation, for detecting when the sampler thread must stop.
2041 const uint32_t mActivityGeneration;
2042
2043 // The interval between samples, measured in microseconds.
2044 const int mIntervalMicroseconds;
2045
2046 // The OS-specific handle for the sampler thread.
2047 #if defined(GP_OS_windows)
2048 HANDLE mThread;
2049 #elif defined(GP_OS_darwin) || defined(GP_OS_linux) || \
2050 defined(GP_OS_android) || defined(GP_OS_freebsd)
2051 pthread_t mThread;
2052 #endif
2053
2054 #if defined(GP_OS_windows)
2055 bool mNoTimerResolutionChange = true;
2056 #endif
2057
2058 SamplerThread(const SamplerThread&) = delete;
2059 void operator=(const SamplerThread&) = delete;
2060 };
2061
2062 // This function is required because we need to create a SamplerThread within
2063 // ActivePS's constructor, but SamplerThread is defined after ActivePS. It
2064 // could probably be removed by moving some code around.
2065 static SamplerThread* NewSamplerThread(PSLockRef aLock, uint32_t aGeneration,
2066 double aInterval, uint32_t aFeatures) {
2067 return new SamplerThread(aLock, aGeneration, aInterval, aFeatures);
2068 }
2069
2070 // This function is the sampler thread. This implementation is used for all
2071 // targets.
2072 void SamplerThread::Run() {
2073 // TODO: If possible, name this thread later on, after NSPR becomes available.
2074 // PR_SetCurrentThreadName("SamplerThread");
2075
2076 // Features won't change during this SamplerThread's lifetime, so we can read
2077 // them once and store them locally.
2078 const uint32_t features = []() -> uint32_t {
2079 PSAutoLock lock;
2080 if (!ActivePS::Exists(lock)) {
2081 // If there is no active profiler, it doesn't matter what we return,
2082 // because this thread will exit before any feature is used.
2083 return 0;
2084 }
2085 return ActivePS::Features(lock);
2086 }();
2087
2088 // Not *no*-stack-sampling means we do want stack sampling.
2089 const bool stackSampling = !ProfilerFeature::HasNoStackSampling(features);
2090
2091 // Use local ProfileBuffer to capture the stack.
2092 // (This is to avoid touching the CorePS::CoreBuffer lock while
2093 // a thread is suspended, because that thread could be working with
2094 // the CorePS::CoreBuffer as well.)
2095 ProfileBufferChunkManagerSingle localChunkManager(
2096 ProfileBufferChunkManager::scExpectedMaximumStackSize);
2097 ProfileChunkedBuffer localBuffer(
2098 ProfileChunkedBuffer::ThreadSafety::WithoutMutex, localChunkManager);
2099 ProfileBuffer localProfileBuffer(localBuffer);
2100
2101 // Will be kept between collections, to know what each collection does.
2102 auto previousState = localBuffer.GetState();
2103
2104 // This will be positive if we are running behind schedule (sampling less
2105 // frequently than desired) and negative if we are ahead of schedule.
2106 TimeDuration lastSleepOvershoot = 0;
2107 TimeStamp sampleStart = TimeStamp::Now();
2108
2109 while (true) {
2110 // This scope is for |lock|. It ends before we sleep below.
2111 {
2112 PSAutoLock lock;
2113 TimeStamp lockAcquired = TimeStamp::Now();
2114
2115 if (!ActivePS::Exists(lock)) {
2116 return;
2117 }
2118
2119 // At this point profiler_stop() might have been called, and
2120 // profiler_start() might have been called on another thread. If this
2121 // happens the generation won't match.
2122 if (ActivePS::Generation(lock) != mActivityGeneration) {
2123 return;
2124 }
2125
2126 ActivePS::ClearExpiredExitProfiles(lock);
2127
2128 TimeStamp expiredMarkersCleaned = TimeStamp::Now();
2129
2130 if (int(gSkipSampling) <= 0 && !ActivePS::IsSamplingPaused(lock)) {
2131 TimeDuration delta = sampleStart - CorePS::ProcessStartTime();
2132 ProfileBuffer& buffer = ActivePS::Buffer(lock);
2133
2134 // handle per-process generic counters
2135 const Vector<BaseProfilerCount*>& counters = CorePS::Counters(lock);
2136 for (auto& counter : counters) {
2137 // create Buffer entries for each counter
2138 buffer.AddEntry(ProfileBufferEntry::CounterId(counter));
2139 buffer.AddEntry(ProfileBufferEntry::Time(delta.ToMilliseconds()));
2140 int64_t count;
2141 uint64_t number;
2142 counter->Sample(count, number);
2143 buffer.AddEntry(ProfileBufferEntry::Count(count));
2144 if (number) {
2145 buffer.AddEntry(ProfileBufferEntry::Number(number));
2146 }
2147 }
2148 TimeStamp countersSampled = TimeStamp::Now();
2149
2150 if (stackSampling) {
2151 const Vector<LiveProfiledThreadData>& liveThreads =
2152 ActivePS::LiveProfiledThreads(lock);
2153
2154 for (auto& thread : liveThreads) {
2155 RegisteredThread* registeredThread = thread.mRegisteredThread;
2156 ProfiledThreadData* profiledThreadData =
2157 thread.mProfiledThreadData.get();
2158 RefPtr<ThreadInfo> info = registeredThread->Info();
2159
2160 // If the thread is asleep and has been sampled before in the same
2161 // sleep episode, find and copy the previous sample, as that's
2162 // cheaper than taking a new sample.
2163 if (registeredThread->RacyRegisteredThread()
2164 .CanDuplicateLastSampleDueToSleep()) {
2165 bool dup_ok = ActivePS::Buffer(lock).DuplicateLastSample(
2166 info->ThreadId(), CorePS::ProcessStartTime(),
2167 profiledThreadData->LastSample());
2168 if (dup_ok) {
2169 continue;
2170 }
2171 }
2172
2173 AUTO_PROFILER_STATS(base_SamplerThread_Run_DoPeriodicSample);
2174
2175 TimeStamp now = TimeStamp::Now();
2176
2177 // Record the global profiler buffer's range start now, before
2178 // adding the first entry for this thread's sample.
2179 const uint64_t bufferRangeStart = buffer.BufferRangeStart();
2180
2181 // Add the thread ID now, so we know its position in the main
2182 // buffer, which is used by some JS data. (DoPeriodicSample only
2183 // knows about the temporary local buffer.)
2184 const uint64_t samplePos =
2185 buffer.AddThreadIdEntry(registeredThread->Info()->ThreadId());
2186 profiledThreadData->LastSample() = Some(samplePos);
2187
2188 // Also add the time, so it's always there after the thread ID, as
2189 // expected by the parser. (Other stack data is optional.)
2190 TimeDuration delta = now - CorePS::ProcessStartTime();
2191 buffer.AddEntry(ProfileBufferEntry::Time(delta.ToMilliseconds()));
2192
2193 mSampler.SuspendAndSampleAndResumeThread(
2194 lock, *registeredThread, now,
2195 [&](const Registers& aRegs, const TimeStamp& aNow) {
2196 DoPeriodicSample(lock, *registeredThread, *profiledThreadData,
2197 aRegs, samplePos, bufferRangeStart,
2198 localProfileBuffer);
2199 });
2200
2201 // If data is complete, copy it into the global buffer.
2202 auto state = localBuffer.GetState();
2203 if (state.mClearedBlockCount != previousState.mClearedBlockCount) {
2204 LOG("Stack sample too big for local storage, needed %u bytes",
2205 unsigned(state.mRangeEnd - previousState.mRangeEnd));
2206 } else if (state.mRangeEnd - previousState.mRangeEnd >=
2207 *profiler_get_core_buffer().BufferLength()) {
2208 LOG("Stack sample too big for profiler storage, needed %u bytes",
2209 unsigned(state.mRangeEnd - previousState.mRangeEnd));
2210 } else {
2211 profiler_get_core_buffer().AppendContents(localBuffer);
2212 }
2213
2214 // Clean up for the next run.
2215 localBuffer.Clear();
2216 previousState = localBuffer.GetState();
2217 }
2218 }
2219
2220 #if defined(USE_LUL_STACKWALK)
2221 // The LUL unwind object accumulates frame statistics. Periodically we
2222 // should poke it to give it a chance to print those statistics. This
2223 // involves doing I/O (fprintf, __android_log_print, etc.) and so
2224 // can't safely be done from the critical section inside
2225 // SuspendAndSampleAndResumeThread, which is why it is done here.
2226 lul::LUL* lul = CorePS::Lul(lock);
2227 if (lul) {
2228 lul->MaybeShowStats();
2229 }
2230 #endif
2231 TimeStamp threadsSampled = TimeStamp::Now();
2232
2233 {
2234 AUTO_PROFILER_STATS(Sampler_FulfillChunkRequests);
2235 ActivePS::FulfillChunkRequests(lock);
2236 }
2237
2238 buffer.CollectOverheadStats(delta, lockAcquired - sampleStart,
2239 expiredMarkersCleaned - lockAcquired,
2240 countersSampled - expiredMarkersCleaned,
2241 threadsSampled - countersSampled);
2242 }
2243 }
2244 // gPSMutex is not held after this point.
2245
2246 // Calculate how long a sleep to request. After the sleep, measure how
2247 // long we actually slept and take the difference into account when
2248 // calculating the sleep interval for the next iteration. This is an
2249 // attempt to keep "to schedule" in the presence of inaccuracy of the
2250 // actual sleep intervals.
2251 TimeStamp targetSleepEndTime =
2252 sampleStart + TimeDuration::FromMicroseconds(mIntervalMicroseconds);
2253 TimeStamp beforeSleep = TimeStamp::Now();
2254 TimeDuration targetSleepDuration = targetSleepEndTime - beforeSleep;
2255 double sleepTime = std::max(
2256 0.0, (targetSleepDuration - lastSleepOvershoot).ToMicroseconds());
2257 SleepMicro(static_cast<uint32_t>(sleepTime));
2258 sampleStart = TimeStamp::Now();
2259 lastSleepOvershoot =
2260 sampleStart - (beforeSleep + TimeDuration::FromMicroseconds(sleepTime));
2261 }
2262 }
2263
2264 // Temporary closing namespaces from enclosing platform.cpp.
2265 } // namespace baseprofiler
2266 } // namespace mozilla
2267
2268 // We #include these files directly because it means those files can use
2269 // declarations from this file trivially. These provide target-specific
2270 // implementations of all SamplerThread methods except Run().
2271 #if defined(GP_OS_windows)
2272 # include "platform-win32.cpp"
2273 #elif defined(GP_OS_darwin)
2274 # include "platform-macos.cpp"
2275 #elif defined(GP_OS_linux) || defined(GP_OS_android) || defined(GP_OS_freebsd)
2276 # include "platform-linux-android.cpp"
2277 #else
2278 # error "bad platform"
2279 #endif
2280
2281 namespace mozilla {
2282 namespace baseprofiler {
2283
2284 UniquePlatformData AllocPlatformData(BaseProfilerThreadId aThreadId) {
2285 return UniquePlatformData(new PlatformData(aThreadId));
2286 }
2287
2288 void PlatformDataDestructor::operator()(PlatformData* aData) { delete aData; }
2289
2290 // END SamplerThread
2291 ////////////////////////////////////////////////////////////////////////
2292
2293 ////////////////////////////////////////////////////////////////////////
2294 // BEGIN externally visible functions
2295
2296 static uint32_t ParseFeature(const char* aFeature, bool aIsStartup) {
2297 if (strcmp(aFeature, "default") == 0) {
2298 return (aIsStartup ? (DefaultFeatures() | StartupExtraDefaultFeatures())
2299 : DefaultFeatures()) &
2300 AvailableFeatures();
2301 }
2302
2303 #define PARSE_FEATURE_BIT(n_, str_, Name_, desc_) \
2304 if (strcmp(aFeature, str_) == 0) { \
2305 return ProfilerFeature::Name_; \
2306 }
2307
2308 BASE_PROFILER_FOR_EACH_FEATURE(PARSE_FEATURE_BIT)
2309
2310 #undef PARSE_FEATURE_BIT
2311
2312 PrintToConsole("\nUnrecognized feature \"%s\".\n\n", aFeature);
2313 // Since we may have an old feature we don't implement anymore, don't exit.
2314 PrintUsage();
2315 return 0;
2316 }
2317
2318 uint32_t ParseFeaturesFromStringArray(const char** aFeatures,
2319 uint32_t aFeatureCount,
2320 bool aIsStartup /* = false */) {
2321 uint32_t features = 0;
2322 for (size_t i = 0; i < aFeatureCount; i++) {
2323 features |= ParseFeature(aFeatures[i], aIsStartup);
2324 }
2325 return features;
2326 }
2327
2328 // Find the RegisteredThread for the current thread. This should only be called
2329 // in places where TLSRegisteredThread can't be used.
2330 static RegisteredThread* FindCurrentThreadRegisteredThread(PSLockRef aLock) {
2331 BaseProfilerThreadId id = profiler_current_thread_id();
2332 const Vector<UniquePtr<RegisteredThread>>& registeredThreads =
2333 CorePS::RegisteredThreads(aLock);
2334 for (auto& registeredThread : registeredThreads) {
2335 if (registeredThread->Info()->ThreadId() == id) {
2336 return registeredThread.get();
2337 }
2338 }
2339
2340 return nullptr;
2341 }
2342
2343 static ProfilingStack* locked_register_thread(PSLockRef aLock,
2344 const char* aName,
2345 void* aStackTop) {
2346 MOZ_RELEASE_ASSERT(CorePS::Exists());
2347
2348 MOZ_ASSERT(!FindCurrentThreadRegisteredThread(aLock));
2349
2350 VTUNE_REGISTER_THREAD(aName);
2351
2352 if (!TLSRegisteredThread::Init(aLock)) {
2353 return nullptr;
2354 }
2355
2356 RefPtr<ThreadInfo> info = new ThreadInfo(aName, profiler_current_thread_id(),
2357 profiler_is_main_thread());
2358 UniquePtr<RegisteredThread> registeredThread =
2359 MakeUnique<RegisteredThread>(info, aStackTop);
2360
2361 TLSRegisteredThread::SetRegisteredThread(aLock, registeredThread.get());
2362
2363 if (ActivePS::Exists(aLock) && ActivePS::ShouldProfileThread(aLock, info)) {
2364 registeredThread->RacyRegisteredThread().SetIsBeingProfiled(true);
2365 ActivePS::AddLiveProfiledThread(aLock, registeredThread.get(),
2366 MakeUnique<ProfiledThreadData>(info));
2367 }
2368
2369 ProfilingStack* profilingStack =
2370 &registeredThread->RacyRegisteredThread().ProfilingStack();
2371
2372 CorePS::AppendRegisteredThread(aLock, std::move(registeredThread));
2373
2374 return profilingStack;
2375 }
2376
2377 static void locked_profiler_start(PSLockRef aLock, PowerOfTwo32 aCapacity,
2378 double aInterval, uint32_t aFeatures,
2379 const char** aFilters, uint32_t aFilterCount,
2380 const Maybe<double>& aDuration);
2381
2382 static Vector<const char*> SplitAtCommas(const char* aString,
2383 UniquePtr<char[]>& aStorage) {
2384 size_t len = strlen(aString);
2385 aStorage = MakeUnique<char[]>(len + 1);
2386 PodCopy(aStorage.get(), aString, len + 1);
2387
2388 // Iterate over all characters in aStorage and split at commas, by
2389 // overwriting commas with the null char.
2390 Vector<const char*> array;
2391 size_t currentElementStart = 0;
2392 for (size_t i = 0; i <= len; i++) {
2393 if (aStorage[i] == ',') {
2394 aStorage[i] = '\0';
2395 }
2396 if (aStorage[i] == '\0') {
2397 // Only add non-empty elements, otherwise ParseFeatures would later
2398 // complain about unrecognized features.
2399 if (currentElementStart != i) {
2400 MOZ_RELEASE_ASSERT(array.append(&aStorage[currentElementStart]));
2401 }
2402 currentElementStart = i + 1;
2403 }
2404 }
2405 return array;
2406 }
2407
2408 static const char* get_size_suffix(const char* str) {
2409 const char* ptr = str;
2410
2411 while (isdigit(*ptr)) {
2412 ptr++;
2413 }
2414
2415 return ptr;
2416 }
2417
2418 void profiler_init(void* aStackTop) {
2419 LOG("profiler_init");
2420
2421 profiler_init_main_thread_id();
2422
2423 Flow::Init();
2424
2425 VTUNE_INIT();
2426
2427 MOZ_RELEASE_ASSERT(!CorePS::Exists());
2428
2429 if (getenv("MOZ_BASE_PROFILER_HELP")) {
2430 PrintUsage();
2431 exit(0);
2432 }
2433
2434 SharedLibraryInfo::Initialize();
2435
2436 uint32_t features = DefaultFeatures() & AvailableFeatures();
2437
2438 UniquePtr<char[]> filterStorage;
2439
2440 Vector<const char*> filters;
2441 MOZ_RELEASE_ASSERT(filters.append(kMainThreadName));
2442
2443 PowerOfTwo32 capacity = BASE_PROFILER_DEFAULT_ENTRIES;
2444 Maybe<double> duration = Nothing();
2445 double interval = BASE_PROFILER_DEFAULT_INTERVAL;
2446
2447 {
2448 PSAutoLock lock;
2449
2450 // We've passed the possible failure point. Instantiate CorePS, which
2451 // indicates that the profiler has initialized successfully.
2452 CorePS::Create(lock);
2453
2454 Unused << locked_register_thread(lock, kMainThreadName, aStackTop);
2455
2456 // Platform-specific initialization.
2457 PlatformInit(lock);
2458
2459 // (Linux-only) We could create CorePS::mLul and read unwind info into it
2460 // at this point. That would match the lifetime implied by destruction of
2461 // it in profiler_shutdown() just below. However, that gives a big delay on
2462 // startup, even if no profiling is actually to be done. So, instead, it is
2463 // created on demand at the first call to PlatformStart().
2464
2465 const char* startupEnv = getenv("MOZ_PROFILER_STARTUP");
2466 if (!startupEnv || startupEnv[0] == '\0' ||
2467 ((startupEnv[0] == '0' || startupEnv[0] == 'N' ||
2468 startupEnv[0] == 'n') &&
2469 startupEnv[1] == '\0')) {
2470 return;
2471 }
2472
2473 // Hidden option to stop Base Profiler, mostly due to Talos intermittents,
2474 // see https://bugzilla.mozilla.org/show_bug.cgi?id=1638851#c3
2475 // TODO: Investigate root cause and remove this in bugs 1648324 and 1648325.
2476 if (getenv("MOZ_PROFILER_STARTUP_NO_BASE")) {
2477 return;
2478 }
2479
2480 LOG("- MOZ_PROFILER_STARTUP is set");
2481
2482 // Startup default capacity may be different.
2483 capacity = BASE_PROFILER_DEFAULT_STARTUP_ENTRIES;
2484
2485 const char* startupCapacity = getenv("MOZ_PROFILER_STARTUP_ENTRIES");
2486 if (startupCapacity && startupCapacity[0] != '\0') {
2487 errno = 0;
2488 long capacityLong = strtol(startupCapacity, nullptr, 10);
2489 std::string_view sizeSuffix = get_size_suffix(startupCapacity);
2490
2491 if (sizeSuffix == "KB") {
2492 capacityLong *= 1000 / scBytesPerEntry;
2493 } else if (sizeSuffix == "KiB") {
2494 capacityLong *= 1024 / scBytesPerEntry;
2495 } else if (sizeSuffix == "MB") {
2496 capacityLong *= (1000 * 1000) / scBytesPerEntry;
2497 } else if (sizeSuffix == "MiB") {
2498 capacityLong *= (1024 * 1024) / scBytesPerEntry;
2499 } else if (sizeSuffix == "GB") {
2500 capacityLong *= (1000 * 1000 * 1000) / scBytesPerEntry;
2501 } else if (sizeSuffix == "GiB") {
2502 capacityLong *= (1024 * 1024 * 1024) / scBytesPerEntry;
2503 } else if (!sizeSuffix.empty()) {
2504 PrintToConsole(
2505 "- MOZ_PROFILER_STARTUP_ENTRIES unit must be one of the "
2506 "following: KB, KiB, MB, MiB, GB, GiB");
2507 PrintUsage();
2508 exit(1);
2509 }
2510
2511 // `long` could be 32 or 64 bits, so we force a 64-bit comparison with
2512 // the maximum 32-bit signed number (as more than that is clamped down to
2513 // 2^31 anyway).
2514 if (errno == 0 && capacityLong > 0 &&
2515 static_cast<uint64_t>(capacityLong) <=
2516 static_cast<uint64_t>(INT32_MAX)) {
2517 capacity = PowerOfTwo32(
2518 ClampToAllowedEntries(static_cast<uint32_t>(capacityLong)));
2519 LOG("- MOZ_PROFILER_STARTUP_ENTRIES = %u", unsigned(capacity.Value()));
2520 } else {
2521 PrintToConsole("- MOZ_PROFILER_STARTUP_ENTRIES not a valid integer: %s",
2522 startupCapacity);
2523 PrintUsage();
2524 exit(1);
2525 }
2526 }
2527
2528 const char* startupDuration = getenv("MOZ_PROFILER_STARTUP_DURATION");
2529 if (startupDuration && startupDuration[0] != '\0') {
2530 // The duration is a floating point number. Use StringToDouble rather than
2531 // strtod, so that "." is used as the decimal separator regardless of OS
2532 // locale.
2533 auto durationVal = StringToDouble(std::string(startupDuration));
2534 if (durationVal && *durationVal >= 0.0) {
2535 if (*durationVal > 0.0) {
2536 duration = Some(*durationVal);
2537 }
2538 LOG("- MOZ_PROFILER_STARTUP_DURATION = %f", *durationVal);
2539 } else {
2540 PrintToConsole("- MOZ_PROFILER_STARTUP_DURATION not a valid float: %s",
2541 startupDuration);
2542 PrintUsage();
2543 exit(1);
2544 }
2545 }
2546
2547 const char* startupInterval = getenv("MOZ_PROFILER_STARTUP_INTERVAL");
2548 if (startupInterval && startupInterval[0] != '\0') {
2549 // The interval is a floating point number. Use StringToDouble rather than
2550 // strtod, so that "." is used as the decimal separator regardless of OS
2551 // locale.
2552 auto intervalValue = StringToDouble(MakeStringSpan(startupInterval));
2553 if (intervalValue && *intervalValue > 0.0 && *intervalValue <= 1000.0) {
2554 interval = *intervalValue;
2555 LOG("- MOZ_PROFILER_STARTUP_INTERVAL = %f", interval);
2556 } else {
2557 PrintToConsole("- MOZ_PROFILER_STARTUP_INTERVAL not a valid float: %s",
2558 startupInterval);
2559 PrintUsage();
2560 exit(1);
2561 }
2562 }
2563
2564 features |= StartupExtraDefaultFeatures() & AvailableFeatures();
2565
2566 const char* startupFeaturesBitfield =
2567 getenv("MOZ_PROFILER_STARTUP_FEATURES_BITFIELD");
2568 if (startupFeaturesBitfield && startupFeaturesBitfield[0] != '\0') {
2569 errno = 0;
2570 features = strtol(startupFeaturesBitfield, nullptr, 10);
2571 if (errno == 0) {
2572 LOG("- MOZ_PROFILER_STARTUP_FEATURES_BITFIELD = %d", features);
2573 } else {
2574 PrintToConsole(
2575 "- MOZ_PROFILER_STARTUP_FEATURES_BITFIELD not a valid integer: %s",
2576 startupFeaturesBitfield);
2577 PrintUsage();
2578 exit(1);
2579 }
2580 } else {
2581 const char* startupFeatures = getenv("MOZ_PROFILER_STARTUP_FEATURES");
2582 if (startupFeatures) {
2583 // Interpret startupFeatures as a list of feature strings, separated by
2584 // commas.
2585 UniquePtr<char[]> featureStringStorage;
2586 Vector<const char*> featureStringArray =
2587 SplitAtCommas(startupFeatures, featureStringStorage);
2588 features = ParseFeaturesFromStringArray(featureStringArray.begin(),
2589 featureStringArray.length(),
2590 /* aIsStartup */ true);
2591 LOG("- MOZ_PROFILER_STARTUP_FEATURES = %d", features);
2592 }
2593 }
2594
2595 const char* startupFilters = getenv("MOZ_PROFILER_STARTUP_FILTERS");
2596 if (startupFilters && startupFilters[0] != '\0') {
2597 filters = SplitAtCommas(startupFilters, filterStorage);
2598 LOG("- MOZ_PROFILER_STARTUP_FILTERS = %s", startupFilters);
2599
2600 if (mozilla::profiler::detail::FiltersExcludePid(filters)) {
2601 LOG(" -> This process is excluded and won't be profiled");
2602 return;
2603 }
2604 }
2605
2606 locked_profiler_start(lock, capacity, interval, features, filters.begin(),
2607 filters.length(), duration);
2608 }
2609
2610 // TODO: Install memory counter if it is possible from mozglue.
2611 // #if defined(MOZ_REPLACE_MALLOC) && defined(MOZ_PROFILER_MEMORY)
2612 // // start counting memory allocations (outside of lock because this may
2613 // call
2614 // // profiler_add_sampled_counter which would attempt to take the lock.)
2615 // mozilla::profiler::install_memory_counter(true);
2616 // #endif
2617 }
2618
2619 static void locked_profiler_save_profile_to_file(PSLockRef aLock,
2620 const char* aFilename,
2621 bool aIsShuttingDown);
2622
2623 static SamplerThread* locked_profiler_stop(PSLockRef aLock);
2624
2625 void profiler_shutdown() {
2626 LOG("profiler_shutdown");
2627
2628 VTUNE_SHUTDOWN();
2629
2630 MOZ_RELEASE_ASSERT(profiler_is_main_thread());
2631 MOZ_RELEASE_ASSERT(CorePS::Exists());
2632
2633 // If the profiler is active we must get a handle to the SamplerThread before
2634 // ActivePS is destroyed, in order to delete it.
2635 SamplerThread* samplerThread = nullptr;
2636 {
2637 PSAutoLock lock;
2638
2639 // Save the profile on shutdown if requested.
2640 if (ActivePS::Exists(lock)) {
2641 const char* filename = getenv("MOZ_PROFILER_SHUTDOWN");
2642 if (filename && filename[0] != '\0') {
2643 locked_profiler_save_profile_to_file(lock, filename,
2644 /* aIsShuttingDown */ true);
2645 }
2646
2647 samplerThread = locked_profiler_stop(lock);
2648 }
2649
2650 CorePS::Destroy(lock);
2651
2652 // We just destroyed CorePS and the ThreadInfos it contains, so we can
2653 // clear this thread's TLSRegisteredThread.
2654 TLSRegisteredThread::SetRegisteredThread(lock, nullptr);
2655 }
2656
2657 // We do these operations with gPSMutex unlocked. The comments in
2658 // profiler_stop() explain why.
2659 if (samplerThread) {
2660 delete samplerThread;
2661 }
2662 }
2663
2664 static bool WriteProfileToJSONWriter(SpliceableChunkedJSONWriter& aWriter,
2665 double aSinceTime, bool aIsShuttingDown,
2666 bool aOnlyThreads = false) {
2667 LOG("WriteProfileToJSONWriter");
2668
2669 MOZ_RELEASE_ASSERT(CorePS::Exists());
2670
2671 if (!aOnlyThreads) {
2672 aWriter.Start();
2673 {
2674 if (!profiler_stream_json_for_this_process(
2675 aWriter, aSinceTime, aIsShuttingDown, aOnlyThreads)) {
2676 return false;
2677 }
2678
2679 // Don't include profiles from other processes because this is a
2680 // synchronous function.
2681 aWriter.StartArrayProperty("processes");
2682 aWriter.EndArray();
2683 }
2684 aWriter.End();
2685 } else {
2686 aWriter.StartBareList();
2687 if (!profiler_stream_json_for_this_process(aWriter, aSinceTime,
2688 aIsShuttingDown, aOnlyThreads)) {
2689 return false;
2690 }
2691 aWriter.EndBareList();
2692 }
2693 return true;
2694 }
2695
2696 void profiler_set_process_name(const std::string& aProcessName,
2697 const std::string* aETLDplus1) {
2698 LOG("profiler_set_process_name(\"%s\", \"%s\")", aProcessName.c_str(),
2699 aETLDplus1 ? aETLDplus1->c_str() : "<none>");
2700 PSAutoLock lock;
2701 CorePS::SetProcessName(lock, aProcessName);
2702 if (aETLDplus1) {
2703 CorePS::SetETLDplus1(lock, *aETLDplus1);
2704 }
2705 }
2706
2707 UniquePtr<char[]> profiler_get_profile(double aSinceTime, bool aIsShuttingDown,
2708 bool aOnlyThreads) {
2709 LOG("profiler_get_profile");
2710
2711 SpliceableChunkedJSONWriter b{FailureLatchInfallibleSource::Singleton()};
2712 if (!WriteProfileToJSONWriter(b, aSinceTime, aIsShuttingDown, aOnlyThreads)) {
2713 return nullptr;
2714 }
2715 return b.ChunkedWriteFunc().CopyData();
2716 }
2717
2718 void profiler_get_start_params(int* aCapacity, Maybe<double>* aDuration,
2719 double* aInterval, uint32_t* aFeatures,
2720 Vector<const char*>* aFilters) {
2721 MOZ_RELEASE_ASSERT(CorePS::Exists());
2722
2723 if (!aCapacity || !aDuration || !aInterval || !aFeatures || !aFilters) {
2724 return;
2725 }
2726
2727 PSAutoLock lock;
2728
2729 if (!ActivePS::Exists(lock)) {
2730 *aCapacity = 0;
2731 *aDuration = Nothing();
2732 *aInterval = 0;
2733 *aFeatures = 0;
2734 aFilters->clear();
2735 return;
2736 }
2737
2738 *aCapacity = ActivePS::Capacity(lock).Value();
2739 *aDuration = ActivePS::Duration(lock);
2740 *aInterval = ActivePS::Interval(lock);
2741 *aFeatures = ActivePS::Features(lock);
2742
2743 const Vector<std::string>& filters = ActivePS::Filters(lock);
2744 MOZ_ALWAYS_TRUE(aFilters->resize(filters.length()));
2745 for (uint32_t i = 0; i < filters.length(); ++i) {
2746 (*aFilters)[i] = filters[i].c_str();
2747 }
2748 }
2749
2750 void GetProfilerEnvVarsForChildProcess(
2751 std::function<void(const char* key, const char* value)>&& aSetEnv) {
2752 MOZ_RELEASE_ASSERT(CorePS::Exists());
2753
2754 PSAutoLock lock;
2755
2756 if (!ActivePS::Exists(lock)) {
2757 aSetEnv("MOZ_PROFILER_STARTUP", "");
2758 return;
2759 }
2760
2761 aSetEnv("MOZ_PROFILER_STARTUP", "1");
2762 auto capacityString =
2763 Smprintf("%u", unsigned(ActivePS::Capacity(lock).Value()));
2764 aSetEnv("MOZ_PROFILER_STARTUP_ENTRIES", capacityString.get());
2765
2766 // Use AppendFloat instead of Smprintf with %f because the decimal
2767 // separator used by %f is locale-dependent. But the string we produce needs
2768 // to be parseable by strtod, which only accepts the period character as a
2769 // decimal separator. AppendFloat always uses the period character.
2770 std::string intervalString = std::to_string(ActivePS::Interval(lock));
2771 aSetEnv("MOZ_PROFILER_STARTUP_INTERVAL", intervalString.c_str());
2772
2773 auto featuresString = Smprintf("%d", ActivePS::Features(lock));
2774 aSetEnv("MOZ_PROFILER_STARTUP_FEATURES_BITFIELD", featuresString.get());
2775
2776 std::string filtersString;
2777 const Vector<std::string>& filters = ActivePS::Filters(lock);
2778 for (uint32_t i = 0; i < filters.length(); ++i) {
2779 filtersString += filters[i];
2780 if (i != filters.length() - 1) {
2781 filtersString += ",";
2782 }
2783 }
2784 aSetEnv("MOZ_PROFILER_STARTUP_FILTERS", filtersString.c_str());
2785 }
2786
2787 void profiler_received_exit_profile(const std::string& aExitProfile) {
2788 MOZ_RELEASE_ASSERT(CorePS::Exists());
2789 PSAutoLock lock;
2790 if (!ActivePS::Exists(lock)) {
2791 return;
2792 }
2793 ActivePS::AddExitProfile(lock, aExitProfile);
2794 }
2795
2796 Vector<std::string> profiler_move_exit_profiles() {
2797 MOZ_RELEASE_ASSERT(CorePS::Exists());
2798 PSAutoLock lock;
2799 Vector<std::string> profiles;
2800 if (ActivePS::Exists(lock)) {
2801 profiles = ActivePS::MoveExitProfiles(lock);
2802 }
2803 return profiles;
2804 }
2805
2806 static void locked_profiler_save_profile_to_file(PSLockRef aLock,
2807 const char* aFilename,
2808 bool aIsShuttingDown = false) {
2809 LOG("locked_profiler_save_profile_to_file(%s)", aFilename);
2810
2811 MOZ_RELEASE_ASSERT(CorePS::Exists() && ActivePS::Exists(aLock));
2812
2813 std::ofstream stream;
2814 stream.open(aFilename);
2815 if (stream.is_open()) {
2816 OStreamJSONWriteFunc jw(stream);
2817 SpliceableJSONWriter w(jw, FailureLatchInfallibleSource::Singleton());
2818 w.Start();
2819 {
2820 locked_profiler_stream_json_for_this_process(aLock, w, /* sinceTime */ 0,
2821 aIsShuttingDown);
2822
2823 w.StartArrayProperty("processes");
2824 Vector<std::string> exitProfiles = ActivePS::MoveExitProfiles(aLock);
2825 for (auto& exitProfile : exitProfiles) {
2826 if (!exitProfile.empty()) {
2827 w.Splice(exitProfile);
2828 }
2829 }
2830 w.EndArray();
2831 }
2832 w.End();
2833
2834 stream.close();
2835 }
2836 }
2837
2838 void baseprofiler_save_profile_to_file(const char* aFilename) {
2839 LOG("baseprofiler_save_profile_to_file(%s)", aFilename);
2840
2841 MOZ_RELEASE_ASSERT(CorePS::Exists());
2842
2843 PSAutoLock lock;
2844
2845 if (!ActivePS::Exists(lock)) {
2846 return;
2847 }
2848
2849 locked_profiler_save_profile_to_file(lock, aFilename);
2850 }
2851
2852 uint32_t profiler_get_available_features() {
2853 MOZ_RELEASE_ASSERT(CorePS::Exists());
2854 return AvailableFeatures();
2855 }
2856
2857 Maybe<ProfilerBufferInfo> profiler_get_buffer_info() {
2858 MOZ_RELEASE_ASSERT(CorePS::Exists());
2859
2860 PSAutoLock lock;
2861
2862 if (!ActivePS::Exists(lock)) {
2863 return Nothing();
2864 }
2865
2866 return Some(ActivePS::Buffer(lock).GetProfilerBufferInfo());
2867 }
2868
2869 // This basically duplicates AutoProfilerLabel's constructor.
2870 static void* MozGlueBaseLabelEnter(const char* aLabel,
2871 const char* aDynamicString, void* aSp) {
2872 ProfilingStack* profilingStack = AutoProfilerLabel::sProfilingStack.get();
2873 if (profilingStack) {
2874 profilingStack->pushLabelFrame(aLabel, aDynamicString, aSp,
2875 ProfilingCategoryPair::OTHER);
2876 }
2877 return profilingStack;
2878 }
2879
2880 // This basically duplicates AutoProfilerLabel's destructor.
2881 static void MozGlueBaseLabelExit(void* sProfilingStack) {
2882 if (sProfilingStack) {
2883 reinterpret_cast<ProfilingStack*>(sProfilingStack)->pop();
2884 }
2885 }
2886
2887 static void locked_profiler_start(PSLockRef aLock, PowerOfTwo32 aCapacity,
2888 double aInterval, uint32_t aFeatures,
2889 const char** aFilters, uint32_t aFilterCount,
2890 const Maybe<double>& aDuration) {
2891 const TimeStamp profilingStartTime = TimeStamp::Now();
2892
2893 if (LOG_TEST) {
2894 LOG("locked_profiler_start");
2895 LOG("- capacity = %d", int(aCapacity.Value()));
2896 LOG("- duration = %.2f", aDuration ? *aDuration : -1);
2897 LOG("- interval = %.2f", aInterval);
2898
2899 #define LOG_FEATURE(n_, str_, Name_, desc_) \
2900 if (ProfilerFeature::Has##Name_(aFeatures)) { \
2901 LOG("- feature = %s", str_); \
2902 }
2903
2904 BASE_PROFILER_FOR_EACH_FEATURE(LOG_FEATURE)
2905
2906 #undef LOG_FEATURE
2907
2908 for (uint32_t i = 0; i < aFilterCount; i++) {
2909 LOG("- threads = %s", aFilters[i]);
2910 }
2911 }
2912
2913 MOZ_RELEASE_ASSERT(CorePS::Exists() && !ActivePS::Exists(aLock));
2914
2915 mozilla::base_profiler_markers_detail::EnsureBufferForMainThreadAddMarker();
2916
2917 #if defined(GP_PLAT_amd64_windows) || defined(GP_PLAT_arm64_windows)
2918 mozilla::WindowsStackWalkInitialization();
2919 #endif
2920
2921 // Fall back to the default values if the passed-in values are unreasonable.
2922 // We want to be able to store at least one full stack.
2923 // TODO: Review magic numbers.
2924 PowerOfTwo32 capacity =
2925 (aCapacity.Value() >=
2926 ProfileBufferChunkManager::scExpectedMaximumStackSize / scBytesPerEntry)
2927 ? aCapacity
2928 : BASE_PROFILER_DEFAULT_ENTRIES;
2929 Maybe<double> duration = aDuration;
2930
2931 if (aDuration && *aDuration <= 0) {
2932 duration = Nothing();
2933 }
2934 double interval = aInterval > 0 ? aInterval : BASE_PROFILER_DEFAULT_INTERVAL;
2935
2936 ActivePS::Create(aLock, profilingStartTime, capacity, interval, aFeatures,
2937 aFilters, aFilterCount, duration);
2938
2939 // Set up profiling for each registered thread, if appropriate.
2940 const Vector<UniquePtr<RegisteredThread>>& registeredThreads =
2941 CorePS::RegisteredThreads(aLock);
2942 for (auto& registeredThread : registeredThreads) {
2943 RefPtr<ThreadInfo> info = registeredThread->Info();
2944
2945 if (ActivePS::ShouldProfileThread(aLock, info)) {
2946 registeredThread->RacyRegisteredThread().SetIsBeingProfiled(true);
2947 ActivePS::AddLiveProfiledThread(aLock, registeredThread.get(),
2948 MakeUnique<ProfiledThreadData>(info));
2949 registeredThread->RacyRegisteredThread().ReinitializeOnResume();
2950 }
2951 }
2952
2953 // Setup support for pushing/popping labels in mozglue.
2954 RegisterProfilerLabelEnterExit(MozGlueBaseLabelEnter, MozGlueBaseLabelExit);
2955
2956 // At the very end, set up RacyFeatures.
2957 RacyFeatures::SetActive(ActivePS::Features(aLock));
2958 }
2959
2960 void profiler_start(PowerOfTwo32 aCapacity, double aInterval,
2961 uint32_t aFeatures, const char** aFilters,
2962 uint32_t aFilterCount, const Maybe<double>& aDuration) {
2963 LOG("profiler_start");
2964
2965 SamplerThread* samplerThread = nullptr;
2966 {
2967 PSAutoLock lock;
2968
2969 // Initialize if necessary.
2970 if (!CorePS::Exists()) {
2971 profiler_init(nullptr);
2972 }
2973
2974 // Reset the current state if the profiler is running.
2975 if (ActivePS::Exists(lock)) {
2976 samplerThread = locked_profiler_stop(lock);
2977 }
2978
2979 locked_profiler_start(lock, aCapacity, aInterval, aFeatures, aFilters,
2980 aFilterCount, aDuration);
2981 }
2982
2983 // TODO: Install memory counter if it is possible from mozglue.
2984 // #if defined(MOZ_REPLACE_MALLOC) && defined(MOZ_PROFILER_MEMORY)
2985 // // start counting memory allocations (outside of lock because this may
2986 // call
2987 // // profiler_add_sampled_counter which would attempt to take the lock.)
2988 // mozilla::profiler::install_memory_counter(true);
2989 // #endif
2990
2991 // We do these operations with gPSMutex unlocked. The comments in
2992 // profiler_stop() explain why.
2993 if (samplerThread) {
2994 delete samplerThread;
2995 }
2996 }
2997
2998 void profiler_ensure_started(PowerOfTwo32 aCapacity, double aInterval,
2999 uint32_t aFeatures, const char** aFilters,
3000 uint32_t aFilterCount,
3001 const Maybe<double>& aDuration) {
3002 LOG("profiler_ensure_started");
3003
3004 // bool startedProfiler = false; (See TODO below)
3005 SamplerThread* samplerThread = nullptr;
3006 {
3007 PSAutoLock lock;
3008
3009 // Initialize if necessary.
3010 if (!CorePS::Exists()) {
3011 profiler_init(nullptr);
3012 }
3013
3014 if (ActivePS::Exists(lock)) {
3015 // The profiler is active.
3016 if (!ActivePS::Equals(lock, aCapacity, aDuration, aInterval, aFeatures,
3017 aFilters, aFilterCount)) {
3018 // Stop and restart with different settings.
3019 samplerThread = locked_profiler_stop(lock);
3020 locked_profiler_start(lock, aCapacity, aInterval, aFeatures, aFilters,
3021 aFilterCount, aDuration);
3022 // startedProfiler = true; (See TODO below)
3023 }
3024 } else {
3025 // The profiler is stopped.
3026 locked_profiler_start(lock, aCapacity, aInterval, aFeatures, aFilters,
3027 aFilterCount, aDuration);
3028 // startedProfiler = true; (See TODO below)
3029 }
3030 }
3031
3032 // TODO: Install memory counter if it is possible from mozglue.
3033 // #if defined(MOZ_REPLACE_MALLOC) && defined(MOZ_PROFILER_MEMORY)
3034 // // start counting memory allocations (outside of lock because this may
3035 // // call profiler_add_sampled_counter which would attempt to take the
3036 // // lock.)
3037 // mozilla::profiler::install_memory_counter(true);
3038 // #endif
3039
3040 // We do these operations with gPSMutex unlocked. The comments in
3041 // profiler_stop() explain why.
3042 if (samplerThread) {
3043 delete samplerThread;
3044 }
3045 }
3046
3047 [[nodiscard]] static SamplerThread* locked_profiler_stop(PSLockRef aLock) {
3048 LOG("locked_profiler_stop");
3049
3050 MOZ_RELEASE_ASSERT(CorePS::Exists() && ActivePS::Exists(aLock));
3051
3052 // At the very start, clear RacyFeatures.
3053 RacyFeatures::SetInactive();
3054
3055 // TODO: Uninstall memory counter if it is possible from mozglue.
3056 // #if defined(MOZ_REPLACE_MALLOC) && defined(MOZ_PROFILER_MEMORY)
3057 // mozilla::profiler::install_memory_counter(false);
3058 // #endif
3059
3060 // Remove support for pushing/popping labels in mozglue.
3061 RegisterProfilerLabelEnterExit(nullptr, nullptr);
3062
3063 // Stop sampling live threads.
3064 const Vector<LiveProfiledThreadData>& liveProfiledThreads =
3065 ActivePS::LiveProfiledThreads(aLock);
3066 for (auto& thread : liveProfiledThreads) {
3067 RegisteredThread* registeredThread = thread.mRegisteredThread;
3068 registeredThread->RacyRegisteredThread().SetIsBeingProfiled(false);
3069 }
3070
3071 // The Stop() call doesn't actually stop Run(); that happens in this
3072 // function's caller when the sampler thread is destroyed. Stop() just gives
3073 // the SamplerThread a chance to do some cleanup with gPSMutex locked.
3074 SamplerThread* samplerThread = ActivePS::Destroy(aLock);
3075 samplerThread->Stop(aLock);
3076
3077 mozilla::base_profiler_markers_detail::ReleaseBufferForMainThreadAddMarker();
3078
3079 return samplerThread;
3080 }
3081
3082 void profiler_stop() {
3083 LOG("profiler_stop");
3084
3085 MOZ_RELEASE_ASSERT(CorePS::Exists());
3086
3087 SamplerThread* samplerThread;
3088 {
3089 PSAutoLock lock;
3090
3091 if (!ActivePS::Exists(lock)) {
3092 return;
3093 }
3094
3095 samplerThread = locked_profiler_stop(lock);
3096 }
3097
3098 // We delete with gPSMutex unlocked. Otherwise we would get a deadlock: we
3099 // would be waiting here with gPSMutex locked for SamplerThread::Run() to
3100 // return so the join operation within the destructor can complete, but Run()
3101 // needs to lock gPSMutex to return.
3102 //
3103 // Because this call occurs with gPSMutex unlocked, it -- including the final
3104 // iteration of Run()'s loop -- must be able detect deactivation and return
3105 // in a way that's safe with respect to other gPSMutex-locking operations
3106 // that may have occurred in the meantime.
3107 delete samplerThread;
3108 }
3109
3110 bool profiler_is_paused() {
3111 MOZ_RELEASE_ASSERT(CorePS::Exists());
3112
3113 PSAutoLock lock;
3114
3115 if (!ActivePS::Exists(lock)) {
3116 return false;
3117 }
3118
3119 return ActivePS::IsPaused(lock);
3120 }
3121
3122 void profiler_pause() {
3123 LOG("profiler_pause");
3124
3125 MOZ_RELEASE_ASSERT(CorePS::Exists());
3126
3127 {
3128 PSAutoLock lock;
3129
3130 if (!ActivePS::Exists(lock)) {
3131 return;
3132 }
3133
3134 RacyFeatures::SetPaused();
3135 ActivePS::SetIsPaused(lock, true);
3136 ActivePS::Buffer(lock).AddEntry(ProfileBufferEntry::Pause(profiler_time()));
3137 }
3138 }
3139
3140 void profiler_resume() {
3141 LOG("profiler_resume");
3142
3143 MOZ_RELEASE_ASSERT(CorePS::Exists());
3144
3145 {
3146 PSAutoLock lock;
3147
3148 if (!ActivePS::Exists(lock)) {
3149 return;
3150 }
3151
3152 ActivePS::Buffer(lock).AddEntry(
3153 ProfileBufferEntry::Resume(profiler_time()));
3154 ActivePS::SetIsPaused(lock, false);
3155 RacyFeatures::SetUnpaused();
3156 }
3157 }
3158
3159 bool profiler_is_sampling_paused() {
3160 MOZ_RELEASE_ASSERT(CorePS::Exists());
3161
3162 PSAutoLock lock;
3163
3164 if (!ActivePS::Exists(lock)) {
3165 return false;
3166 }
3167
3168 return ActivePS::IsSamplingPaused(lock);
3169 }
3170
3171 void profiler_pause_sampling() {
3172 LOG("profiler_pause_sampling");
3173
3174 MOZ_RELEASE_ASSERT(CorePS::Exists());
3175
3176 {
3177 PSAutoLock lock;
3178
3179 if (!ActivePS::Exists(lock)) {
3180 return;
3181 }
3182
3183 RacyFeatures::SetSamplingPaused();
3184 ActivePS::SetIsSamplingPaused(lock, true);
3185 ActivePS::Buffer(lock).AddEntry(
3186 ProfileBufferEntry::PauseSampling(profiler_time()));
3187 }
3188 }
3189
3190 void profiler_resume_sampling() {
3191 LOG("profiler_resume_sampling");
3192
3193 MOZ_RELEASE_ASSERT(CorePS::Exists());
3194
3195 {
3196 PSAutoLock lock;
3197
3198 if (!ActivePS::Exists(lock)) {
3199 return;
3200 }
3201
3202 ActivePS::Buffer(lock).AddEntry(
3203 ProfileBufferEntry::ResumeSampling(profiler_time()));
3204 ActivePS::SetIsSamplingPaused(lock, false);
3205 RacyFeatures::SetSamplingUnpaused();
3206 }
3207 }
3208
3209 bool profiler_feature_active(uint32_t aFeature) {
3210 // This function runs both on and off the main thread.
3211
3212 MOZ_RELEASE_ASSERT(CorePS::Exists());
3213
3214 // This function is hot enough that we use RacyFeatures, not ActivePS.
3215 return RacyFeatures::IsActiveWithFeature(aFeature);
3216 }
3217
3218 bool profiler_active_without_feature(uint32_t aFeature) {
3219 // This function runs both on and off the main thread.
3220
3221 // This function is hot enough that we use RacyFeatures, not ActivePS.
3222 return RacyFeatures::IsActiveWithoutFeature(aFeature);
3223 }
3224
3225 void profiler_add_sampled_counter(BaseProfilerCount* aCounter) {
3226 DEBUG_LOG("profiler_add_sampled_counter(%s)", aCounter->mLabel);
3227 PSAutoLock lock;
3228 CorePS::AppendCounter(lock, aCounter);
3229 }
3230
3231 void profiler_remove_sampled_counter(BaseProfilerCount* aCounter) {
3232 DEBUG_LOG("profiler_remove_sampled_counter(%s)", aCounter->mLabel);
3233 PSAutoLock lock;
3234 // Note: we don't enforce a final sample, though we could do so if the
3235 // profiler was active
3236 CorePS::RemoveCounter(lock, aCounter);
3237 }
3238
3239 ProfilingStack* profiler_register_thread(const char* aName,
3240 void* aGuessStackTop) {
3241 DEBUG_LOG("profiler_register_thread(%s)", aName);
3242
3243 MOZ_RELEASE_ASSERT(CorePS::Exists());
3244
3245 PSAutoLock lock;
3246
3247 if (RegisteredThread* thread = FindCurrentThreadRegisteredThread(lock);
3248 thread) {
3249 LOG("profiler_register_thread(%s) - thread %" PRIu64
3250 " already registered as %s",
3251 aName, uint64_t(profiler_current_thread_id().ToNumber()),
3252 thread->Info()->Name());
3253 // TODO: Use new name. This is currently not possible because the
3254 // RegisteredThread's ThreadInfo cannot be changed.
3255 // In the meantime, we record a marker that could be used in the frontend.
3256 std::string text("Thread ");
3257 text += std::to_string(profiler_current_thread_id().ToNumber());
3258 text += " \"";
3259 text += thread->Info()->Name();
3260 text += "\" attempted to re-register as \"";
3261 text += aName;
3262 text += "\"";
3263 BASE_PROFILER_MARKER_TEXT("profiler_register_thread again", OTHER_Profiling,
3264 MarkerThreadId::MainThread(), text);
3265
3266 return &thread->RacyRegisteredThread().ProfilingStack();
3267 }
3268
3269 void* stackTop = GetStackTop(aGuessStackTop);
3270 return locked_register_thread(lock, aName, stackTop);
3271 }
3272
3273 void profiler_unregister_thread() {
3274 if (!CorePS::Exists()) {
3275 // This function can be called after the main thread has already shut down.
3276 return;
3277 }
3278
3279 PSAutoLock lock;
3280
3281 RegisteredThread* registeredThread = FindCurrentThreadRegisteredThread(lock);
3282 MOZ_RELEASE_ASSERT(registeredThread ==
3283 TLSRegisteredThread::RegisteredThread(lock));
3284 if (registeredThread) {
3285 RefPtr<ThreadInfo> info = registeredThread->Info();
3286
3287 DEBUG_LOG("profiler_unregister_thread: %s", info->Name());
3288
3289 if (ActivePS::Exists(lock)) {
3290 ActivePS::UnregisterThread(lock, registeredThread);
3291 }
3292
3293 // Clear the pointer to the RegisteredThread object that we're about to
3294 // destroy.
3295 TLSRegisteredThread::SetRegisteredThread(lock, nullptr);
3296
3297 // Remove the thread from the list of registered threads. This deletes the
3298 // registeredThread object.
3299 CorePS::RemoveRegisteredThread(lock, registeredThread);
3300 } else {
3301 LOG("profiler_unregister_thread() - thread %" PRIu64
3302 " already unregistered",
3303 uint64_t(profiler_current_thread_id().ToNumber()));
3304 // We cannot record a marker on this thread because it was already
3305 // unregistered. Send it to the main thread (unless this *is* already the
3306 // main thread, which has been unregistered); this may be useful to catch
3307 // mismatched register/unregister pairs in Firefox.
3308 if (BaseProfilerThreadId tid = profiler_current_thread_id();
3309 tid != profiler_main_thread_id()) {
3310 BASE_PROFILER_MARKER_TEXT(
3311 "profiler_unregister_thread again", OTHER_Profiling,
3312 MarkerThreadId::MainThread(),
3313 std::to_string(profiler_current_thread_id().ToNumber()));
3314 }
3315 // There are two ways FindCurrentThreadRegisteredThread() might have failed.
3316 //
3317 // - TLSRegisteredThread::Init() failed in locked_register_thread().
3318 //
3319 // - We've already called profiler_unregister_thread() for this thread.
3320 // (Whether or not it should, this does happen in practice.)
3321 //
3322 // Either way, TLSRegisteredThread should be empty.
3323 MOZ_RELEASE_ASSERT(!TLSRegisteredThread::RegisteredThread(lock));
3324 }
3325 }
3326
3327 void profiler_register_page(uint64_t aTabID, uint64_t aInnerWindowID,
3328 const std::string& aUrl,
3329 uint64_t aEmbedderInnerWindowID) {
3330 DEBUG_LOG("profiler_register_page(%" PRIu64 ", %" PRIu64 ", %s, %" PRIu64 ")",
3331 aTabID, aInnerWindowID, aUrl.c_str(), aEmbedderInnerWindowID);
3332
3333 MOZ_RELEASE_ASSERT(CorePS::Exists());
3334
3335 PSAutoLock lock;
3336
3337 // When a Browsing context is first loaded, the first url loaded in it will be
3338 // about:blank. Because of that, this call keeps the first non-about:blank
3339 // registration of window and discards the previous one.
3340 RefPtr<PageInformation> pageInfo =
3341 new PageInformation(aTabID, aInnerWindowID, aUrl, aEmbedderInnerWindowID);
3342 CorePS::AppendRegisteredPage(lock, std::move(pageInfo));
3343
3344 // After appending the given page to CorePS, look for the expired
3345 // pages and remove them if there are any.
3346 if (ActivePS::Exists(lock)) {
3347 ActivePS::DiscardExpiredPages(lock);
3348 }
3349 }
3350
3351 void profiler_unregister_page(uint64_t aRegisteredInnerWindowID) {
3352 if (!CorePS::Exists()) {
3353 // This function can be called after the main thread has already shut down.
3354 return;
3355 }
3356
3357 PSAutoLock lock;
3358
3359 // During unregistration, if the profiler is active, we have to keep the
3360 // page information since there may be some markers associated with the given
3361 // page. But if profiler is not active. we have no reason to keep the
3362 // page information here because there can't be any marker associated with it.
3363 if (ActivePS::Exists(lock)) {
3364 ActivePS::UnregisterPage(lock, aRegisteredInnerWindowID);
3365 } else {
3366 CorePS::RemoveRegisteredPage(lock, aRegisteredInnerWindowID);
3367 }
3368 }
3369
3370 void profiler_clear_all_pages() {
3371 if (!CorePS::Exists()) {
3372 // This function can be called after the main thread has already shut down.
3373 return;
3374 }
3375
3376 {
3377 PSAutoLock lock;
3378 CorePS::ClearRegisteredPages(lock);
3379 if (ActivePS::Exists(lock)) {
3380 ActivePS::ClearUnregisteredPages(lock);
3381 }
3382 }
3383 }
3384
3385 void profiler_thread_sleep() {
3386 // This function runs both on and off the main thread.
3387
3388 MOZ_RELEASE_ASSERT(CorePS::Exists());
3389
3390 RacyRegisteredThread* racyRegisteredThread =
3391 TLSRegisteredThread::RacyRegisteredThread();
3392 if (!racyRegisteredThread) {
3393 return;
3394 }
3395
3396 racyRegisteredThread->SetSleeping();
3397 }
3398
3399 void profiler_thread_wake() {
3400 // This function runs both on and off the main thread.
3401
3402 MOZ_RELEASE_ASSERT(CorePS::Exists());
3403
3404 RacyRegisteredThread* racyRegisteredThread =
3405 TLSRegisteredThread::RacyRegisteredThread();
3406 if (!racyRegisteredThread) {
3407 return;
3408 }
3409
3410 racyRegisteredThread->SetAwake();
3411 }
3412
3413 bool detail::IsThreadBeingProfiled() {
3414 MOZ_RELEASE_ASSERT(CorePS::Exists());
3415
3416 const RacyRegisteredThread* racyRegisteredThread =
3417 TLSRegisteredThread::RacyRegisteredThread();
3418 return racyRegisteredThread && racyRegisteredThread->IsBeingProfiled();
3419 }
3420
3421 bool profiler_thread_is_sleeping() {
3422 MOZ_RELEASE_ASSERT(profiler_is_main_thread());
3423 MOZ_RELEASE_ASSERT(CorePS::Exists());
3424
3425 RacyRegisteredThread* racyRegisteredThread =
3426 TLSRegisteredThread::RacyRegisteredThread();
3427 if (!racyRegisteredThread) {
3428 return false;
3429 }
3430 return racyRegisteredThread->IsSleeping();
3431 }
3432
3433 double profiler_time() {
3434 MOZ_RELEASE_ASSERT(CorePS::Exists());
3435
3436 TimeDuration delta = TimeStamp::Now() - CorePS::ProcessStartTime();
3437 return delta.ToMilliseconds();
3438 }
3439
3440 bool profiler_capture_backtrace_into(ProfileChunkedBuffer& aChunkedBuffer,
3441 StackCaptureOptions aCaptureOptions) {
3442 MOZ_RELEASE_ASSERT(CorePS::Exists());
3443
3444 PSAutoLock lock;
3445
3446 if (!ActivePS::Exists(lock) ||
3447 aCaptureOptions == StackCaptureOptions::NoStack) {
3448 return false;
3449 }
3450
3451 RegisteredThread* registeredThread =
3452 TLSRegisteredThread::RegisteredThread(lock);
3453 if (!registeredThread) {
3454 MOZ_ASSERT(registeredThread);
3455 return false;
3456 }
3457
3458 ProfileBuffer profileBuffer(aChunkedBuffer);
3459
3460 Registers regs;
3461 #if defined(HAVE_NATIVE_UNWIND)
3462 REGISTERS_SYNC_POPULATE(regs);
3463 #else
3464 regs.Clear();
3465 #endif
3466
3467 DoSyncSample(lock, *registeredThread, TimeStamp::Now(), regs, profileBuffer,
3468 aCaptureOptions);
3469
3470 return true;
3471 }
3472
3473 UniquePtr<ProfileChunkedBuffer> profiler_capture_backtrace() {
3474 MOZ_RELEASE_ASSERT(CorePS::Exists());
3475 AUTO_BASE_PROFILER_LABEL("baseprofiler::profiler_capture_backtrace",
3476 PROFILER);
3477
3478 // Quick is-active check before allocating a buffer.
3479 // If NoMarkerStacks is set, we don't want to capture a backtrace.
3480 if (!profiler_active_without_feature(ProfilerFeature::NoMarkerStacks)) {
3481 return nullptr;
3482 }
3483
3484 auto buffer = MakeUnique<ProfileChunkedBuffer>(
3485 ProfileChunkedBuffer::ThreadSafety::WithoutMutex,
3486 MakeUnique<ProfileBufferChunkManagerSingle>(
3487 ProfileBufferChunkManager::scExpectedMaximumStackSize));
3488
3489 if (!profiler_capture_backtrace_into(*buffer, StackCaptureOptions::Full)) {
3490 return nullptr;
3491 }
3492
3493 return buffer;
3494 }
3495
3496 UniqueProfilerBacktrace profiler_get_backtrace() {
3497 UniquePtr<ProfileChunkedBuffer> buffer = profiler_capture_backtrace();
3498
3499 if (!buffer) {
3500 return nullptr;
3501 }
3502
3503 return UniqueProfilerBacktrace(
3504 new ProfilerBacktrace("SyncProfile", std::move(buffer)));
3505 }
3506
3507 void ProfilerBacktraceDestructor::operator()(ProfilerBacktrace* aBacktrace) {
3508 delete aBacktrace;
3509 }
3510
3511 bool profiler_is_locked_on_current_thread() {
3512 // This function is used to help users avoid calling `profiler_...` functions
3513 // when the profiler may already have a lock in place, which would prevent a
3514 // 2nd recursive lock (resulting in a crash or a never-ending wait).
3515 // So we must return `true` for any of:
3516 // - The main profiler mutex, used by most functions, and/or
3517 // - The buffer mutex, used directly in some functions without locking the
3518 // main mutex, e.g., marker-related functions.
3519 return PSAutoLock::IsLockedOnCurrentThread() ||
3520 profiler_get_core_buffer().IsThreadSafeAndLockedOnCurrentThread();
3521 }
3522
3523 // This is a simplified version of profiler_add_marker that can be easily passed
3524 // into the JS engine.
3525 void profiler_add_js_marker(const char* aMarkerName, const char* aMarkerText) {
3526 BASE_PROFILER_MARKER_TEXT(
3527 ProfilerString8View::WrapNullTerminatedString(aMarkerName), JS, {},
3528 ProfilerString8View::WrapNullTerminatedString(aMarkerText));
3529 }
3530
3531 // NOTE: aCollector's methods will be called while the target thread is paused.
3532 // Doing things in those methods like allocating -- which may try to claim
3533 // locks -- is a surefire way to deadlock.
3534 void profiler_suspend_and_sample_thread(BaseProfilerThreadId aThreadId,
3535 uint32_t aFeatures,
3536 ProfilerStackCollector& aCollector,
3537 bool aSampleNative /* = true */) {
3538 const bool isSynchronous = [&aThreadId]() {
3539 const BaseProfilerThreadId currentThreadId = profiler_current_thread_id();
3540 if (!aThreadId.IsSpecified()) {
3541 aThreadId = currentThreadId;
3542 return true;
3543 }
3544 return aThreadId == currentThreadId;
3545 }();
3546
3547 // Lock the profiler mutex
3548 PSAutoLock lock;
3549
3550 const Vector<UniquePtr<RegisteredThread>>& registeredThreads =
3551 CorePS::RegisteredThreads(lock);
3552 for (auto& thread : registeredThreads) {
3553 RefPtr<ThreadInfo> info = thread->Info();
3554 RegisteredThread& registeredThread = *thread.get();
3555
3556 if (info->ThreadId() == aThreadId) {
3557 if (info->IsMainThread()) {
3558 aCollector.SetIsMainThread();
3559 }
3560
3561 // Allocate the space for the native stack
3562 NativeStack nativeStack;
3563
3564 auto collectStack = [&](const Registers& aRegs, const TimeStamp& aNow) {
3565 // The target thread is now suspended. Collect a native
3566 // backtrace, and call the callback.
3567 #if defined(HAVE_FASTINIT_NATIVE_UNWIND)
3568 if (aSampleNative) {
3569 // We can only use FramePointerStackWalk or MozStackWalk from
3570 // suspend_and_sample_thread as other stackwalking methods may not be
3571 // initialized.
3572 # if defined(USE_FRAME_POINTER_STACK_WALK)
3573 DoFramePointerBacktrace(lock, registeredThread, aRegs, nativeStack);
3574 # elif defined(USE_MOZ_STACK_WALK)
3575 DoMozStackWalkBacktrace(lock, registeredThread, aRegs, nativeStack);
3576 # else
3577 # error "Invalid configuration"
3578 # endif
3579
3580 MergeStacks(isSynchronous, registeredThread, nativeStack, aCollector);
3581 } else
3582 #endif
3583 {
3584 MergeStacks(isSynchronous, registeredThread, nativeStack, aCollector);
3585
3586 aCollector.CollectNativeLeafAddr((void*)aRegs.mPC);
3587 }
3588 };
3589
3590 if (isSynchronous) {
3591 // Sampling the current thread, do NOT suspend it!
3592 Registers regs;
3593 #if defined(HAVE_NATIVE_UNWIND)
3594 REGISTERS_SYNC_POPULATE(regs);
3595 #else
3596 regs.Clear();
3597 #endif
3598 collectStack(regs, TimeStamp::Now());
3599 } else {
3600 // Suspend, sample, and then resume the target thread.
3601 Sampler sampler(lock);
3602 TimeStamp now = TimeStamp::Now();
3603 sampler.SuspendAndSampleAndResumeThread(lock, registeredThread, now,
3604 collectStack);
3605
3606 // NOTE: Make sure to disable the sampler before it is destroyed, in
3607 // case the profiler is running at the same time.
3608 sampler.Disable(lock);
3609 }
3610 break;
3611 }
3612 }
3613 }
3614
3615 // END externally visible functions
3616 ////////////////////////////////////////////////////////////////////////
3617
3618 } // namespace baseprofiler
3619 } // namespace mozilla