Debian Codegraph @

mozglue/baseprofiler/core/ProfileBufferEntry.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 #include "ProfileBufferEntry.h"
8
9 #include <ostream>
10 #include <type_traits>
11
12 #include "mozilla/Logging.h"
13 #include "mozilla/ScopeExit.h"
14 #include "mozilla/Sprintf.h"
15 #include "mozilla/StackWalk.h"
16
17 #include "BaseProfiler.h"
18 #include "mozilla/BaseProfilerMarkers.h"
19 #include "platform.h"
20 #include "ProfileBuffer.h"
21 #include "ProfilerBacktrace.h"
22
23 namespace mozilla {
24 namespace baseprofiler {
25
26 ////////////////////////////////////////////////////////////////////////
27 // BEGIN ProfileBufferEntry
28
29 ProfileBufferEntry::ProfileBufferEntry()
30 : mKind(Kind::INVALID), mStorage{0, 0, 0, 0, 0, 0, 0, 0} {}
31
32 // aString must be a static string.
33 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, const char* aString)
34 : mKind(aKind) {
35 memcpy(mStorage, &aString, sizeof(aString));
36 }
37
38 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, char aChars[kNumChars])
39 : mKind(aKind) {
40 memcpy(mStorage, aChars, kNumChars);
41 }
42
43 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, void* aPtr) : mKind(aKind) {
44 memcpy(mStorage, &aPtr, sizeof(aPtr));
45 }
46
47 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, double aDouble)
48 : mKind(aKind) {
49 memcpy(mStorage, &aDouble, sizeof(aDouble));
50 }
51
52 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, int aInt) : mKind(aKind) {
53 memcpy(mStorage, &aInt, sizeof(aInt));
54 }
55
56 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, int64_t aInt64)
57 : mKind(aKind) {
58 memcpy(mStorage, &aInt64, sizeof(aInt64));
59 }
60
61 ProfileBufferEntry::ProfileBufferEntry(Kind aKind, uint64_t aUint64)
62 : mKind(aKind) {
63 memcpy(mStorage, &aUint64, sizeof(aUint64));
64 }
65
66 ProfileBufferEntry::ProfileBufferEntry(Kind aKind,
67 BaseProfilerThreadId aThreadId)
68 : mKind(aKind) {
69 static_assert(std::is_trivially_copyable_v<BaseProfilerThreadId>);
70 static_assert(sizeof(aThreadId) <= sizeof(mStorage));
71 memcpy(mStorage, &aThreadId, sizeof(aThreadId));
72 }
73
74 const char* ProfileBufferEntry::GetString() const {
75 const char* result;
76 memcpy(&result, mStorage, sizeof(result));
77 return result;
78 }
79
80 void* ProfileBufferEntry::GetPtr() const {
81 void* result;
82 memcpy(&result, mStorage, sizeof(result));
83 return result;
84 }
85
86 double ProfileBufferEntry::GetDouble() const {
87 double result;
88 memcpy(&result, mStorage, sizeof(result));
89 return result;
90 }
91
92 int ProfileBufferEntry::GetInt() const {
93 int result;
94 memcpy(&result, mStorage, sizeof(result));
95 return result;
96 }
97
98 int64_t ProfileBufferEntry::GetInt64() const {
99 int64_t result;
100 memcpy(&result, mStorage, sizeof(result));
101 return result;
102 }
103
104 uint64_t ProfileBufferEntry::GetUint64() const {
105 uint64_t result;
106 memcpy(&result, mStorage, sizeof(result));
107 return result;
108 }
109
110 BaseProfilerThreadId ProfileBufferEntry::GetThreadId() const {
111 BaseProfilerThreadId result;
112 static_assert(std::is_trivially_copyable_v<BaseProfilerThreadId>);
113 memcpy(&result, mStorage, sizeof(result));
114 return result;
115 }
116
117 void ProfileBufferEntry::CopyCharsInto(char (&aOutArray)[kNumChars]) const {
118 memcpy(aOutArray, mStorage, kNumChars);
119 }
120
121 // END ProfileBufferEntry
122 ////////////////////////////////////////////////////////////////////////
123
124 // As mentioned in ProfileBufferEntry.h, the JSON format contains many
125 // arrays whose elements are laid out according to various schemas to help
126 // de-duplication. This RAII class helps write these arrays by keeping track of
127 // the last non-null element written and adding the appropriate number of null
128 // elements when writing new non-null elements. It also automatically opens and
129 // closes an array element on the given JSON writer.
130 //
131 // You grant the AutoArraySchemaWriter exclusive access to the JSONWriter and
132 // the UniqueJSONStrings objects for the lifetime of AutoArraySchemaWriter. Do
133 // not access them independently while the AutoArraySchemaWriter is alive.
134 // If you need to add complex objects, call FreeFormElement(), which will give
135 // you temporary access to the writer.
136 //
137 // Example usage:
138 //
139 // // Define the schema of elements in this type of array: [FOO, BAR, BAZ]
140 // enum Schema : uint32_t {
141 // FOO = 0,
142 // BAR = 1,
143 // BAZ = 2
144 // };
145 //
146 // AutoArraySchemaWriter writer(someJsonWriter, someUniqueStrings);
147 // if (shouldWriteFoo) {
148 // writer.IntElement(FOO, getFoo());
149 // }
150 // ... etc ...
151 //
152 // The elements need to be added in-order.
153 class MOZ_RAII AutoArraySchemaWriter {
154 public:
155 explicit AutoArraySchemaWriter(SpliceableJSONWriter& aWriter)
156 : mJSONWriter(aWriter), mNextFreeIndex(0) {
157 mJSONWriter.StartArrayElement();
158 }
159
160 ~AutoArraySchemaWriter() { mJSONWriter.EndArray(); }
161
162 template <typename T>
163 void IntElement(uint32_t aIndex, T aValue) {
164 static_assert(!std::is_same_v<T, uint64_t>,
165 "Narrowing uint64 -> int64 conversion not allowed");
166 FillUpTo(aIndex);
167 mJSONWriter.IntElement(static_cast<int64_t>(aValue));
168 }
169
170 void DoubleElement(uint32_t aIndex, double aValue) {
171 FillUpTo(aIndex);
172 mJSONWriter.DoubleElement(aValue);
173 }
174
175 void TimeMsElement(uint32_t aIndex, double aTime_ms) {
176 FillUpTo(aIndex);
177 mJSONWriter.TimeDoubleMsElement(aTime_ms);
178 }
179
180 void BoolElement(uint32_t aIndex, bool aValue) {
181 FillUpTo(aIndex);
182 mJSONWriter.BoolElement(aValue);
183 }
184
185 protected:
186 SpliceableJSONWriter& Writer() { return mJSONWriter; }
187
188 void FillUpTo(uint32_t aIndex) {
189 MOZ_ASSERT(aIndex >= mNextFreeIndex);
190 mJSONWriter.NullElements(aIndex - mNextFreeIndex);
191 mNextFreeIndex = aIndex + 1;
192 }
193
194 private:
195 SpliceableJSONWriter& mJSONWriter;
196 uint32_t mNextFreeIndex;
197 };
198
199 // Same as AutoArraySchemaWriter, but this can also write strings (output as
200 // indexes into the table of unique strings).
201 class MOZ_RAII AutoArraySchemaWithStringsWriter : public AutoArraySchemaWriter {
202 public:
203 AutoArraySchemaWithStringsWriter(SpliceableJSONWriter& aWriter,
204 UniqueJSONStrings& aStrings)
205 : AutoArraySchemaWriter(aWriter), mStrings(aStrings) {}
206
207 void StringElement(uint32_t aIndex, const Span<const char>& aValue) {
208 FillUpTo(aIndex);
209 mStrings.WriteElement(Writer(), aValue);
210 }
211
212 private:
213 UniqueJSONStrings& mStrings;
214 };
215
216 UniqueStacks::StackKey UniqueStacks::BeginStack(const FrameKey& aFrame) {
217 return StackKey(GetOrAddFrameIndex(aFrame));
218 }
219
220 UniqueStacks::StackKey UniqueStacks::AppendFrame(const StackKey& aStack,
221 const FrameKey& aFrame) {
222 return StackKey(aStack, GetOrAddStackIndex(aStack),
223 GetOrAddFrameIndex(aFrame));
224 }
225
226 bool UniqueStacks::FrameKey::NormalFrameData::operator==(
227 const NormalFrameData& aOther) const {
228 return mLocation == aOther.mLocation &&
229 mRelevantForJS == aOther.mRelevantForJS &&
230 mInnerWindowID == aOther.mInnerWindowID && mLine == aOther.mLine &&
231 mColumn == aOther.mColumn && mCategoryPair == aOther.mCategoryPair;
232 }
233
234 UniqueStacks::UniqueStacks()
235 : mUniqueStrings(MakeUnique<UniqueJSONStrings>(
236 FailureLatchInfallibleSource::Singleton())),
237 mFrameTableWriter(FailureLatchInfallibleSource::Singleton()),
238 mStackTableWriter(FailureLatchInfallibleSource::Singleton()) {
239 mFrameTableWriter.StartBareList();
240 mStackTableWriter.StartBareList();
241 }
242
243 uint32_t UniqueStacks::GetOrAddStackIndex(const StackKey& aStack) {
244 uint32_t count = mStackToIndexMap.count();
245 auto entry = mStackToIndexMap.lookupForAdd(aStack);
246 if (entry) {
247 MOZ_ASSERT(entry->value() < count);
248 return entry->value();
249 }
250
251 MOZ_RELEASE_ASSERT(mStackToIndexMap.add(entry, aStack, count));
252 StreamStack(aStack);
253 return count;
254 }
255
256 uint32_t UniqueStacks::GetOrAddFrameIndex(const FrameKey& aFrame) {
257 uint32_t count = mFrameToIndexMap.count();
258 auto entry = mFrameToIndexMap.lookupForAdd(aFrame);
259 if (entry) {
260 MOZ_ASSERT(entry->value() < count);
261 return entry->value();
262 }
263
264 MOZ_RELEASE_ASSERT(mFrameToIndexMap.add(entry, aFrame, count));
265 StreamNonJITFrame(aFrame);
266 return count;
267 }
268
269 void UniqueStacks::SpliceFrameTableElements(SpliceableJSONWriter& aWriter) {
270 mFrameTableWriter.EndBareList();
271 aWriter.TakeAndSplice(mFrameTableWriter.TakeChunkedWriteFunc());
272 }
273
274 void UniqueStacks::SpliceStackTableElements(SpliceableJSONWriter& aWriter) {
275 mStackTableWriter.EndBareList();
276 aWriter.TakeAndSplice(mStackTableWriter.TakeChunkedWriteFunc());
277 }
278
279 void UniqueStacks::StreamStack(const StackKey& aStack) {
280 enum Schema : uint32_t { PREFIX = 0, FRAME = 1 };
281
282 AutoArraySchemaWriter writer(mStackTableWriter);
283 if (aStack.mPrefixStackIndex.isSome()) {
284 writer.IntElement(PREFIX, *aStack.mPrefixStackIndex);
285 }
286 writer.IntElement(FRAME, aStack.mFrameIndex);
287 }
288
289 void UniqueStacks::StreamNonJITFrame(const FrameKey& aFrame) {
290 using NormalFrameData = FrameKey::NormalFrameData;
291
292 enum Schema : uint32_t {
293 LOCATION = 0,
294 RELEVANT_FOR_JS = 1,
295 INNER_WINDOW_ID = 2,
296 IMPLEMENTATION = 3,
297 LINE = 4,
298 COLUMN = 5,
299 CATEGORY = 6,
300 SUBCATEGORY = 7
301 };
302
303 AutoArraySchemaWithStringsWriter writer(mFrameTableWriter, *mUniqueStrings);
304
305 const NormalFrameData& data = aFrame.mData.as<NormalFrameData>();
306 writer.StringElement(LOCATION, data.mLocation);
307 writer.BoolElement(RELEVANT_FOR_JS, data.mRelevantForJS);
308
309 // It's okay to convert uint64_t to double here because DOM always creates IDs
310 // that are convertible to double.
311 writer.DoubleElement(INNER_WINDOW_ID, data.mInnerWindowID);
312
313 if (data.mLine.isSome()) {
314 writer.IntElement(LINE, *data.mLine);
315 }
316 if (data.mColumn.isSome()) {
317 writer.IntElement(COLUMN, *data.mColumn);
318 }
319 if (data.mCategoryPair.isSome()) {
320 const ProfilingCategoryPairInfo& info =
321 GetProfilingCategoryPairInfo(*data.mCategoryPair);
322 writer.IntElement(CATEGORY, uint32_t(info.mCategory));
323 writer.IntElement(SUBCATEGORY, info.mSubcategoryIndex);
324 }
325 }
326
327 struct ProfileSample {
328 uint32_t mStack;
329 double mTime;
330 Maybe<double> mResponsiveness;
331 };
332
333 static void WriteSample(SpliceableJSONWriter& aWriter,
334 const ProfileSample& aSample) {
335 enum Schema : uint32_t {
336 STACK = 0,
337 TIME = 1,
338 EVENT_DELAY = 2,
339 };
340
341 AutoArraySchemaWriter writer(aWriter);
342
343 writer.IntElement(STACK, aSample.mStack);
344
345 writer.TimeMsElement(TIME, aSample.mTime);
346
347 if (aSample.mResponsiveness.isSome()) {
348 writer.DoubleElement(EVENT_DELAY, *aSample.mResponsiveness);
349 }
350 }
351
352 class EntryGetter {
353 public:
354 explicit EntryGetter(ProfileChunkedBuffer::Reader& aReader,
355 uint64_t aInitialReadPos = 0)
356 : mBlockIt(
357 aReader.At(ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
358 aInitialReadPos))),
359 mBlockItEnd(aReader.end()) {
360 if (!ReadLegacyOrEnd()) {
361 // Find and read the next non-legacy entry.
362 Next();
363 }
364 }
365
366 bool Has() const { return mBlockIt != mBlockItEnd; }
367
368 const ProfileBufferEntry& Get() const {
369 MOZ_ASSERT(Has(), "Caller should have checked `Has()` before `Get()`");
370 return mEntry;
371 }
372
373 void Next() {
374 MOZ_ASSERT(Has(), "Caller should have checked `Has()` before `Next()`");
375 for (;;) {
376 ++mBlockIt;
377 if (ReadLegacyOrEnd()) {
378 // Either we're at the end, or we could read a legacy entry -> Done.
379 break;
380 }
381 // Otherwise loop around until we hit the end or a legacy entry.
382 }
383 }
384
385 ProfileBufferBlockIndex CurBlockIndex() const {
386 return mBlockIt.CurrentBlockIndex();
387 }
388
389 uint64_t CurPos() const {
390 return CurBlockIndex().ConvertToProfileBufferIndex();
391 }
392
393 private:
394 // Try to read the entry at the current `mBlockIt` position.
395 // * If we're at the end of the buffer, just return `true`.
396 // * If there is a "legacy" entry (containing a real `ProfileBufferEntry`),
397 // read it into `mEntry`, and return `true` as well.
398 // * Otherwise the entry contains a "modern" type that cannot be read into
399 // `mEntry`, return `false` (so `EntryGetter` can skip to another entry).
400 bool ReadLegacyOrEnd() {
401 if (!Has()) {
402 return true;
403 }
404 // Read the entry "kind", which is always at the start of all entries.
405 ProfileBufferEntryReader aER = *mBlockIt;
406 auto type = static_cast<ProfileBufferEntry::Kind>(
407 aER.ReadObject<ProfileBufferEntry::KindUnderlyingType>());
408 MOZ_ASSERT(static_cast<ProfileBufferEntry::KindUnderlyingType>(type) <
409 static_cast<ProfileBufferEntry::KindUnderlyingType>(
410 ProfileBufferEntry::Kind::MODERN_LIMIT));
411 if (type >= ProfileBufferEntry::Kind::LEGACY_LIMIT) {
412 aER.SetRemainingBytes(0);
413 return false;
414 }
415 // Here, we have a legacy item, we need to read it from the start.
416 // Because the above `ReadObject` moved the reader, we ned to reset it to
417 // the start of the entry before reading the whole entry.
418 aER = *mBlockIt;
419 aER.ReadBytes(&mEntry, aER.RemainingBytes());
420 return true;
421 }
422
423 ProfileBufferEntry mEntry;
424 ProfileChunkedBuffer::BlockIterator mBlockIt;
425 const ProfileChunkedBuffer::BlockIterator mBlockItEnd;
426 };
427
428 // The following grammar shows legal sequences of profile buffer entries.
429 // The sequences beginning with a ThreadId entry are known as "samples".
430 //
431 // (
432 // ( /* Samples */
433 // ThreadId
434 // Time
435 // ( NativeLeafAddr
436 // | Label FrameFlags? DynamicStringFragment* LineNumber? CategoryPair?
437 // | JitReturnAddr
438 // )+
439 // Responsiveness?
440 // )
441 // | MarkerData
442 // | ( /* Counters */
443 // CounterId
444 // Time
445 // (
446 // CounterKey
447 // Count
448 // Number?
449 // )*
450 // )
451 // | CollectionStart
452 // | CollectionEnd
453 // | Pause
454 // | Resume
455 // | ( ProfilerOverheadTime /* Sampling start timestamp */
456 // ProfilerOverheadDuration /* Lock acquisition */
457 // ProfilerOverheadDuration /* Expired data cleaning */
458 // ProfilerOverheadDuration /* Counters */
459 // ProfilerOverheadDuration /* Threads */
460 // )
461 // )*
462 //
463 // The most complicated part is the stack entry sequence that begins with
464 // Label. Here are some examples.
465 //
466 // - ProfilingStack frames without a dynamic string:
467 //
468 // Label("js::RunScript")
469 // CategoryPair(ProfilingCategoryPair::JS)
470 //
471 // Label("XREMain::XRE_main")
472 // LineNumber(4660)
473 // CategoryPair(ProfilingCategoryPair::OTHER)
474 //
475 // Label("ElementRestyler::ComputeStyleChangeFor")
476 // LineNumber(3003)
477 // CategoryPair(ProfilingCategoryPair::CSS)
478 //
479 // - ProfilingStack frames with a dynamic string:
480 //
481 // Label("nsObserverService::NotifyObservers")
482 // FrameFlags(uint64_t(ProfilingStackFrame::Flags::IS_LABEL_FRAME))
483 // DynamicStringFragment("domwindo")
484 // DynamicStringFragment("wopened")
485 // LineNumber(291)
486 // CategoryPair(ProfilingCategoryPair::OTHER)
487 //
488 // Label("")
489 // FrameFlags(uint64_t(ProfilingStackFrame::Flags::IS_JS_FRAME))
490 // DynamicStringFragment("closeWin")
491 // DynamicStringFragment("dow (chr")
492 // DynamicStringFragment("ome://gl")
493 // DynamicStringFragment("obal/con")
494 // DynamicStringFragment("tent/glo")
495 // DynamicStringFragment("balOverl")
496 // DynamicStringFragment("ay.js:5)")
497 // DynamicStringFragment("") # this string holds the closing '\0'
498 // LineNumber(25)
499 // CategoryPair(ProfilingCategoryPair::JS)
500 //
501 // Label("")
502 // FrameFlags(uint64_t(ProfilingStackFrame::Flags::IS_JS_FRAME))
503 // DynamicStringFragment("bound (s")
504 // DynamicStringFragment("elf-host")
505 // DynamicStringFragment("ed:914)")
506 // LineNumber(945)
507 // CategoryPair(ProfilingCategoryPair::JS)
508 //
509 // - A profiling stack frame with an overly long dynamic string:
510 //
511 // Label("")
512 // FrameFlags(uint64_t(ProfilingStackFrame::Flags::IS_LABEL_FRAME))
513 // DynamicStringFragment("(too lon")
514 // DynamicStringFragment("g)")
515 // LineNumber(100)
516 // CategoryPair(ProfilingCategoryPair::NETWORK)
517 //
518 // - A wasm JIT frame:
519 //
520 // Label("")
521 // FrameFlags(uint64_t(0))
522 // DynamicStringFragment("wasm-fun")
523 // DynamicStringFragment("ction[87")
524 // DynamicStringFragment("36] (blo")
525 // DynamicStringFragment("b:http:/")
526 // DynamicStringFragment("/webasse")
527 // DynamicStringFragment("mbly.org")
528 // DynamicStringFragment("/3dc5759")
529 // DynamicStringFragment("4-ce58-4")
530 // DynamicStringFragment("626-975b")
531 // DynamicStringFragment("-08ad116")
532 // DynamicStringFragment("30bc1:38")
533 // DynamicStringFragment("29856)")
534 //
535 // - A JS frame in a synchronous sample:
536 //
537 // Label("")
538 // FrameFlags(uint64_t(ProfilingStackFrame::Flags::IS_LABEL_FRAME))
539 // DynamicStringFragment("u (https")
540 // DynamicStringFragment("://perf-")
541 // DynamicStringFragment("html.io/")
542 // DynamicStringFragment("ac0da204")
543 // DynamicStringFragment("aaa44d75")
544 // DynamicStringFragment("a800.bun")
545 // DynamicStringFragment("dle.js:2")
546 // DynamicStringFragment("5)")
547
548 // Because this is a format entirely internal to the Profiler, any parsing
549 // error indicates a bug in the ProfileBuffer writing or the parser itself,
550 // or possibly flaky hardware.
551 #define ERROR_AND_CONTINUE(msg) \
552 { \
553 fprintf(stderr, "ProfileBuffer parse error: %s", msg); \
554 MOZ_ASSERT(false, msg); \
555 continue; \
556 }
557
558 BaseProfilerThreadId ProfileBuffer::StreamSamplesToJSON(
559 SpliceableJSONWriter& aWriter, BaseProfilerThreadId aThreadId,
560 double aSinceTime, UniqueStacks& aUniqueStacks) const {
561 UniquePtr<char[]> dynStrBuf = MakeUnique<char[]>(kMaxFrameKeyLength);
562
563 return mEntries.Read([&](ProfileChunkedBuffer::Reader* aReader) {
564 MOZ_ASSERT(aReader,
565 "ProfileChunkedBuffer cannot be out-of-session when sampler is "
566 "running");
567
568 BaseProfilerThreadId processedThreadId;
569
570 EntryGetter e(*aReader);
571
572 for (;;) {
573 // This block skips entries until we find the start of the next sample.
574 // This is useful in three situations.
575 //
576 // - The circular buffer overwrites old entries, so when we start parsing
577 // we might be in the middle of a sample, and we must skip forward to
578 // the start of the next sample.
579 //
580 // - We skip samples that don't have an appropriate ThreadId or Time.
581 //
582 // - We skip range Pause, Resume, CollectionStart, Counter and
583 // CollectionEnd entries between samples.
584 while (e.Has()) {
585 if (e.Get().IsThreadId()) {
586 break;
587 }
588 e.Next();
589 }
590
591 if (!e.Has()) {
592 break;
593 }
594
595 // Due to the skip_to_next_sample block above, if we have an entry here it
596 // must be a ThreadId entry.
597 MOZ_ASSERT(e.Get().IsThreadId());
598
599 BaseProfilerThreadId threadId = e.Get().GetThreadId();
600 e.Next();
601
602 // Ignore samples that are for the wrong thread.
603 if (threadId != aThreadId && aThreadId.IsSpecified()) {
604 continue;
605 }
606
607 MOZ_ASSERT(
608 aThreadId.IsSpecified() || !processedThreadId.IsSpecified(),
609 "Unspecified aThreadId should only be used with 1-sample buffer");
610
611 ProfileSample sample;
612
613 if (e.Has() && e.Get().IsTime()) {
614 sample.mTime = e.Get().GetDouble();
615 e.Next();
616
617 // Ignore samples that are too old.
618 if (sample.mTime < aSinceTime) {
619 continue;
620 }
621 } else {
622 ERROR_AND_CONTINUE("expected a Time entry");
623 }
624
625 UniqueStacks::StackKey stack =
626 aUniqueStacks.BeginStack(UniqueStacks::FrameKey("(root)"));
627
628 int numFrames = 0;
629 while (e.Has()) {
630 if (e.Get().IsNativeLeafAddr()) {
631 numFrames++;
632
633 void* pc = e.Get().GetPtr();
634 e.Next();
635
636 static const uint32_t BUF_SIZE = 256;
637 char buf[BUF_SIZE];
638
639 // Bug 753041: We need a double cast here to tell GCC that we don't
640 // want to sign extend 32-bit addresses starting with 0xFXXXXXX.
641 unsigned long long pcULL = (unsigned long long)(uintptr_t)pc;
642 SprintfLiteral(buf, "0x%llx", pcULL);
643
644 // If the "MOZ_PROFILER_SYMBOLICATE" env-var is set, we add a local
645 // symbolication description to the PC address. This is off by
646 // default, and mainly intended for local development.
647 static const bool preSymbolicate = []() {
648 const char* symbolicate = getenv("MOZ_PROFILER_SYMBOLICATE");
649 return symbolicate && symbolicate[0] != '\0';
650 }();
651 if (preSymbolicate) {
652 MozCodeAddressDetails details;
653 if (MozDescribeCodeAddress(pc, &details)) {
654 // Replace \0 terminator with space.
655 const uint32_t pcLen = strlen(buf);
656 buf[pcLen] = ' ';
657 // Add description after space. Note: Using a frame number of 0,
658 // as using `numFrames` wouldn't help here, and would prevent
659 // combining same function calls that happen at different depths.
660 // TODO: Remove unsightly "#00: " if too annoying. :-)
661 MozFormatCodeAddressDetails(
662 buf + pcLen + 1, BUF_SIZE - (pcLen + 1), 0, pc, &details);
663 }
664 }
665
666 stack = aUniqueStacks.AppendFrame(stack, UniqueStacks::FrameKey(buf));
667
668 } else if (e.Get().IsLabel()) {
669 numFrames++;
670
671 const char* label = e.Get().GetString();
672 e.Next();
673
674 using FrameFlags = ProfilingStackFrame::Flags;
675 uint32_t frameFlags = 0;
676 if (e.Has() && e.Get().IsFrameFlags()) {
677 frameFlags = uint32_t(e.Get().GetUint64());
678 e.Next();
679 }
680
681 bool relevantForJS =
682 frameFlags & uint32_t(FrameFlags::RELEVANT_FOR_JS);
683
684 // Copy potential dynamic string fragments into dynStrBuf, so that
685 // dynStrBuf will then contain the entire dynamic string.
686 size_t i = 0;
687 dynStrBuf[0] = '\0';
688 while (e.Has()) {
689 if (e.Get().IsDynamicStringFragment()) {
690 char chars[ProfileBufferEntry::kNumChars];
691 e.Get().CopyCharsInto(chars);
692 for (char c : chars) {
693 if (i < kMaxFrameKeyLength) {
694 dynStrBuf[i] = c;
695 i++;
696 }
697 }
698 e.Next();
699 } else {
700 break;
701 }
702 }
703 dynStrBuf[kMaxFrameKeyLength - 1] = '\0';
704 bool hasDynamicString = (i != 0);
705
706 std::string frameLabel;
707 if (label[0] != '\0' && hasDynamicString) {
708 if (frameFlags & uint32_t(FrameFlags::STRING_TEMPLATE_METHOD)) {
709 frameLabel += label;
710 frameLabel += '.';
711 frameLabel += dynStrBuf.get();
712 } else if (frameFlags &
713 uint32_t(FrameFlags::STRING_TEMPLATE_GETTER)) {
714 frameLabel += "get ";
715 frameLabel += label;
716 frameLabel += '.';
717 frameLabel += dynStrBuf.get();
718 } else if (frameFlags &
719 uint32_t(FrameFlags::STRING_TEMPLATE_SETTER)) {
720 frameLabel += "set ";
721 frameLabel += label;
722 frameLabel += '.';
723 frameLabel += dynStrBuf.get();
724 } else {
725 frameLabel += label;
726 frameLabel += ' ';
727 frameLabel += dynStrBuf.get();
728 }
729 } else if (hasDynamicString) {
730 frameLabel += dynStrBuf.get();
731 } else {
732 frameLabel += label;
733 }
734
735 uint64_t innerWindowID = 0;
736 if (e.Has() && e.Get().IsInnerWindowID()) {
737 innerWindowID = uint64_t(e.Get().GetUint64());
738 e.Next();
739 }
740
741 Maybe<unsigned> line;
742 if (e.Has() && e.Get().IsLineNumber()) {
743 line = Some(unsigned(e.Get().GetInt()));
744 e.Next();
745 }
746
747 Maybe<unsigned> column;
748 if (e.Has() && e.Get().IsColumnNumber()) {
749 column = Some(unsigned(e.Get().GetInt()));
750 e.Next();
751 }
752
753 Maybe<ProfilingCategoryPair> categoryPair;
754 if (e.Has() && e.Get().IsCategoryPair()) {
755 categoryPair =
756 Some(ProfilingCategoryPair(uint32_t(e.Get().GetInt())));
757 e.Next();
758 }
759
760 stack = aUniqueStacks.AppendFrame(
761 stack, UniqueStacks::FrameKey(std::move(frameLabel),
762 relevantForJS, innerWindowID, line,
763 column, categoryPair));
764
765 } else {
766 break;
767 }
768 }
769
770 if (numFrames == 0) {
771 // It is possible to have empty stacks if native stackwalking is
772 // disabled. Skip samples with empty stacks. (See Bug 1497985).
773 // Thus, don't use ERROR_AND_CONTINUE, but just continue.
774 continue;
775 }
776
777 sample.mStack = aUniqueStacks.GetOrAddStackIndex(stack);
778
779 if (e.Has() && e.Get().IsResponsiveness()) {
780 sample.mResponsiveness = Some(e.Get().GetDouble());
781 e.Next();
782 }
783
784 WriteSample(aWriter, sample);
785
786 processedThreadId = threadId;
787 }
788
789 return processedThreadId;
790 });
791 }
792
793 void ProfileBuffer::StreamMarkersToJSON(SpliceableJSONWriter& aWriter,
794 BaseProfilerThreadId aThreadId,
795 const TimeStamp& aProcessStartTime,
796 double aSinceTime,
797 UniqueStacks& aUniqueStacks) const {
798 mEntries.ReadEach([&](ProfileBufferEntryReader& aER) {
799 auto type = static_cast<ProfileBufferEntry::Kind>(
800 aER.ReadObject<ProfileBufferEntry::KindUnderlyingType>());
801 MOZ_ASSERT(static_cast<ProfileBufferEntry::KindUnderlyingType>(type) <
802 static_cast<ProfileBufferEntry::KindUnderlyingType>(
803 ProfileBufferEntry::Kind::MODERN_LIMIT));
804 if (type == ProfileBufferEntry::Kind::Marker) {
805 ::mozilla::base_profiler_markers_detail::DeserializeAfterKindAndStream(
806 aER,
807 [&](const BaseProfilerThreadId& aMarkerThreadId) {
808 return (aMarkerThreadId == aThreadId) ? &aWriter : nullptr;
809 },
810 [&](ProfileChunkedBuffer& aChunkedBuffer) {
811 ProfilerBacktrace backtrace("", &aChunkedBuffer);
812 backtrace.StreamJSON(aWriter, TimeStamp::ProcessCreation(),
813 aUniqueStacks);
814 },
815 // We don't have Rust markers in the mozglue.
816 [&](mozilla::base_profiler_markers_detail::Streaming::
817 DeserializerTag) {
818 MOZ_ASSERT_UNREACHABLE("No Rust markers in mozglue.");
819 });
820 } else {
821 // The entry was not a marker, we need to skip to the end.
822 aER.SetRemainingBytes(0);
823 }
824 });
825 }
826
827 void ProfileBuffer::StreamProfilerOverheadToJSON(
828 SpliceableJSONWriter& aWriter, const TimeStamp& aProcessStartTime,
829 double aSinceTime) const {
830 const char* recordOverheads = getenv("MOZ_PROFILER_RECORD_OVERHEADS");
831 if (!recordOverheads || recordOverheads[0] == '\0') {
832 // Overheads were not recorded, return early.
833 return;
834 }
835
836 mEntries.Read([&](ProfileChunkedBuffer::Reader* aReader) {
837 MOZ_ASSERT(aReader,
838 "ProfileChunkedBuffer cannot be out-of-session when sampler is "
839 "running");
840
841 EntryGetter e(*aReader);
842
843 enum Schema : uint32_t {
844 TIME = 0,
845 LOCKING = 1,
846 MARKER_CLEANING = 2,
847 COUNTERS = 3,
848 THREADS = 4
849 };
850
851 aWriter.StartObjectProperty("profilerOverhead");
852 aWriter.StartObjectProperty("samples");
853 // Stream all sampling overhead data. We skip other entries, because we
854 // process them in StreamSamplesToJSON()/etc.
855 {
856 JSONSchemaWriter schema(aWriter);
857 schema.WriteField("time");
858 schema.WriteField("locking");
859 schema.WriteField("expiredMarkerCleaning");
860 schema.WriteField("counters");
861 schema.WriteField("threads");
862 }
863
864 aWriter.StartArrayProperty("data");
865 double firstTime = 0.0;
866 double lastTime = 0.0;
867 ProfilerStats intervals, overheads, lockings, cleanings, counters, threads;
868 while (e.Has()) {
869 // valid sequence: ProfilerOverheadTime, ProfilerOverheadDuration * 4
870 if (e.Get().IsProfilerOverheadTime()) {
871 double time = e.Get().GetDouble();
872 if (time >= aSinceTime) {
873 e.Next();
874 if (!e.Has() || !e.Get().IsProfilerOverheadDuration()) {
875 ERROR_AND_CONTINUE(
876 "expected a ProfilerOverheadDuration entry after "
877 "ProfilerOverheadTime");
878 }
879 double locking = e.Get().GetDouble();
880 e.Next();
881 if (!e.Has() || !e.Get().IsProfilerOverheadDuration()) {
882 ERROR_AND_CONTINUE(
883 "expected a ProfilerOverheadDuration entry after "
884 "ProfilerOverheadTime,ProfilerOverheadDuration");
885 }
886 double cleaning = e.Get().GetDouble();
887 e.Next();
888 if (!e.Has() || !e.Get().IsProfilerOverheadDuration()) {
889 ERROR_AND_CONTINUE(
890 "expected a ProfilerOverheadDuration entry after "
891 "ProfilerOverheadTime,ProfilerOverheadDuration*2");
892 }
893 double counter = e.Get().GetDouble();
894 e.Next();
895 if (!e.Has() || !e.Get().IsProfilerOverheadDuration()) {
896 ERROR_AND_CONTINUE(
897 "expected a ProfilerOverheadDuration entry after "
898 "ProfilerOverheadTime,ProfilerOverheadDuration*3");
899 }
900 double thread = e.Get().GetDouble();
901
902 if (firstTime == 0.0) {
903 firstTime = time;
904 } else {
905 // Note that we'll have 1 fewer interval than other numbers (because
906 // we need both ends of an interval to know its duration). The final
907 // difference should be insignificant over the expected many
908 // thousands of iterations.
909 intervals.Count(time - lastTime);
910 }
911 lastTime = time;
912 overheads.Count(locking + cleaning + counter + thread);
913 lockings.Count(locking);
914 cleanings.Count(cleaning);
915 counters.Count(counter);
916 threads.Count(thread);
917
918 AutoArraySchemaWriter writer(aWriter);
919 writer.TimeMsElement(TIME, time);
920 writer.DoubleElement(LOCKING, locking);
921 writer.DoubleElement(MARKER_CLEANING, cleaning);
922 writer.DoubleElement(COUNTERS, counter);
923 writer.DoubleElement(THREADS, thread);
924 }
925 }
926 e.Next();
927 }
928 aWriter.EndArray(); // data
929 aWriter.EndObject(); // samples
930
931 // Only output statistics if there is at least one full interval (and
932 // therefore at least two samplings.)
933 if (intervals.n > 0) {
934 aWriter.StartObjectProperty("statistics");
935 aWriter.DoubleProperty("profiledDuration", lastTime - firstTime);
936 aWriter.IntProperty("samplingCount", overheads.n);
937 aWriter.DoubleProperty("overheadDurations", overheads.sum);
938 aWriter.DoubleProperty("overheadPercentage",
939 overheads.sum / (lastTime - firstTime));
940 #define PROFILER_STATS(name, var) \
941 aWriter.DoubleProperty("mean" name, (var).sum / (var).n); \
942 aWriter.DoubleProperty("min" name, (var).min); \
943 aWriter.DoubleProperty("max" name, (var).max);
944 PROFILER_STATS("Interval", intervals);
945 PROFILER_STATS("Overhead", overheads);
946 PROFILER_STATS("Lockings", lockings);
947 PROFILER_STATS("Cleaning", cleanings);
948 PROFILER_STATS("Counter", counters);
949 PROFILER_STATS("Thread", threads);
950 #undef PROFILER_STATS
951 aWriter.EndObject(); // statistics
952 }
953 aWriter.EndObject(); // profilerOverhead
954 });
955 }
956
957 struct CounterSample {
958 double mTime;
959 uint64_t mNumber;
960 int64_t mCount;
961 };
962
963 using CounterSamples = Vector<CounterSample>;
964
965 // HashMap lookup, if not found, a default value is inserted.
966 // Returns reference to (existing or new) value inside the HashMap.
967 template <typename HashM, typename Key>
968 static auto& LookupOrAdd(HashM& aMap, Key&& aKey) {
969 auto addPtr = aMap.lookupForAdd(aKey);
970 if (!addPtr) {
971 MOZ_RELEASE_ASSERT(aMap.add(addPtr, std::forward<Key>(aKey),
972 typename HashM::Entry::ValueType{}));
973 MOZ_ASSERT(!!addPtr);
974 }
975 return addPtr->value();
976 }
977
978 void ProfileBuffer::StreamCountersToJSON(SpliceableJSONWriter& aWriter,
979 const TimeStamp& aProcessStartTime,
980 double aSinceTime) const {
981 // Because this is a format entirely internal to the Profiler, any parsing
982 // error indicates a bug in the ProfileBuffer writing or the parser itself,
983 // or possibly flaky hardware.
984
985 mEntries.Read([&](ProfileChunkedBuffer::Reader* aReader) {
986 MOZ_ASSERT(aReader,
987 "ProfileChunkedBuffer cannot be out-of-session when sampler is "
988 "running");
989
990 EntryGetter e(*aReader);
991
992 enum Schema : uint32_t { TIME = 0, COUNT = 1, NUMBER = 2 };
993
994 // Stream all counters. We skip other entries, because we process them in
995 // StreamSamplesToJSON()/etc.
996 //
997 // Valid sequence in the buffer:
998 // CounterID
999 // Time
1000 // ( Count Number? )*
1001 //
1002 // And the JSON (example):
1003 // "counters": {
1004 // "name": "malloc",
1005 // "category": "Memory",
1006 // "description": "Amount of allocated memory",
1007 // "samples": {
1008 // "schema": {"time": 0, "count": 1, "number": 2},
1009 // "data": [
1010 // [
1011 // 16117.033968000002,
1012 // 2446216,
1013 // 6801320
1014 // ],
1015 // [
1016 // 16118.037638,
1017 // 2446216,
1018 // 6801320
1019 // ],
1020 // ],
1021 // },
1022 // }
1023
1024 // Build the map of counters and populate it
1025 HashMap<void*, CounterSamples> counters;
1026
1027 while (e.Has()) {
1028 // skip all non-Counters, including if we start in the middle of a counter
1029 if (e.Get().IsCounterId()) {
1030 void* id = e.Get().GetPtr();
1031 CounterSamples& data = LookupOrAdd(counters, id);
1032 e.Next();
1033 if (!e.Has() || !e.Get().IsTime()) {
1034 ERROR_AND_CONTINUE("expected a Time entry");
1035 }
1036 double time = e.Get().GetDouble();
1037 e.Next();
1038 if (time >= aSinceTime) {
1039 if (!e.Has() || !e.Get().IsCount()) {
1040 ERROR_AND_CONTINUE("expected a Count entry");
1041 }
1042 int64_t count = e.Get().GetUint64();
1043 e.Next();
1044 uint64_t number;
1045 if (!e.Has() || !e.Get().IsNumber()) {
1046 number = 0;
1047 } else {
1048 number = e.Get().GetInt64();
1049 e.Next();
1050 }
1051 CounterSample sample = {time, number, count};
1052 MOZ_RELEASE_ASSERT(data.append(sample));
1053 } else {
1054 // skip counter sample - only need to skip the initial counter
1055 // id, then let the loop at the top skip the rest
1056 }
1057 } else {
1058 e.Next();
1059 }
1060 }
1061 // we have a map of counter entries; dump them to JSON
1062 if (counters.count() == 0) {
1063 return;
1064 }
1065
1066 aWriter.StartArrayProperty("counters");
1067 for (auto iter = counters.iter(); !iter.done(); iter.next()) {
1068 CounterSamples& samples = iter.get().value();
1069 size_t size = samples.length();
1070 if (size == 0) {
1071 continue;
1072 }
1073 const BaseProfilerCount* base_counter =
1074 static_cast<const BaseProfilerCount*>(iter.get().key());
1075
1076 aWriter.Start();
1077 aWriter.StringProperty("name", MakeStringSpan(base_counter->mLabel));
1078 aWriter.StringProperty("category",
1079 MakeStringSpan(base_counter->mCategory));
1080 aWriter.StringProperty("description",
1081 MakeStringSpan(base_counter->mDescription));
1082
1083 bool hasNumber = false;
1084 for (size_t i = 0; i < size; i++) {
1085 if (samples[i].mNumber != 0) {
1086 hasNumber = true;
1087 break;
1088 }
1089 }
1090
1091 aWriter.StartObjectProperty("samples");
1092 {
1093 JSONSchemaWriter schema(aWriter);
1094 schema.WriteField("time");
1095 schema.WriteField("count");
1096 if (hasNumber) {
1097 schema.WriteField("number");
1098 }
1099 }
1100
1101 aWriter.StartArrayProperty("data");
1102 uint64_t previousNumber = 0;
1103 int64_t previousCount = 0;
1104 for (size_t i = 0; i < size; i++) {
1105 // Encode as deltas, and only encode if different than the last
1106 // sample
1107 if (i == 0 || samples[i].mNumber != previousNumber ||
1108 samples[i].mCount != previousCount) {
1109 MOZ_ASSERT(i == 0 || samples[i].mTime >= samples[i - 1].mTime);
1110 MOZ_ASSERT(samples[i].mNumber >= previousNumber);
1111 MOZ_ASSERT(samples[i].mNumber - previousNumber <=
1112 uint64_t(std::numeric_limits<int64_t>::max()));
1113
1114 AutoArraySchemaWriter writer(aWriter);
1115 writer.TimeMsElement(TIME, samples[i].mTime);
1116 writer.IntElement(COUNT, samples[i].mCount - previousCount);
1117 if (hasNumber) {
1118 writer.IntElement(NUMBER, static_cast<int64_t>(samples[i].mNumber -
1119 previousNumber));
1120 }
1121 previousNumber = samples[i].mNumber;
1122 previousCount = samples[i].mCount;
1123 }
1124 }
1125 aWriter.EndArray(); // data
1126 aWriter.EndObject(); // samples
1127 aWriter.End(); // for each counter
1128 }
1129 aWriter.EndArray(); // counters
1130 });
1131 }
1132
1133 #undef ERROR_AND_CONTINUE
1134
1135 static void AddPausedRange(SpliceableJSONWriter& aWriter, const char* aReason,
1136 const Maybe<double>& aStartTime,
1137 const Maybe<double>& aEndTime) {
1138 aWriter.Start();
1139 if (aStartTime) {
1140 aWriter.TimeDoubleMsProperty("startTime", *aStartTime);
1141 } else {
1142 aWriter.NullProperty("startTime");
1143 }
1144 if (aEndTime) {
1145 aWriter.TimeDoubleMsProperty("endTime", *aEndTime);
1146 } else {
1147 aWriter.NullProperty("endTime");
1148 }
1149 aWriter.StringProperty("reason", MakeStringSpan(aReason));
1150 aWriter.End();
1151 }
1152
1153 void ProfileBuffer::StreamPausedRangesToJSON(SpliceableJSONWriter& aWriter,
1154 double aSinceTime) const {
1155 mEntries.Read([&](ProfileChunkedBuffer::Reader* aReader) {
1156 MOZ_ASSERT(aReader,
1157 "ProfileChunkedBuffer cannot be out-of-session when sampler is "
1158 "running");
1159
1160 EntryGetter e(*aReader);
1161
1162 Maybe<double> currentPauseStartTime;
1163 Maybe<double> currentCollectionStartTime;
1164
1165 while (e.Has()) {
1166 if (e.Get().IsPause()) {
1167 currentPauseStartTime = Some(e.Get().GetDouble());
1168 } else if (e.Get().IsResume()) {
1169 AddPausedRange(aWriter, "profiler-paused", currentPauseStartTime,
1170 Some(e.Get().GetDouble()));
1171 currentPauseStartTime = Nothing();
1172 } else if (e.Get().IsCollectionStart()) {
1173 currentCollectionStartTime = Some(e.Get().GetDouble());
1174 } else if (e.Get().IsCollectionEnd()) {
1175 AddPausedRange(aWriter, "collecting", currentCollectionStartTime,
1176 Some(e.Get().GetDouble()));
1177 currentCollectionStartTime = Nothing();
1178 }
1179 e.Next();
1180 }
1181
1182 if (currentPauseStartTime) {
1183 AddPausedRange(aWriter, "profiler-paused", currentPauseStartTime,
1184 Nothing());
1185 }
1186 if (currentCollectionStartTime) {
1187 AddPausedRange(aWriter, "collecting", currentCollectionStartTime,
1188 Nothing());
1189 }
1190 });
1191 }
1192
1193 bool ProfileBuffer::DuplicateLastSample(BaseProfilerThreadId aThreadId,
1194 const TimeStamp& aProcessStartTime,
1195 Maybe<uint64_t>& aLastSample) {
1196 if (!aLastSample) {
1197 return false;
1198 }
1199
1200 ProfileChunkedBuffer tempBuffer(
1201 ProfileChunkedBuffer::ThreadSafety::WithoutMutex, WorkerChunkManager());
1202
1203 auto retrieveWorkerChunk = MakeScopeExit(
1204 [&]() { WorkerChunkManager().Reset(tempBuffer.GetAllChunks()); });
1205
1206 const bool ok = mEntries.Read([&](ProfileChunkedBuffer::Reader* aReader) {
1207 MOZ_ASSERT(aReader,
1208 "ProfileChunkedBuffer cannot be out-of-session when sampler is "
1209 "running");
1210
1211 EntryGetter e(*aReader, *aLastSample);
1212
1213 if (e.CurPos() != *aLastSample) {
1214 // The last sample is no longer within the buffer range, so we cannot
1215 // use it. Reset the stored buffer position to Nothing().
1216 aLastSample.reset();
1217 return false;
1218 }
1219
1220 MOZ_RELEASE_ASSERT(e.Has() && e.Get().IsThreadId() &&
1221 e.Get().GetThreadId() == aThreadId);
1222
1223 e.Next();
1224
1225 // Go through the whole entry and duplicate it, until we find the next
1226 // one.
1227 while (e.Has()) {
1228 switch (e.Get().GetKind()) {
1229 case ProfileBufferEntry::Kind::Pause:
1230 case ProfileBufferEntry::Kind::Resume:
1231 case ProfileBufferEntry::Kind::PauseSampling:
1232 case ProfileBufferEntry::Kind::ResumeSampling:
1233 case ProfileBufferEntry::Kind::CollectionStart:
1234 case ProfileBufferEntry::Kind::CollectionEnd:
1235 case ProfileBufferEntry::Kind::ThreadId:
1236 // We're done.
1237 return true;
1238 case ProfileBufferEntry::Kind::Time:
1239 // Copy with new time
1240 AddEntry(
1241 tempBuffer,
1242 ProfileBufferEntry::Time(
1243 (TimeStamp::Now() - aProcessStartTime).ToMilliseconds()));
1244 break;
1245 case ProfileBufferEntry::Kind::Number:
1246 case ProfileBufferEntry::Kind::Count:
1247 case ProfileBufferEntry::Kind::Responsiveness:
1248 // Don't copy anything not part of a thread's stack sample
1249 break;
1250 case ProfileBufferEntry::Kind::CounterId:
1251 // CounterId is normally followed by Time - if so, we'd like
1252 // to skip it. If we duplicate Time, it won't hurt anything, just
1253 // waste buffer space (and this can happen if the CounterId has
1254 // fallen off the end of the buffer, but Time (and Number/Count)
1255 // are still in the buffer).
1256 e.Next();
1257 if (e.Has() && e.Get().GetKind() != ProfileBufferEntry::Kind::Time) {
1258 // this would only happen if there was an invalid sequence
1259 // in the buffer. Don't skip it.
1260 continue;
1261 }
1262 // we've skipped Time
1263 break;
1264 case ProfileBufferEntry::Kind::ProfilerOverheadTime:
1265 // ProfilerOverheadTime is normally followed by
1266 // ProfilerOverheadDuration*4 - if so, we'd like to skip it. Don't
1267 // duplicate, as we are in the middle of a sampling and will soon
1268 // capture its own overhead.
1269 e.Next();
1270 // A missing Time would only happen if there was an invalid
1271 // sequence in the buffer. Don't skip unexpected entry.
1272 if (e.Has() &&
1273 e.Get().GetKind() !=
1274 ProfileBufferEntry::Kind::ProfilerOverheadDuration) {
1275 continue;
1276 }
1277 e.Next();
1278 if (e.Has() &&
1279 e.Get().GetKind() !=
1280 ProfileBufferEntry::Kind::ProfilerOverheadDuration) {
1281 continue;
1282 }
1283 e.Next();
1284 if (e.Has() &&
1285 e.Get().GetKind() !=
1286 ProfileBufferEntry::Kind::ProfilerOverheadDuration) {
1287 continue;
1288 }
1289 e.Next();
1290 if (e.Has() &&
1291 e.Get().GetKind() !=
1292 ProfileBufferEntry::Kind::ProfilerOverheadDuration) {
1293 continue;
1294 }
1295 // we've skipped ProfilerOverheadTime and
1296 // ProfilerOverheadDuration*4.
1297 break;
1298 default: {
1299 // Copy anything else we don't know about.
1300 AddEntry(tempBuffer, e.Get());
1301 break;
1302 }
1303 }
1304 e.Next();
1305 }
1306 return true;
1307 });
1308
1309 if (!ok) {
1310 return false;
1311 }
1312
1313 // If the buffer was big enough, there won't be any cleared blocks.
1314 if (tempBuffer.GetState().mClearedBlockCount != 0) {
1315 // No need to try to read stack again as it won't fit. Reset the stored
1316 // buffer position to Nothing().
1317 aLastSample.reset();
1318 return false;
1319 }
1320
1321 aLastSample = Some(AddThreadIdEntry(aThreadId));
1322
1323 tempBuffer.Read([&](ProfileChunkedBuffer::Reader* aReader) {
1324 MOZ_ASSERT(aReader, "tempBuffer cannot be out-of-session");
1325
1326 EntryGetter e(*aReader);
1327
1328 while (e.Has()) {
1329 AddEntry(e.Get());
1330 e.Next();
1331 }
1332 });
1333
1334 return true;
1335 }
1336
1337 void ProfileBuffer::DiscardSamplesBeforeTime(double aTime) {
1338 // This function does nothing!
1339 // The duration limit will be removed from Firefox, see bug 1632365.
1340 Unused << aTime;
1341 }
1342
1343 // END ProfileBuffer
1344 ////////////////////////////////////////////////////////////////////////
1345
1346 } // namespace baseprofiler
1347 } // namespace mozilla