Debian Codegraph @

js/src/gc/Statistics.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 "gc/Statistics.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/Sprintf.h"
11 #include "mozilla/TimeStamp.h"
12
13 #include <algorithm>
14 #include <stdarg.h>
15 #include <stdio.h>
16 #include <type_traits>
17
18 #include "gc/GC.h"
19 #include "gc/GCInternals.h"
20 #include "gc/Memory.h"
21 #include "js/Printer.h"
22 #include "util/GetPidProvider.h"
23 #include "util/Text.h"
24 #include "vm/JSONPrinter.h"
25 #include "vm/Runtime.h"
26 #include "vm/Time.h"
27
28 #include "gc/PrivateIterators-inl.h"
29
30 using namespace js;
31 using namespace js::gc;
32 using namespace js::gcstats;
33
34 using mozilla::DebugOnly;
35 using mozilla::EnumeratedArray;
36 using mozilla::Maybe;
37 using mozilla::TimeDuration;
38 using mozilla::TimeStamp;
39
40 using JS::SliceBudget;
41
42 static const size_t BYTES_PER_MB = 1024 * 1024;
43
44 /*
45 * If this fails, then you can either delete this assertion and allow all
46 * larger-numbered reasons to pile up in the last telemetry bucket, or switch
47 * to GC_REASON_3 and bump the max value.
48 */
49 static_assert(JS::GCReason::NUM_TELEMETRY_REASONS >= JS::GCReason::NUM_REASONS);
50
51 static inline auto AllPhaseKinds() {
52 return mozilla::MakeEnumeratedRange(PhaseKind::FIRST, PhaseKind::LIMIT);
53 }
54
55 static inline auto MajorGCPhaseKinds() {
56 return mozilla::MakeEnumeratedRange(PhaseKind::GC_BEGIN,
57 PhaseKind(size_t(PhaseKind::GC_END) + 1));
58 }
59
60 static const char* ExplainGCOptions(JS::GCOptions options) {
61 switch (options) {
62 case JS::GCOptions::Normal:
63 return "Normal";
64 case JS::GCOptions::Shrink:
65 return "Shrink";
66 case JS::GCOptions::Shutdown:
67 return "Shutdown";
68 }
69
70 MOZ_CRASH("Unexpected GCOptions value");
71 }
72
73 JS_PUBLIC_API const char* JS::ExplainGCReason(JS::GCReason reason) {
74 switch (reason) {
75 #define SWITCH_REASON(name, _) \
76 case JS::GCReason::name: \
77 return #name;
78 GCREASONS(SWITCH_REASON)
79 #undef SWITCH_REASON
80
81 case JS::GCReason::NO_REASON:
82 return "NO_REASON";
83
84 default:
85 MOZ_CRASH("bad GC reason");
86 }
87 }
88
89 JS_PUBLIC_API const char* JS::ExplainGCAbortReason(uint32_t val) {
90 GCAbortReason reason = static_cast<GCAbortReason>(val);
91 return js::gcstats::ExplainAbortReason(reason);
92 }
93
94 JS_PUBLIC_API bool JS::InternalGCReason(JS::GCReason reason) {
95 return reason < JS::GCReason::FIRST_FIREFOX_REASON;
96 }
97
98 const char* js::gcstats::ExplainAbortReason(GCAbortReason reason) {
99 switch (reason) {
100 #define SWITCH_REASON(name, _) \
101 case GCAbortReason::name: \
102 return #name;
103 GC_ABORT_REASONS(SWITCH_REASON)
104
105 default:
106 MOZ_CRASH("bad GC abort reason");
107 #undef SWITCH_REASON
108 }
109 }
110
111 static FILE* MaybeOpenFileFromEnv(const char* env,
112 FILE* defaultFile = nullptr) {
113 const char* value = getenv(env);
114 if (!value) {
115 return defaultFile;
116 }
117
118 FILE* file;
119 if (strcmp(value, "none") == 0) {
120 file = nullptr;
121 } else if (strcmp(value, "stdout") == 0) {
122 file = stdout;
123 } else if (strcmp(value, "stderr") == 0) {
124 file = stderr;
125 } else {
126 char path[300];
127 if (value[0] != '/') {
128 const char* dir = getenv("MOZ_UPLOAD_DIR");
129 if (dir) {
130 SprintfLiteral(path, "%s/%s", dir, value);
131 value = path;
132 }
133 }
134
135 file = fopen(value, "a");
136 if (!file || setvbuf(file, nullptr, _IOLBF, 256) != 0) {
137 perror("Error opening log file");
138 MOZ_CRASH("Failed to open log file.");
139 }
140 }
141
142 return file;
143 }
144
145 struct PhaseKindInfo {
146 Phase firstPhase;
147 uint8_t telemetryBucket;
148 const char* name;
149 };
150
151 // PhaseInfo objects form a tree.
152 struct PhaseInfo {
153 Phase parent;
154 Phase firstChild;
155 Phase nextSibling;
156 Phase nextWithPhaseKind;
157 PhaseKind phaseKind;
158 uint8_t depth;
159 const char* name;
160 const char* path;
161 };
162
163 // A table of PhaseInfo indexed by Phase.
164 using PhaseTable = EnumeratedArray<Phase, PhaseInfo, size_t(Phase::LIMIT)>;
165
166 // A table of PhaseKindInfo indexed by PhaseKind.
167 using PhaseKindTable =
168 EnumeratedArray<PhaseKind, PhaseKindInfo, size_t(PhaseKind::LIMIT)>;
169
170 #include "gc/StatsPhasesGenerated.inc"
171
172 // Iterate the phases in a phase kind.
173 class PhaseIter {
174 Phase phase;
175
176 public:
177 explicit PhaseIter(PhaseKind kind) : phase(phaseKinds[kind].firstPhase) {}
178 bool done() const { return phase == Phase::NONE; }
179 void next() { phase = phases[phase].nextWithPhaseKind; }
180 Phase get() const { return phase; }
181 operator Phase() const { return phase; }
182 };
183
184 JS_PUBLIC_API const char* JS::GetGCPhaseName(uint32_t val) {
185 PhaseKind kind = static_cast<PhaseKind>(val);
186 MOZ_RELEASE_ASSERT(kind < PhaseKind::LIMIT);
187 return phaseKinds[kind].name;
188 }
189
190 static double t(TimeDuration duration) { return duration.ToMilliseconds(); }
191
192 static TimeDuration TimeBetween(TimeStamp start, TimeStamp end) {
193 #ifndef XP_WIN
194 MOZ_ASSERT(end >= start);
195 #else
196 // Sadly this happens sometimes.
197 if (end < start) {
198 return TimeDuration::Zero();
199 }
200 #endif
201 return end - start;
202 }
203
204 inline JSContext* Statistics::context() {
205 return gc->rt->mainContextFromOwnThread();
206 }
207
208 inline Phase Statistics::currentPhase() const {
209 return phaseStack.empty() ? Phase::NONE : phaseStack.back();
210 }
211
212 PhaseKind Statistics::currentPhaseKind() const {
213 // Public API to get the current phase kind, suppressing the synthetic
214 // PhaseKind::MUTATOR phase.
215
216 Phase phase = currentPhase();
217 MOZ_ASSERT_IF(phase == Phase::MUTATOR, phaseStack.length() == 1);
218 if (phase == Phase::NONE || phase == Phase::MUTATOR) {
219 return PhaseKind::NONE;
220 }
221
222 return phases[phase].phaseKind;
223 }
224
225 static Phase LookupPhaseWithParent(PhaseKind phaseKind, Phase parentPhase) {
226 for (PhaseIter phase(phaseKind); !phase.done(); phase.next()) {
227 if (phases[phase].parent == parentPhase) {
228 return phase;
229 }
230 }
231
232 return Phase::NONE;
233 }
234
235 static const char* PhaseKindName(PhaseKind kind) {
236 if (kind == PhaseKind::NONE) {
237 return "NONE";
238 }
239
240 return phaseKinds[kind].name;
241 }
242
243 Phase Statistics::lookupChildPhase(PhaseKind phaseKind) const {
244 if (phaseKind == PhaseKind::IMPLICIT_SUSPENSION) {
245 return Phase::IMPLICIT_SUSPENSION;
246 }
247 if (phaseKind == PhaseKind::EXPLICIT_SUSPENSION) {
248 return Phase::EXPLICIT_SUSPENSION;
249 }
250
251 MOZ_ASSERT(phaseKind < PhaseKind::LIMIT);
252
253 // Search all expanded phases that correspond to the required
254 // phase to find the one whose parent is the current expanded phase.
255 Phase phase = LookupPhaseWithParent(phaseKind, currentPhase());
256
257 if (phase == Phase::NONE) {
258 MOZ_CRASH_UNSAFE_PRINTF(
259 "Child phase kind %s not found under current phase kind %s",
260 PhaseKindName(phaseKind), PhaseKindName(currentPhaseKind()));
261 }
262
263 return phase;
264 }
265
266 inline auto AllPhases() {
267 return mozilla::MakeEnumeratedRange(Phase::FIRST, Phase::LIMIT);
268 }
269
270 void Statistics::gcDuration(TimeDuration* total, TimeDuration* maxPause) const {
271 *total = *maxPause = TimeDuration::Zero();
272 for (const auto& slice : slices_) {
273 *total += slice.duration();
274 if (slice.duration() > *maxPause) {
275 *maxPause = slice.duration();
276 }
277 }
278 if (*maxPause > maxPauseInInterval) {
279 maxPauseInInterval = *maxPause;
280 }
281 }
282
283 void Statistics::sccDurations(TimeDuration* total,
284 TimeDuration* maxPause) const {
285 *total = *maxPause = TimeDuration::Zero();
286 for (const auto& duration : sccTimes) {
287 *total += duration;
288 *maxPause = std::max(*maxPause, duration);
289 }
290 }
291
292 using FragmentVector = Vector<UniqueChars, 8, SystemAllocPolicy>;
293
294 static UniqueChars Join(const FragmentVector& fragments,
295 const char* separator = "") {
296 const size_t separatorLength = strlen(separator);
297 size_t length = 0;
298 for (size_t i = 0; i < fragments.length(); ++i) {
299 length += fragments[i] ? strlen(fragments[i].get()) : 0;
300 if (i < (fragments.length() - 1)) {
301 length += separatorLength;
302 }
303 }
304
305 char* joined = js_pod_malloc<char>(length + 1);
306 if (!joined) {
307 return UniqueChars();
308 }
309
310 joined[length] = '\0';
311 char* cursor = joined;
312 for (size_t i = 0; i < fragments.length(); ++i) {
313 if (fragments[i]) {
314 strcpy(cursor, fragments[i].get());
315 }
316 cursor += fragments[i] ? strlen(fragments[i].get()) : 0;
317 if (i < (fragments.length() - 1)) {
318 if (separatorLength) {
319 strcpy(cursor, separator);
320 }
321 cursor += separatorLength;
322 }
323 }
324
325 return UniqueChars(joined);
326 }
327
328 static TimeDuration SumChildTimes(Phase phase,
329 const Statistics::PhaseTimes& phaseTimes) {
330 TimeDuration total;
331 for (phase = phases[phase].firstChild; phase != Phase::NONE;
332 phase = phases[phase].nextSibling) {
333 total += phaseTimes[phase];
334 }
335 return total;
336 }
337
338 UniqueChars Statistics::formatCompactSliceMessage() const {
339 // Skip if we OOM'ed.
340 if (slices_.length() == 0) {
341 return UniqueChars(nullptr);
342 }
343
344 const size_t index = slices_.length() - 1;
345 const SliceData& slice = slices_.back();
346
347 char budgetDescription[200];
348 slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
349
350 const char* format =
351 "GC Slice %u - Pause: %.3fms of %s budget (@ %.3fms); Reason: %s; Reset: "
352 "%s%s; Times: ";
353 char buffer[1024];
354 SprintfLiteral(buffer, format, index, t(slice.duration()), budgetDescription,
355 t(slice.start - slices_[0].start),
356 ExplainGCReason(slice.reason),
357 slice.wasReset() ? "yes - " : "no",
358 slice.wasReset() ? ExplainAbortReason(slice.resetReason) : "");
359
360 FragmentVector fragments;
361 if (!fragments.append(DuplicateString(buffer)) ||
362 !fragments.append(
363 formatCompactSlicePhaseTimes(slices_[index].phaseTimes))) {
364 return UniqueChars(nullptr);
365 }
366 return Join(fragments);
367 }
368
369 UniqueChars Statistics::formatCompactSummaryMessage() const {
370 FragmentVector fragments;
371 if (!fragments.append(DuplicateString("Summary - "))) {
372 return UniqueChars(nullptr);
373 }
374
375 TimeDuration total, longest;
376 gcDuration(&total, &longest);
377
378 const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
379 const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
380
381 char buffer[1024];
382 if (!nonincremental()) {
383 SprintfLiteral(buffer,
384 "Max Pause: %.3fms; MMU 20ms: %.1f%%; MMU 50ms: %.1f%%; "
385 "Total: %.3fms; ",
386 t(longest), mmu20 * 100., mmu50 * 100., t(total));
387 } else {
388 SprintfLiteral(buffer, "Non-Incremental: %.3fms (%s); ", t(total),
389 ExplainAbortReason(nonincrementalReason_));
390 }
391 if (!fragments.append(DuplicateString(buffer))) {
392 return UniqueChars(nullptr);
393 }
394
395 SprintfLiteral(buffer,
396 "Zones: %zu of %zu (-%zu); Compartments: %zu of %zu (-%zu); "
397 "HeapSize: %.3f MiB; "
398 "HeapChange (abs): %+d (%u); ",
399 zoneStats.collectedZoneCount, zoneStats.zoneCount,
400 zoneStats.sweptZoneCount, zoneStats.collectedCompartmentCount,
401 zoneStats.compartmentCount, zoneStats.sweptCompartmentCount,
402 double(preTotalGCHeapBytes) / BYTES_PER_MB,
403 int32_t(counts[COUNT_NEW_CHUNK] - counts[COUNT_DESTROY_CHUNK]),
404 counts[COUNT_NEW_CHUNK] + counts[COUNT_DESTROY_CHUNK]);
405 if (!fragments.append(DuplicateString(buffer))) {
406 return UniqueChars(nullptr);
407 }
408
409 MOZ_ASSERT_IF(counts[COUNT_ARENA_RELOCATED],
410 gcOptions == JS::GCOptions::Shrink);
411 if (gcOptions == JS::GCOptions::Shrink) {
412 SprintfLiteral(
413 buffer, "Kind: %s; Relocated: %.3f MiB; ", ExplainGCOptions(gcOptions),
414 double(ArenaSize * counts[COUNT_ARENA_RELOCATED]) / BYTES_PER_MB);
415 if (!fragments.append(DuplicateString(buffer))) {
416 return UniqueChars(nullptr);
417 }
418 }
419
420 return Join(fragments);
421 }
422
423 UniqueChars Statistics::formatCompactSlicePhaseTimes(
424 const PhaseTimes& phaseTimes) const {
425 static const TimeDuration MaxUnaccountedTime =
426 TimeDuration::FromMicroseconds(100);
427
428 FragmentVector fragments;
429 char buffer[128];
430 for (auto phase : AllPhases()) {
431 DebugOnly<uint8_t> level = phases[phase].depth;
432 MOZ_ASSERT(level < 4);
433
434 TimeDuration ownTime = phaseTimes[phase];
435 TimeDuration childTime = SumChildTimes(phase, phaseTimes);
436 if (ownTime > MaxUnaccountedTime) {
437 SprintfLiteral(buffer, "%s: %.3fms", phases[phase].name, t(ownTime));
438 if (!fragments.append(DuplicateString(buffer))) {
439 return UniqueChars(nullptr);
440 }
441
442 if (childTime && (ownTime - childTime) > MaxUnaccountedTime) {
443 MOZ_ASSERT(level < 3);
444 SprintfLiteral(buffer, "%s: %.3fms", "Other", t(ownTime - childTime));
445 if (!fragments.append(DuplicateString(buffer))) {
446 return UniqueChars(nullptr);
447 }
448 }
449 }
450 }
451 return Join(fragments, ", ");
452 }
453
454 UniqueChars Statistics::formatDetailedMessage() const {
455 FragmentVector fragments;
456
457 if (!fragments.append(formatDetailedDescription())) {
458 return UniqueChars(nullptr);
459 }
460
461 if (!slices_.empty()) {
462 for (unsigned i = 0; i < slices_.length(); i++) {
463 if (!fragments.append(formatDetailedSliceDescription(i, slices_[i]))) {
464 return UniqueChars(nullptr);
465 }
466 if (!fragments.append(formatDetailedPhaseTimes(slices_[i].phaseTimes))) {
467 return UniqueChars(nullptr);
468 }
469 }
470 }
471 if (!fragments.append(formatDetailedTotals())) {
472 return UniqueChars(nullptr);
473 }
474 if (!fragments.append(formatDetailedPhaseTimes(phaseTimes))) {
475 return UniqueChars(nullptr);
476 }
477
478 return Join(fragments);
479 }
480
481 UniqueChars Statistics::formatDetailedDescription() const {
482 TimeDuration sccTotal, sccLongest;
483 sccDurations(&sccTotal, &sccLongest);
484
485 const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
486 const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
487
488 const char* format =
489 "=================================================================\n\
490 Invocation Kind: %s\n\
491 Reason: %s\n\
492 Incremental: %s%s\n\
493 Zones Collected: %d of %d (-%d)\n\
494 Compartments Collected: %d of %d (-%d)\n\
495 MinorGCs since last GC: %d\n\
496 Store Buffer Overflows: %d\n\
497 MMU 20ms:%.1f%%; 50ms:%.1f%%\n\
498 SCC Sweep Total (MaxPause): %.3fms (%.3fms)\n\
499 HeapSize: %.3f MiB\n\
500 Chunk Delta (magnitude): %+d (%d)\n\
501 Arenas Relocated: %.3f MiB\n\
502 ";
503
504 char buffer[1024];
505 SprintfLiteral(
506 buffer, format, ExplainGCOptions(gcOptions),
507 ExplainGCReason(slices_[0].reason), nonincremental() ? "no - " : "yes",
508 nonincremental() ? ExplainAbortReason(nonincrementalReason_) : "",
509 zoneStats.collectedZoneCount, zoneStats.zoneCount,
510 zoneStats.sweptZoneCount, zoneStats.collectedCompartmentCount,
511 zoneStats.compartmentCount, zoneStats.sweptCompartmentCount,
512 getCount(COUNT_MINOR_GC), getCount(COUNT_STOREBUFFER_OVERFLOW),
513 mmu20 * 100., mmu50 * 100., t(sccTotal), t(sccLongest),
514 double(preTotalGCHeapBytes) / BYTES_PER_MB,
515 getCount(COUNT_NEW_CHUNK) - getCount(COUNT_DESTROY_CHUNK),
516 getCount(COUNT_NEW_CHUNK) + getCount(COUNT_DESTROY_CHUNK),
517 double(ArenaSize * getCount(COUNT_ARENA_RELOCATED)) / BYTES_PER_MB);
518
519 return DuplicateString(buffer);
520 }
521
522 UniqueChars Statistics::formatDetailedSliceDescription(
523 unsigned i, const SliceData& slice) const {
524 char budgetDescription[200];
525 slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
526
527 const char* format =
528 "\
529 ---- Slice %u ----\n\
530 Reason: %s\n\
531 Trigger: %s\n\
532 Reset: %s%s\n\
533 State: %s -> %s\n\
534 Page Faults: %" PRIu64
535 "\n\
536 Pause: %.3fms of %s budget (@ %.3fms)\n\
537 ";
538
539 char triggerBuffer[100] = "n/a";
540 if (slice.trigger) {
541 Trigger trigger = slice.trigger.value();
542 SprintfLiteral(triggerBuffer, "%.3f MiB of %.3f MiB threshold\n",
543 double(trigger.amount) / BYTES_PER_MB,
544 double(trigger.threshold) / BYTES_PER_MB);
545 }
546
547 char buffer[1024];
548 SprintfLiteral(
549 buffer, format, i, ExplainGCReason(slice.reason), triggerBuffer,
550 slice.wasReset() ? "yes - " : "no",
551 slice.wasReset() ? ExplainAbortReason(slice.resetReason) : "",
552 gc::StateName(slice.initialState), gc::StateName(slice.finalState),
553 uint64_t(slice.endFaults - slice.startFaults), t(slice.duration()),
554 budgetDescription, t(slice.start - slices_[0].start));
555 return DuplicateString(buffer);
556 }
557
558 static bool IncludePhase(TimeDuration duration) {
559 // Don't include durations that will print as "0.000ms".
560 return duration.ToMilliseconds() >= 0.001;
561 }
562
563 UniqueChars Statistics::formatDetailedPhaseTimes(
564 const PhaseTimes& phaseTimes) const {
565 static const TimeDuration MaxUnaccountedChildTime =
566 TimeDuration::FromMicroseconds(50);
567
568 FragmentVector fragments;
569 char buffer[128];
570 for (auto phase : AllPhases()) {
571 uint8_t level = phases[phase].depth;
572 TimeDuration ownTime = phaseTimes[phase];
573 TimeDuration childTime = SumChildTimes(phase, phaseTimes);
574 if (IncludePhase(ownTime)) {
575 SprintfLiteral(buffer, " %*s%s: %.3fms\n", level * 2, "",
576 phases[phase].name, t(ownTime));
577 if (!fragments.append(DuplicateString(buffer))) {
578 return UniqueChars(nullptr);
579 }
580
581 if (childTime && (ownTime - childTime) > MaxUnaccountedChildTime) {
582 SprintfLiteral(buffer, " %*s%s: %.3fms\n", (level + 1) * 2, "",
583 "Other", t(ownTime - childTime));
584 if (!fragments.append(DuplicateString(buffer))) {
585 return UniqueChars(nullptr);
586 }
587 }
588 }
589 }
590 return Join(fragments);
591 }
592
593 UniqueChars Statistics::formatDetailedTotals() const {
594 TimeDuration total, longest;
595 gcDuration(&total, &longest);
596
597 const char* format =
598 "\
599 ---- Totals ----\n\
600 Total Time: %.3fms\n\
601 Max Pause: %.3fms\n\
602 ";
603 char buffer[1024];
604 SprintfLiteral(buffer, format, t(total), t(longest));
605 return DuplicateString(buffer);
606 }
607
608 void Statistics::formatJsonSlice(size_t sliceNum, JSONPrinter& json) const {
609 /*
610 * We number each of the slice properties to keep the code in
611 * GCTelemetry.sys.mjs in sync. See MAX_SLICE_KEYS.
612 */
613 json.beginObject();
614 formatJsonSliceDescription(sliceNum, slices_[sliceNum], json); // # 1-11
615
616 json.beginObjectProperty("times"); // # 12
617 formatJsonPhaseTimes(slices_[sliceNum].phaseTimes, json);
618 json.endObject();
619
620 json.endObject();
621 }
622
623 UniqueChars Statistics::renderJsonSlice(size_t sliceNum) const {
624 Sprinter printer(nullptr, false);
625 if (!printer.init()) {
626 return UniqueChars(nullptr);
627 }
628 JSONPrinter json(printer, false);
629
630 formatJsonSlice(sliceNum, json);
631 return printer.release();
632 }
633
634 UniqueChars Statistics::renderNurseryJson() const {
635 Sprinter printer(nullptr, false);
636 if (!printer.init()) {
637 return UniqueChars(nullptr);
638 }
639 JSONPrinter json(printer, false);
640 gc->nursery().renderProfileJSON(json);
641 return printer.release();
642 }
643
644 #ifdef DEBUG
645 void Statistics::log(const char* fmt, ...) {
646 va_list args;
647 va_start(args, fmt);
648 if (gcDebugFile) {
649 TimeDuration sinceStart =
650 TimeBetween(TimeStamp::FirstTimeStamp(), TimeStamp::Now());
651 fprintf(gcDebugFile, "%12.3f: ", sinceStart.ToMicroseconds());
652 vfprintf(gcDebugFile, fmt, args);
653 fprintf(gcDebugFile, "\n");
654 fflush(gcDebugFile);
655 }
656 va_end(args);
657 }
658 #endif
659
660 UniqueChars Statistics::renderJsonMessage() const {
661 /*
662 * The format of the JSON message is specified by the GCMajorMarkerPayload
663 * type in profiler.firefox.com
664 * https://github.com/firefox-devtools/profiler/blob/master/src/types/markers.js#L62
665 *
666 * All the properties listed here are created within the timings property
667 * of the GCMajor marker.
668 */
669 if (aborted) {
670 return DuplicateString("{status:\"aborted\"}"); // May return nullptr
671 }
672
673 Sprinter printer(nullptr, false);
674 if (!printer.init()) {
675 return UniqueChars(nullptr);
676 }
677 JSONPrinter json(printer, false);
678
679 json.beginObject();
680 json.property("status", "completed");
681 formatJsonDescription(json);
682
683 json.beginObjectProperty("totals");
684 formatJsonPhaseTimes(phaseTimes, json);
685 json.endObject();
686
687 json.endObject();
688
689 return printer.release();
690 }
691
692 void Statistics::formatJsonDescription(JSONPrinter& json) const {
693 // If you change JSON properties here, please update:
694 // Firefox Profiler:
695 // https://github.com/firefox-devtools/profiler
696
697 TimeDuration total, longest;
698 gcDuration(&total, &longest);
699 json.property("max_pause", longest, JSONPrinter::MILLISECONDS);
700 json.property("total_time", total, JSONPrinter::MILLISECONDS);
701 // We might be able to omit reason if profiler.firefox.com was able to retrive
702 // it from the first slice. But it doesn't do this yet.
703 json.property("reason", ExplainGCReason(slices_[0].reason));
704 json.property("zones_collected", zoneStats.collectedZoneCount);
705 json.property("total_zones", zoneStats.zoneCount);
706 json.property("total_compartments", zoneStats.compartmentCount);
707 json.property("minor_gcs", getCount(COUNT_MINOR_GC));
708 json.property("minor_gc_number", gc->minorGCCount());
709 json.property("major_gc_number", gc->majorGCCount());
710 uint32_t storebufferOverflows = getCount(COUNT_STOREBUFFER_OVERFLOW);
711 if (storebufferOverflows) {
712 json.property("store_buffer_overflows", storebufferOverflows);
713 }
714 json.property("slices", slices_.length());
715
716 const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
717 const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
718 json.property("mmu_20ms", int(mmu20 * 100));
719 json.property("mmu_50ms", int(mmu50 * 100));
720
721 TimeDuration sccTotal, sccLongest;
722 sccDurations(&sccTotal, &sccLongest);
723 json.property("scc_sweep_total", sccTotal, JSONPrinter::MILLISECONDS);
724 json.property("scc_sweep_max_pause", sccLongest, JSONPrinter::MILLISECONDS);
725
726 if (nonincrementalReason_ != GCAbortReason::None) {
727 json.property("nonincremental_reason",
728 ExplainAbortReason(nonincrementalReason_));
729 }
730 json.property("allocated_bytes", preTotalGCHeapBytes);
731 json.property("post_heap_size", postTotalGCHeapBytes);
732
733 json.property("pre_malloc_heap_size", preTotalMallocHeapBytes);
734 json.property("post_malloc_heap_size", postTotalMallocHeapBytes);
735
736 uint32_t addedChunks = getCount(COUNT_NEW_CHUNK);
737 if (addedChunks) {
738 json.property("added_chunks", addedChunks);
739 }
740 uint32_t removedChunks = getCount(COUNT_DESTROY_CHUNK);
741 if (removedChunks) {
742 json.property("removed_chunks", removedChunks);
743 }
744 json.property("major_gc_number", startingMajorGCNumber);
745 json.property("minor_gc_number", startingMinorGCNumber);
746 json.property("slice_number", startingSliceNumber);
747 }
748
749 void Statistics::formatJsonSliceDescription(unsigned i, const SliceData& slice,
750 JSONPrinter& json) const {
751 // If you change JSON properties here, please update:
752 // Firefox Profiler:
753 // https://github.com/firefox-devtools/profiler
754 //
755 char budgetDescription[200];
756 slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
757 TimeStamp originTime = TimeStamp::ProcessCreation();
758
759 json.property("slice", i);
760 json.property("pause", slice.duration(), JSONPrinter::MILLISECONDS);
761 json.property("reason", ExplainGCReason(slice.reason));
762 json.property("initial_state", gc::StateName(slice.initialState));
763 json.property("final_state", gc::StateName(slice.finalState));
764 json.property("budget", budgetDescription);
765 json.property("major_gc_number", startingMajorGCNumber);
766 if (slice.trigger) {
767 Trigger trigger = slice.trigger.value();
768 json.property("trigger_amount", trigger.amount);
769 json.property("trigger_threshold", trigger.threshold);
770 }
771 MOZ_ASSERT(slice.endFaults >= slice.startFaults);
772 size_t numFaults = slice.endFaults - slice.startFaults;
773 if (numFaults != 0) {
774 json.property("page_faults", numFaults);
775 }
776 json.property("start_timestamp", TimeBetween(originTime, slice.start),
777 JSONPrinter::SECONDS);
778 }
779
780 void Statistics::formatJsonPhaseTimes(const PhaseTimes& phaseTimes,
781 JSONPrinter& json) const {
782 for (auto phase : AllPhases()) {
783 TimeDuration ownTime = phaseTimes[phase];
784 if (!ownTime.IsZero()) {
785 json.property(phases[phase].path, ownTime, JSONPrinter::MILLISECONDS);
786 }
787 }
788 }
789
790 Statistics::Statistics(GCRuntime* gc)
791 : gc(gc),
792 gcTimerFile(nullptr),
793 gcDebugFile(nullptr),
794 nonincrementalReason_(GCAbortReason::None),
795 creationTime_(TimeStamp::Now()),
796 tenuredAllocsSinceMinorGC(0),
797 preTotalGCHeapBytes(0),
798 postTotalGCHeapBytes(0),
799 preCollectedGCHeapBytes(0),
800 preTotalMallocHeapBytes(0),
801 postTotalMallocHeapBytes(0),
802 startingMinorGCNumber(0),
803 startingMajorGCNumber(0),
804 startingSliceNumber(0),
805 sliceCallback(nullptr),
806 aborted(false),
807 enableProfiling_(false),
808 sliceCount_(0) {
809 for (auto& count : counts) {
810 count = 0;
811 }
812
813 for (auto& stat : stats) {
814 stat = 0;
815 }
816
817 #ifdef DEBUG
818 for (const auto& duration : totalTimes_) {
819 using ElementType = std::remove_reference_t<decltype(duration)>;
820 static_assert(!std::is_trivially_constructible_v<ElementType>,
821 "Statistics::Statistics will only initialize "
822 "totalTimes_'s elements if their default constructor is "
823 "non-trivial");
824 MOZ_ASSERT(duration.IsZero(),
825 "totalTimes_ default-initialization should have "
826 "default-initialized every element of totalTimes_ to zero");
827 }
828 #endif
829
830 MOZ_ALWAYS_TRUE(phaseStack.reserve(MAX_PHASE_NESTING));
831 MOZ_ALWAYS_TRUE(suspendedPhases.reserve(MAX_SUSPENDED_PHASES));
832
833 gcTimerFile = MaybeOpenFileFromEnv("MOZ_GCTIMER");
834 gcDebugFile = MaybeOpenFileFromEnv("JS_GC_DEBUG");
835 gcProfileFile = MaybeOpenFileFromEnv("JS_GC_PROFILE_FILE", stderr);
836
837 gc::ReadProfileEnv("JS_GC_PROFILE",
838 "Report major GCs taking more than N milliseconds for "
839 "all or just the main runtime\n",
840 &enableProfiling_, &profileWorkers_, &profileThreshold_);
841
842 const char* env = getenv("JS_GC_BUFFER_STATS");
843 enableBufferAllocStats_ = env && atoi(env);
844 }
845
846 Statistics::~Statistics() {
847 if (gcTimerFile && gcTimerFile != stdout && gcTimerFile != stderr) {
848 fclose(gcTimerFile);
849 }
850 if (gcDebugFile && gcDebugFile != stdout && gcDebugFile != stderr) {
851 fclose(gcDebugFile);
852 }
853 }
854
855 /* static */
856 bool Statistics::initialize() {
857 #ifdef DEBUG
858 // Sanity check generated tables.
859 for (auto i : AllPhases()) {
860 auto parent = phases[i].parent;
861 if (parent != Phase::NONE) {
862 MOZ_ASSERT(phases[i].depth == phases[parent].depth + 1);
863 }
864 auto firstChild = phases[i].firstChild;
865 if (firstChild != Phase::NONE) {
866 MOZ_ASSERT(i == phases[firstChild].parent);
867 MOZ_ASSERT(phases[i].depth == phases[firstChild].depth - 1);
868 }
869 auto nextSibling = phases[i].nextSibling;
870 if (nextSibling != Phase::NONE) {
871 MOZ_ASSERT(parent == phases[nextSibling].parent);
872 MOZ_ASSERT(phases[i].depth == phases[nextSibling].depth);
873 }
874 auto nextWithPhaseKind = phases[i].nextWithPhaseKind;
875 if (nextWithPhaseKind != Phase::NONE) {
876 MOZ_ASSERT(phases[i].phaseKind == phases[nextWithPhaseKind].phaseKind);
877 MOZ_ASSERT(parent != phases[nextWithPhaseKind].parent);
878 }
879 }
880 for (auto i : AllPhaseKinds()) {
881 MOZ_ASSERT(phases[phaseKinds[i].firstPhase].phaseKind == i);
882 for (auto j : AllPhaseKinds()) {
883 MOZ_ASSERT_IF(i != j, phaseKinds[i].telemetryBucket !=
884 phaseKinds[j].telemetryBucket);
885 }
886 }
887 #endif
888
889 return true;
890 }
891
892 JS::GCSliceCallback Statistics::setSliceCallback(
893 JS::GCSliceCallback newCallback) {
894 JS::GCSliceCallback oldCallback = sliceCallback;
895 sliceCallback = newCallback;
896 return oldCallback;
897 }
898
899 TimeDuration Statistics::clearMaxGCPauseAccumulator() {
900 TimeDuration prior = maxPauseInInterval;
901 maxPauseInInterval = TimeDuration::Zero();
902 return prior;
903 }
904
905 TimeDuration Statistics::getMaxGCPauseSinceClear() {
906 return maxPauseInInterval;
907 }
908
909 // Sum up the time for a phase, including instances of the phase with different
910 // parents.
911 static TimeDuration SumPhase(PhaseKind phaseKind,
912 const Statistics::PhaseTimes& times) {
913 TimeDuration sum;
914 for (PhaseIter phase(phaseKind); !phase.done(); phase.next()) {
915 sum += times[phase];
916 }
917 return sum;
918 }
919
920 static bool CheckSelfTime(Phase parent, Phase child,
921 const Statistics::PhaseTimes& times,
922 const Statistics::PhaseTimes& selfTimes,
923 TimeDuration childTime) {
924 if (selfTimes[parent] < childTime) {
925 fprintf(
926 stderr,
927 "Parent %s time = %.3fms with %.3fms remaining, child %s time %.3fms\n",
928 phases[parent].name, times[parent].ToMilliseconds(),
929 selfTimes[parent].ToMilliseconds(), phases[child].name,
930 childTime.ToMilliseconds());
931 fflush(stderr);
932 return false;
933 }
934
935 return true;
936 }
937
938 static PhaseKind FindLongestPhaseKind(const Statistics::PhaseKindTimes& times) {
939 TimeDuration longestTime;
940 PhaseKind phaseKind = PhaseKind::NONE;
941 for (auto i : MajorGCPhaseKinds()) {
942 if (times[i] > longestTime) {
943 longestTime = times[i];
944 phaseKind = i;
945 }
946 }
947
948 return phaseKind;
949 }
950
951 static PhaseKind LongestPhaseSelfTimeInMajorGC(
952 const Statistics::PhaseTimes& times) {
953 // Start with total times per expanded phase, including children's times.
954 Statistics::PhaseTimes selfTimes(times);
955
956 // We have the total time spent in each phase, including descendant times.
957 // Loop over the children and subtract their times from their parent's self
958 // time.
959 for (auto i : AllPhases()) {
960 Phase parent = phases[i].parent;
961 if (parent != Phase::NONE) {
962 bool ok = CheckSelfTime(parent, i, times, selfTimes, times[i]);
963
964 // This happens very occasionally in release builds and frequently
965 // in Windows debug builds. Skip collecting longest phase telemetry
966 // if it does.
967 #ifndef XP_WIN
968 MOZ_ASSERT(ok, "Inconsistent time data; see bug 1400153");
969 #endif
970 if (!ok) {
971 return PhaseKind::NONE;
972 }
973
974 selfTimes[parent] -= times[i];
975 }
976 }
977
978 // Sum expanded phases corresponding to the same phase.
979 Statistics::PhaseKindTimes phaseKindTimes;
980 for (auto i : AllPhaseKinds()) {
981 phaseKindTimes[i] = SumPhase(i, selfTimes);
982 }
983
984 return FindLongestPhaseKind(phaseKindTimes);
985 }
986
987 void Statistics::printStats() {
988 if (aborted) {
989 fprintf(gcTimerFile,
990 "OOM during GC statistics collection. The report is unavailable "
991 "for this GC.\n");
992 } else {
993 UniqueChars msg = formatDetailedMessage();
994 if (msg) {
995 double secSinceStart =
996 TimeBetween(TimeStamp::ProcessCreation(), slices_[0].start)
997 .ToSeconds();
998 fprintf(gcTimerFile, "GC(T+%.3fs) %s\n", secSinceStart, msg.get());
999 }
1000 }
1001 fflush(gcTimerFile);
1002 }
1003
1004 void Statistics::beginGC(JS::GCOptions options, const TimeStamp& currentTime) {
1005 slices_.clearAndFree();
1006 sccTimes.clearAndFree();
1007 gcOptions = options;
1008 nonincrementalReason_ = GCAbortReason::None;
1009
1010 startingMajorGCNumber = gc->majorGCCount();
1011 startingSliceNumber = gc->gcNumber();
1012
1013 if (gc->lastGCEndTime()) {
1014 timeSinceLastGC = TimeBetween(gc->lastGCEndTime(), currentTime);
1015 }
1016
1017 totalGCTime_ = TimeDuration::Zero();
1018
1019 preTotalGCHeapBytes = 0;
1020 postTotalGCHeapBytes = 0;
1021 preCollectedGCHeapBytes = 0;
1022 preTotalMallocHeapBytes = 0;
1023 postTotalMallocHeapBytes = 0;
1024 }
1025
1026 void Statistics::measureInitialHeapSizes() {
1027 MOZ_ASSERT(preTotalGCHeapBytes == 0);
1028 MOZ_ASSERT(preCollectedGCHeapBytes == 0);
1029 MOZ_ASSERT(preTotalMallocHeapBytes == 0);
1030
1031 preTotalGCHeapBytes = gc->heapSize.bytes();
1032
1033 for (AllZonesIter zone(gc); !zone.done(); zone.next()) {
1034 preTotalMallocHeapBytes += zone->mallocHeapSize.bytes();
1035 if (zone->wasGCStarted()) {
1036 preCollectedGCHeapBytes += zone->gcHeapSize.bytes();
1037 }
1038 }
1039 }
1040
1041 void Statistics::endGC() {
1042 MOZ_ASSERT(postTotalGCHeapBytes == 0);
1043 MOZ_ASSERT(postTotalMallocHeapBytes == 0);
1044
1045 postTotalGCHeapBytes = gc->heapSize.bytes();
1046 for (AllZonesIter zone(gc); !zone.done(); zone.next()) {
1047 postTotalMallocHeapBytes += zone->mallocHeapSize.bytes();
1048 }
1049
1050 sendGCTelemetry();
1051 }
1052
1053 TimeDuration Statistics::sumTotalParallelTime(PhaseKind phaseKind) const {
1054 TimeDuration total;
1055 for (const SliceData& slice : slices_) {
1056 total += slice.totalParallelTimes[phaseKind];
1057 }
1058 return total;
1059 }
1060
1061 void Statistics::sendGCTelemetry() {
1062 JSRuntime* runtime = gc->rt;
1063 // NOTE: "Compartmental" is term that was deprecated with the
1064 // introduction of zone-based GC, but the old telemetry probe
1065 // continues to be used.
1066 runtime->metrics().GC_IS_COMPARTMENTAL(!gc->fullGCRequested);
1067 runtime->metrics().GC_ZONE_COUNT(zoneStats.zoneCount);
1068 runtime->metrics().GC_ZONES_COLLECTED(zoneStats.collectedZoneCount);
1069
1070 TimeDuration prepareTotal = phaseTimes[Phase::PREPARE];
1071 TimeDuration markTotal = SumPhase(PhaseKind::MARK, phaseTimes);
1072 TimeDuration markRootsTotal = SumPhase(PhaseKind::MARK_ROOTS, phaseTimes);
1073
1074 // Gray and weak marking time is counted under MARK_WEAK and not MARK_GRAY.
1075 TimeDuration markWeakTotal = SumPhase(PhaseKind::MARK_WEAK, phaseTimes);
1076 TimeDuration markGrayNotWeak =
1077 SumPhase(PhaseKind::MARK_GRAY, phaseTimes) +
1078 SumPhase(PhaseKind::MARK_INCOMING_GRAY, phaseTimes);
1079 TimeDuration markGrayWeak = SumPhase(PhaseKind::MARK_GRAY_WEAK, phaseTimes);
1080 TimeDuration markGrayTotal = markGrayNotWeak + markGrayWeak;
1081 TimeDuration markNotGrayOrWeak = markTotal - markGrayNotWeak - markWeakTotal;
1082 if (markNotGrayOrWeak < TimeDuration::FromMilliseconds(0)) {
1083 markNotGrayOrWeak = TimeDuration::Zero();
1084 }
1085
1086 size_t markCount = getCount(COUNT_CELLS_MARKED);
1087
1088 runtime->metrics().GC_PREPARE_MS(prepareTotal);
1089 runtime->metrics().GC_MARK_MS(markNotGrayOrWeak);
1090 if (markTotal >= TimeDuration::FromMicroseconds(1)) {
1091 double markRate = double(markCount) / t(markTotal);
1092 runtime->metrics().GC_MARK_RATE_2(uint32_t(markRate));
1093 }
1094 runtime->metrics().GC_SWEEP_MS(phaseTimes[Phase::SWEEP]);
1095 if (gc->didCompactZones()) {
1096 runtime->metrics().GC_COMPACT_MS(phaseTimes[Phase::COMPACT]);
1097 }
1098 runtime->metrics().GC_MARK_ROOTS_US(markRootsTotal);
1099 runtime->metrics().GC_MARK_GRAY_MS_2(markGrayTotal);
1100 runtime->metrics().GC_MARK_WEAK_MS(markWeakTotal);
1101 runtime->metrics().GC_NON_INCREMENTAL(nonincremental());
1102 if (nonincremental()) {
1103 runtime->metrics().GC_NON_INCREMENTAL_REASON(
1104 uint32_t(nonincrementalReason_));
1105 }
1106
1107 #ifdef DEBUG
1108 // Reset happens non-incrementally, so only the last slice can be reset.
1109 for (size_t i = 0; i < slices_.length() - 1; i++) {
1110 MOZ_ASSERT(!slices_[i].wasReset());
1111 }
1112 #endif
1113 const auto& lastSlice = slices_.back();
1114 runtime->metrics().GC_RESET(lastSlice.wasReset());
1115 if (lastSlice.wasReset()) {
1116 runtime->metrics().GC_RESET_REASON(uint32_t(lastSlice.resetReason));
1117 }
1118
1119 TimeDuration total, longest;
1120 gcDuration(&total, &longest);
1121
1122 runtime->metrics().GC_MS(total);
1123 runtime->metrics().GC_MAX_PAUSE_MS_2(longest);
1124
1125 const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
1126 runtime->metrics().GC_MMU_50(mmu50 * 100.0);
1127
1128 // Record scheduling telemetry for the main runtime but not for workers, which
1129 // are scheduled differently.
1130 if (!runtime->parentRuntime && timeSinceLastGC) {
1131 runtime->metrics().GC_TIME_BETWEEN_S(timeSinceLastGC);
1132 if (!nonincremental()) {
1133 runtime->metrics().GC_SLICE_COUNT(slices_.length());
1134 }
1135 }
1136
1137 if (!lastSlice.wasReset() && preCollectedGCHeapBytes != 0) {
1138 size_t bytesSurvived = 0;
1139 for (ZonesIter zone(runtime, WithAtoms); !zone.done(); zone.next()) {
1140 if (zone->wasCollected()) {
1141 bytesSurvived += zone->gcHeapSize.retainedBytes();
1142 }
1143 }
1144
1145 MOZ_ASSERT(preCollectedGCHeapBytes >= bytesSurvived);
1146 double survivalRate =
1147 100.0 * double(bytesSurvived) / double(preCollectedGCHeapBytes);
1148 runtime->metrics().GC_TENURED_SURVIVAL_RATE(survivalRate);
1149
1150 // Calculate 'effectiveness' in MB / second, on main thread only for now.
1151 if (!runtime->parentRuntime) {
1152 size_t bytesFreed = preCollectedGCHeapBytes - bytesSurvived;
1153 TimeDuration clampedTotal =
1154 TimeDuration::Max(total, TimeDuration::FromMilliseconds(1));
1155 double effectiveness =
1156 (double(bytesFreed) / BYTES_PER_MB) / clampedTotal.ToSeconds();
1157 runtime->metrics().GC_EFFECTIVENESS(uint32_t(effectiveness));
1158 }
1159 }
1160
1161 // Parallel marking stats.
1162 bool usedParallelMarking = false;
1163 if (gc->isParallelMarkingEnabled()) {
1164 TimeDuration wallTime = SumPhase(PhaseKind::PARALLEL_MARK, phaseTimes);
1165 TimeDuration parallelMarkTime =
1166 sumTotalParallelTime(PhaseKind::PARALLEL_MARK_MARK);
1167 TimeDuration parallelRunTime =
1168 parallelMarkTime + sumTotalParallelTime(PhaseKind::PARALLEL_MARK_OTHER);
1169 usedParallelMarking = wallTime && parallelMarkTime;
1170 if (usedParallelMarking) {
1171 uint32_t threadCount = gc->markers.length();
1172 double speedup = parallelMarkTime / wallTime;
1173 double utilization = parallelRunTime / (wallTime * threadCount);
1174 runtime->metrics().GC_PARALLEL_MARK_SPEEDUP(uint32_t(speedup * 100.0));
1175 runtime->metrics().GC_PARALLEL_MARK_UTILIZATION(
1176 std::clamp(utilization * 100.0, 0.0, 100.0));
1177 runtime->metrics().GC_PARALLEL_MARK_INTERRUPTIONS(
1178 getCount(COUNT_PARALLEL_MARK_INTERRUPTIONS));
1179 }
1180 }
1181 runtime->metrics().GC_PARALLEL_MARK(usedParallelMarking);
1182 }
1183
1184 void Statistics::beginNurseryCollection() {
1185 count(COUNT_MINOR_GC);
1186 startingMinorGCNumber = gc->minorGCCount();
1187 }
1188
1189 void Statistics::endNurseryCollection() { tenuredAllocsSinceMinorGC = 0; }
1190
1191 Statistics::SliceData::SliceData(const SliceBudget& budget,
1192 Maybe<Trigger> trigger, JS::GCReason reason,
1193 TimeStamp start, size_t startFaults,
1194 gc::State initialState)
1195 : budget(budget),
1196 reason(reason),
1197 trigger(trigger),
1198 initialState(initialState),
1199 start(start),
1200 startFaults(startFaults) {}
1201
1202 TimeDuration Statistics::SliceData::duration() const {
1203 return TimeBetween(start, end);
1204 }
1205
1206 void Statistics::beginSlice(const ZoneGCStats& zoneStats, JS::GCOptions options,
1207 const SliceBudget& budget, JS::GCReason reason,
1208 bool budgetWasIncreased) {
1209 MOZ_ASSERT(phaseStack.empty() ||
1210 (phaseStack.length() == 1 && phaseStack[0] == Phase::MUTATOR));
1211
1212 this->zoneStats = zoneStats;
1213
1214 TimeStamp currentTime = TimeStamp::Now();
1215
1216 bool first = !gc->isIncrementalGCInProgress();
1217 if (first) {
1218 beginGC(options, currentTime);
1219 }
1220
1221 JSRuntime* runtime = gc->rt;
1222 if (!runtime->parentRuntime && !slices_.empty()) {
1223 TimeDuration timeSinceLastSlice =
1224 TimeBetween(slices_.back().end, currentTime);
1225 runtime->metrics().GC_TIME_BETWEEN_SLICES_MS(timeSinceLastSlice);
1226 }
1227
1228 Maybe<Trigger> trigger = recordedTrigger;
1229 recordedTrigger.reset();
1230
1231 if (!slices_.emplaceBack(budget, trigger, reason, currentTime,
1232 GetPageFaultCount(), gc->state())) {
1233 // If we are OOM, set a flag to indicate we have missing slice data.
1234 aborted = true;
1235 return;
1236 }
1237
1238 runtime->metrics().GC_REASON_2(uint32_t(reason));
1239 runtime->metrics().GC_BUDGET_WAS_INCREASED(budgetWasIncreased);
1240
1241 // Slice callbacks should only fire for the outermost level.
1242 if (sliceCallback) {
1243 JSContext* cx = context();
1244 JS::GCDescription desc(!gc->fullGCRequested, false, options, reason);
1245 if (first) {
1246 (*sliceCallback)(cx, JS::GC_CYCLE_BEGIN, desc);
1247 }
1248 (*sliceCallback)(cx, JS::GC_SLICE_BEGIN, desc);
1249 }
1250
1251 log("begin slice");
1252 }
1253
1254 void Statistics::endSlice() {
1255 MOZ_ASSERT(phaseStack.empty() ||
1256 (phaseStack.length() == 1 && phaseStack[0] == Phase::MUTATOR));
1257
1258 if (!aborted) {
1259 auto& slice = slices_.back();
1260 slice.end = TimeStamp::Now();
1261 slice.endFaults = GetPageFaultCount();
1262 slice.finalState = gc->state();
1263
1264 log("end slice");
1265
1266 sendSliceTelemetry(slice);
1267
1268 sliceCount_++;
1269
1270 totalGCTime_ += slice.duration();
1271 }
1272
1273 bool last = !gc->isIncrementalGCInProgress();
1274 if (last) {
1275 if (gcTimerFile) {
1276 printStats();
1277 }
1278
1279 if (!aborted) {
1280 endGC();
1281 }
1282 }
1283
1284 if (!aborted) {
1285 if (ShouldPrintProfile(gc->rt, enableProfiling_, profileWorkers_,
1286 profileThreshold_, slices_.back().duration())) {
1287 printSliceProfile();
1288 }
1289
1290 if (enableBufferAllocStats_ && gc->rt->isMainRuntime()) {
1291 maybePrintProfileHeaders();
1292 BufferAllocator::printStats(gc, creationTime(), true, profileFile());
1293 }
1294
1295 // Slice callbacks should only fire for the outermost level.
1296 if (sliceCallback) {
1297 JSContext* cx = context();
1298 JS::GCDescription desc(!gc->fullGCRequested, last, gcOptions,
1299 slices_.back().reason);
1300 (*sliceCallback)(cx, JS::GC_SLICE_END, desc);
1301 if (last) {
1302 (*sliceCallback)(cx, JS::GC_CYCLE_END, desc);
1303 }
1304 }
1305 }
1306
1307 // Do this after the slice callback since it uses these values.
1308 if (last) {
1309 for (auto& count : counts) {
1310 count = 0;
1311 }
1312
1313 // Clear the timers at the end of a GC, preserving the data for
1314 // PhaseKind::MUTATOR.
1315 auto mutatorStartTime = phaseStartTimes[Phase::MUTATOR];
1316 auto mutatorTime = phaseTimes[Phase::MUTATOR];
1317
1318 phaseStartTimes = PhaseTimeStamps();
1319 #ifdef DEBUG
1320 phaseEndTimes = PhaseTimeStamps();
1321 #endif
1322 phaseTimes = PhaseTimes();
1323
1324 phaseStartTimes[Phase::MUTATOR] = mutatorStartTime;
1325 phaseTimes[Phase::MUTATOR] = mutatorTime;
1326 }
1327
1328 aborted = false;
1329 }
1330
1331 void Statistics::sendSliceTelemetry(const SliceData& slice) {
1332 JSRuntime* runtime = gc->rt;
1333 TimeDuration sliceTime = slice.duration();
1334 runtime->metrics().GC_SLICE_MS(sliceTime);
1335
1336 if (slice.budget.isTimeBudget()) {
1337 TimeDuration budgetDuration = slice.budget.timeBudgetDuration();
1338 runtime->metrics().GC_BUDGET_MS_2(budgetDuration);
1339
1340 if (IsCurrentlyAnimating(runtime->lastAnimationTime, slice.end)) {
1341 runtime->metrics().GC_ANIMATION_MS(sliceTime);
1342 }
1343
1344 bool wasLongSlice = false;
1345 if (sliceTime > budgetDuration) {
1346 // Record how long we went over budget.
1347 TimeDuration overrun = sliceTime - budgetDuration;
1348 runtime->metrics().GC_BUDGET_OVERRUN(overrun);
1349
1350 // Long GC slices are those that go 50% or 5ms over their budget.
1351 wasLongSlice = (overrun > TimeDuration::FromMilliseconds(5)) ||
1352 (overrun > (budgetDuration / int64_t(2)));
1353
1354 // Record the longest phase in any long slice.
1355 if (wasLongSlice) {
1356 PhaseKind longest = LongestPhaseSelfTimeInMajorGC(slice.phaseTimes);
1357 reportLongestPhaseInMajorGC(
1358 longest,
1359 [runtime](auto sample) {
1360 runtime->metrics().GC_SLOW_PHASE(sample);
1361 },
1362 [runtime](auto sample) {
1363 runtime->metrics().GC_GLEAN_SLOW_PHASE(sample);
1364 });
1365
1366 // If the longest phase was waiting for parallel tasks then record the
1367 // longest task.
1368 if (longest == PhaseKind::JOIN_PARALLEL_TASKS) {
1369 PhaseKind longestParallel =
1370 FindLongestPhaseKind(slice.maxParallelTimes);
1371 reportLongestPhaseInMajorGC(
1372 longestParallel,
1373 [runtime](auto sample) {
1374 runtime->metrics().GC_SLOW_TASK(sample);
1375 },
1376 [runtime](auto sample) {
1377 runtime->metrics().GC_GLEAN_SLOW_TASK(sample);
1378 });
1379 }
1380 }
1381 }
1382
1383 // Record `wasLongSlice` for all TimeBudget slices.
1384 runtime->metrics().GC_SLICE_WAS_LONG(wasLongSlice);
1385 }
1386 }
1387
1388 template <typename LegacyFn, typename GleanFn>
1389 void Statistics::reportLongestPhaseInMajorGC(PhaseKind longest,
1390 LegacyFn legacyReportFn,
1391 GleanFn gleanReportFn) {
1392 if (longest != PhaseKind::NONE) {
1393 uint8_t bucket = phaseKinds[longest].telemetryBucket;
1394 legacyReportFn(bucket);
1395 gleanReportFn(static_cast<uint32_t>(longest));
1396 }
1397 }
1398
1399 bool Statistics::startTimingMutator() {
1400 if (phaseStack.length() != 0) {
1401 // Should only be called from outside of GC.
1402 MOZ_ASSERT(phaseStack.length() == 1);
1403 MOZ_ASSERT(phaseStack[0] == Phase::MUTATOR);
1404 return false;
1405 }
1406
1407 MOZ_ASSERT(suspendedPhases.empty());
1408
1409 timedGCTime = TimeDuration::Zero();
1410 phaseStartTimes[Phase::MUTATOR] = TimeStamp();
1411 phaseTimes[Phase::MUTATOR] = TimeDuration::Zero();
1412 timedGCStart = TimeStamp();
1413
1414 beginPhase(PhaseKind::MUTATOR);
1415 return true;
1416 }
1417
1418 bool Statistics::stopTimingMutator(double& mutator_ms, double& gc_ms) {
1419 // This should only be called from outside of GC, while timing the mutator.
1420 if (phaseStack.length() != 1 || phaseStack[0] != Phase::MUTATOR) {
1421 return false;
1422 }
1423
1424 endPhase(PhaseKind::MUTATOR);
1425 mutator_ms = t(phaseTimes[Phase::MUTATOR]);
1426 gc_ms = t(timedGCTime);
1427
1428 return true;
1429 }
1430
1431 void Statistics::suspendPhases(PhaseKind suspension) {
1432 MOZ_ASSERT(suspension == PhaseKind::EXPLICIT_SUSPENSION ||
1433 suspension == PhaseKind::IMPLICIT_SUSPENSION);
1434 while (!phaseStack.empty()) {
1435 MOZ_ASSERT(suspendedPhases.length() < MAX_SUSPENDED_PHASES);
1436 Phase parent = phaseStack.back();
1437 suspendedPhases.infallibleAppend(parent);
1438 recordPhaseEnd(parent);
1439 }
1440 suspendedPhases.infallibleAppend(lookupChildPhase(suspension));
1441 }
1442
1443 void Statistics::resumePhases() {
1444 MOZ_ASSERT(suspendedPhases.back() == Phase::EXPLICIT_SUSPENSION ||
1445 suspendedPhases.back() == Phase::IMPLICIT_SUSPENSION);
1446 suspendedPhases.popBack();
1447
1448 while (!suspendedPhases.empty() &&
1449 suspendedPhases.back() != Phase::EXPLICIT_SUSPENSION &&
1450 suspendedPhases.back() != Phase::IMPLICIT_SUSPENSION) {
1451 Phase resumePhase = suspendedPhases.popCopy();
1452 if (resumePhase == Phase::MUTATOR) {
1453 timedGCTime += TimeBetween(timedGCStart, TimeStamp::Now());
1454 }
1455 recordPhaseBegin(resumePhase);
1456 }
1457 }
1458
1459 void Statistics::beginPhase(PhaseKind phaseKind) {
1460 // No longer timing these phases. We should never see these.
1461 MOZ_ASSERT(phaseKind != PhaseKind::GC_BEGIN &&
1462 phaseKind != PhaseKind::GC_END);
1463
1464 // PhaseKind::MUTATOR is suspended while performing GC.
1465 if (currentPhase() == Phase::MUTATOR) {
1466 suspendPhases(PhaseKind::IMPLICIT_SUSPENSION);
1467 }
1468
1469 recordPhaseBegin(lookupChildPhase(phaseKind));
1470 }
1471
1472 void Statistics::recordPhaseBegin(Phase phase) {
1473 MOZ_ASSERT(CurrentThreadCanAccessRuntime(gc->rt));
1474
1475 // Guard against any other re-entry.
1476 MOZ_ASSERT(!phaseStartTimes[phase]);
1477
1478 MOZ_ASSERT(phaseStack.length() < MAX_PHASE_NESTING);
1479
1480 Phase current = currentPhase();
1481 MOZ_ASSERT(phases[phase].parent == current);
1482
1483 TimeStamp now = TimeStamp::Now();
1484
1485 if (current != Phase::NONE) {
1486 MOZ_ASSERT(now >= phaseStartTimes[currentPhase()],
1487 "Inconsistent time data; see bug 1400153");
1488 if (now < phaseStartTimes[currentPhase()]) {
1489 now = phaseStartTimes[currentPhase()];
1490 aborted = true;
1491 }
1492 }
1493
1494 phaseStack.infallibleAppend(phase);
1495 phaseStartTimes[phase] = now;
1496 log("begin: %s", phases[phase].path);
1497 }
1498
1499 void Statistics::recordPhaseEnd(Phase phase) {
1500 MOZ_ASSERT(CurrentThreadCanAccessRuntime(gc->rt));
1501
1502 MOZ_ASSERT(phaseStartTimes[phase]);
1503
1504 TimeStamp now = TimeStamp::Now();
1505
1506 // Make sure this phase ends after it starts.
1507 MOZ_ASSERT(now >= phaseStartTimes[phase],
1508 "Inconsistent time data; see bug 1400153");
1509
1510 #ifdef DEBUG
1511 // Make sure this phase ends after all of its children. Note that some
1512 // children might not have run in this instance, in which case they will
1513 // have run in a previous instance of this parent or not at all.
1514 for (Phase kid = phases[phase].firstChild; kid != Phase::NONE;
1515 kid = phases[kid].nextSibling) {
1516 if (phaseEndTimes[kid].IsNull()) {
1517 continue;
1518 }
1519 if (phaseEndTimes[kid] > now) {
1520 fprintf(stderr,
1521 "Parent %s ended at %.3fms, before child %s ended at %.3fms?\n",
1522 phases[phase].name,
1523 t(TimeBetween(TimeStamp::FirstTimeStamp(), now)),
1524 phases[kid].name,
1525 t(TimeBetween(TimeStamp::FirstTimeStamp(), phaseEndTimes[kid])));
1526 }
1527 MOZ_ASSERT(phaseEndTimes[kid] <= now,
1528 "Inconsistent time data; see bug 1400153");
1529 }
1530 #endif
1531
1532 if (now < phaseStartTimes[phase]) {
1533 now = phaseStartTimes[phase];
1534 aborted = true;
1535 }
1536
1537 if (phase == Phase::MUTATOR) {
1538 timedGCStart = now;
1539 }
1540
1541 phaseStack.popBack();
1542
1543 TimeDuration t = TimeBetween(phaseStartTimes[phase], now);
1544 if (!slices_.empty()) {
1545 slices_.back().phaseTimes[phase] += t;
1546 }
1547 phaseTimes[phase] += t;
1548 phaseStartTimes[phase] = TimeStamp();
1549
1550 #ifdef DEBUG
1551 phaseEndTimes[phase] = now;
1552 log("end: %s", phases[phase].path);
1553 #endif
1554 }
1555
1556 void Statistics::endPhase(PhaseKind phaseKind) {
1557 Phase phase = currentPhase();
1558 MOZ_ASSERT(phase != Phase::NONE);
1559 MOZ_ASSERT(phases[phase].phaseKind == phaseKind);
1560
1561 recordPhaseEnd(phase);
1562
1563 // When emptying the stack, we may need to return to timing the mutator
1564 // (PhaseKind::MUTATOR).
1565 if (phaseStack.empty() && !suspendedPhases.empty() &&
1566 suspendedPhases.back() == Phase::IMPLICIT_SUSPENSION) {
1567 resumePhases();
1568 }
1569 }
1570
1571 void Statistics::recordParallelPhase(PhaseKind phaseKind,
1572 TimeDuration duration) {
1573 MOZ_ASSERT(CurrentThreadCanAccessRuntime(gc->rt));
1574
1575 if (slices_.empty()) {
1576 return;
1577 }
1578
1579 slices_.back().totalParallelTimes[phaseKind] += duration;
1580
1581 // Also record the maximum task time for each phase. Don't record times for
1582 // parent phases.
1583 TimeDuration& maxTime = slices_.back().maxParallelTimes[phaseKind];
1584 maxTime = std::max(maxTime, duration);
1585 }
1586
1587 TimeStamp Statistics::beginSCC() { return TimeStamp::Now(); }
1588
1589 void Statistics::endSCC(unsigned scc, TimeStamp start) {
1590 if (scc >= sccTimes.length() && !sccTimes.resize(scc + 1)) {
1591 return;
1592 }
1593
1594 sccTimes[scc] += TimeBetween(start, TimeStamp::Now());
1595 }
1596
1597 /*
1598 * Calculate minimum mutator utilization for previous incremental GC.
1599 *
1600 * MMU (minimum mutator utilization) is a measure of how much garbage collection
1601 * is affecting the responsiveness of the system. MMU measurements are given
1602 * with respect to a certain window size. If we report MMU(50ms) = 80%, then
1603 * that means that, for any 50ms window of time, at least 80% of the window is
1604 * devoted to the mutator. In other words, the GC is running for at most 20% of
1605 * the window, or 10ms. The GC can run multiple slices during the 50ms window
1606 * as long as the total time it spends is at most 10ms.
1607 */
1608 double Statistics::computeMMU(TimeDuration window) const {
1609 MOZ_ASSERT(window > TimeDuration::Zero());
1610 MOZ_ASSERT(!slices().empty());
1611
1612 // Examine all ranges of slices from |startIndex| to |endIndex| inclusive
1613 // whose timestamps span less than the window duration. The time spent in GC
1614 // in each range is stored in |gcInRange| by maintaining a running total. The
1615 // maximum value of this after adjustment to the window size is recorded in
1616 // |maxGCInWindow|.
1617
1618 size_t startIndex = 0;
1619 const SliceData* startSlice = &sliceAt(startIndex);
1620 TimeDuration gcInRange = startSlice->duration();
1621 if (gcInRange >= window) {
1622 return 0.0;
1623 }
1624
1625 TimeDuration maxGCInWindow = gcInRange;
1626
1627 for (size_t endIndex = 1; endIndex < slices().length(); endIndex++) {
1628 const SliceData* endSlice = &sliceAt(endIndex);
1629 if (endSlice->duration() >= window) {
1630 return 0.0;
1631 }
1632
1633 gcInRange += endSlice->duration();
1634
1635 while (TimeBetween(startSlice->end, endSlice->end) >= window) {
1636 gcInRange -= startSlice->duration();
1637 ++startIndex;
1638 MOZ_ASSERT(startIndex <= endIndex);
1639 startSlice = &sliceAt(startIndex);
1640 }
1641
1642 TimeDuration totalInRange = TimeBetween(startSlice->start, endSlice->end);
1643 MOZ_ASSERT(gcInRange <= totalInRange);
1644
1645 TimeDuration gcInWindow = gcInRange;
1646 if (totalInRange > window) {
1647 gcInWindow -= (totalInRange - window);
1648 }
1649 MOZ_ASSERT(gcInWindow <= window);
1650
1651 if (gcInWindow > maxGCInWindow) {
1652 maxGCInWindow = gcInWindow;
1653 }
1654 }
1655
1656 MOZ_ASSERT(maxGCInWindow >= TimeDuration::Zero());
1657 MOZ_ASSERT(maxGCInWindow <= window);
1658 return (window - maxGCInWindow) / window;
1659 }
1660
1661 void Statistics::maybePrintProfileHeaders() {
1662 static int printedHeader = 0;
1663 if ((printedHeader++ % 200) == 0) {
1664 if (enableProfiling_) {
1665 printProfileHeader();
1666 }
1667 if (gc->nursery().enableProfiling()) {
1668 gc->nursery().printProfileHeader();
1669 }
1670 if (enableBufferAllocStats_) {
1671 BufferAllocator::printStatsHeader(profileFile());
1672 }
1673 }
1674 }
1675
1676 // The following macros define GC profile metadata fields that are printed
1677 // before the timing information defined by FOR_EACH_GC_PROFILE_TIME.
1678
1679 #define FOR_EACH_GC_PROFILE_COMMON_METADATA(_) \
1680 _("PID", 7, "%7zu", pid) \
1681 _("Runtime", 14, "0x%12p", runtime)
1682
1683 #define FOR_EACH_GC_PROFILE_SLICE_METADATA(_) \
1684 _("Timestamp", 10, "%10.6f", timestamp.ToSeconds()) \
1685 _("Reason", 20, "%-20.20s", reason) \
1686 _("States", 6, "%6s", formatGCStates(slice)) \
1687 _("FSNR", 4, "%4s", formatGCFlags(slice)) \
1688 _("SizeKB", 8, "%8zu", gcSizeKB) \
1689 _("MllcKB", 8, "%8zu", mallocSizeKB) \
1690 _("Zs", 3, "%3zu", zoneCount) \
1691 _("Cs", 3, "%3zu", compartmentCount) \
1692 _("Rs", 3, "%3zu", realmCount) \
1693 _("Budget", 6, "%6s", formatBudget(slice))
1694
1695 #define FOR_EACH_GC_PROFILE_METADATA(_) \
1696 FOR_EACH_GC_PROFILE_COMMON_METADATA(_) \
1697 FOR_EACH_GC_PROFILE_SLICE_METADATA(_)
1698
1699 void Statistics::printProfileHeader() {
1700 Sprinter sprinter;
1701 if (!sprinter.init()) {
1702 return;
1703 }
1704 sprinter.put(MajorGCProfilePrefix);
1705
1706 #define PRINT_METADATA_NAME(name, width, _1, _2) \
1707 sprinter.printf(" %-*s", width, name);
1708
1709 FOR_EACH_GC_PROFILE_METADATA(PRINT_METADATA_NAME)
1710 #undef PRINT_METADATA_NAME
1711
1712 #define PRINT_PROFILE_NAME(_1, text, _2) sprinter.printf(" %-6.6s", text);
1713
1714 FOR_EACH_GC_PROFILE_TIME(PRINT_PROFILE_NAME)
1715 #undef PRINT_PROFILE_NAME
1716
1717 sprinter.put("\n");
1718
1719 JS::UniqueChars str = sprinter.release();
1720 if (!str) {
1721 return;
1722 }
1723 fputs(str.get(), profileFile());
1724 }
1725
1726 static TimeDuration SumAllPhaseKinds(const Statistics::PhaseKindTimes& times) {
1727 TimeDuration sum;
1728 for (PhaseKind kind : AllPhaseKinds()) {
1729 sum += times[kind];
1730 }
1731 return sum;
1732 }
1733
1734 void Statistics::printSliceProfile() {
1735 maybePrintProfileHeaders();
1736
1737 const SliceData& slice = slices_.back();
1738 ProfileDurations times = getProfileTimes(slice);
1739 updateTotalProfileTimes(times);
1740
1741 Sprinter sprinter;
1742 if (!sprinter.init()) {
1743 return;
1744 }
1745 sprinter.put(MajorGCProfilePrefix);
1746
1747 size_t pid = getpid();
1748 JSRuntime* runtime = gc->rt;
1749 TimeDuration timestamp = TimeBetween(creationTime(), slice.end);
1750 const char* reason = ExplainGCReason(slice.reason);
1751 size_t gcSizeKB = gc->heapSize.bytes() / 1024;
1752 size_t mallocSizeKB = getMallocHeapSize() / 1024;
1753 size_t zoneCount = zoneStats.zoneCount;
1754 size_t compartmentCount = zoneStats.compartmentCount;
1755 size_t realmCount = zoneStats.realmCount;
1756
1757 #define PRINT_FIELD_VALUE(_1, _2, format, value) \
1758 sprinter.printf(" " format, value);
1759
1760 FOR_EACH_GC_PROFILE_METADATA(PRINT_FIELD_VALUE)
1761 #undef PRINT_FIELD_VALUE
1762
1763 printProfileTimes(times, sprinter);
1764
1765 JS::UniqueChars str = sprinter.release();
1766 if (!str) {
1767 return;
1768 }
1769 fputs(str.get(), profileFile());
1770 }
1771
1772 size_t Statistics::getMallocHeapSize() {
1773 size_t bytes = 0;
1774 for (AllZonesIter zone(gc); !zone.done(); zone.next()) {
1775 bytes += zone->mallocHeapSize.bytes();
1776 }
1777 return bytes;
1778 }
1779
1780 Statistics::ProfileDurations Statistics::getProfileTimes(
1781 const SliceData& slice) const {
1782 ProfileDurations times;
1783
1784 times[ProfileKey::Total] = slice.duration();
1785 times[ProfileKey::Background] = SumAllPhaseKinds(slice.totalParallelTimes);
1786
1787 #define GET_PROFILE_TIME(name, text, phase) \
1788 if (phase != PhaseKind::NONE) { \
1789 times[ProfileKey::name] = SumPhase(phase, slice.phaseTimes); \
1790 }
1791 FOR_EACH_GC_PROFILE_TIME(GET_PROFILE_TIME)
1792 #undef GET_PROFILE_TIME
1793
1794 return times;
1795 }
1796
1797 void Statistics::updateTotalProfileTimes(const ProfileDurations& times) {
1798 #define UPDATE_PROFILE_TIME(name, _, phase) \
1799 totalTimes_[ProfileKey::name] += times[ProfileKey::name];
1800 FOR_EACH_GC_PROFILE_TIME(UPDATE_PROFILE_TIME)
1801 #undef UPDATE_PROFILE_TIME
1802 }
1803
1804 const char* Statistics::formatGCStates(const SliceData& slice) {
1805 DebugOnly<int> r =
1806 SprintfLiteral(formatBuffer_, "%1d -> %1d", int(slice.initialState),
1807 int(slice.finalState));
1808 MOZ_ASSERT(r > 0 && r < FormatBufferLength);
1809 return formatBuffer_;
1810 }
1811
1812 const char* Statistics::formatGCFlags(const SliceData& slice) {
1813 bool fullGC = gc->fullGCRequested;
1814 bool shrinkingGC = gcOptions == JS::GCOptions::Shrink;
1815 bool nonIncrementalGC = nonincrementalReason_ != GCAbortReason::None;
1816 bool wasReset = slice.resetReason != GCAbortReason::None;
1817
1818 MOZ_ASSERT(FormatBufferLength >= 5);
1819 formatBuffer_[0] = fullGC ? 'F' : ' ';
1820 formatBuffer_[1] = shrinkingGC ? 'S' : ' ';
1821 formatBuffer_[2] = nonIncrementalGC ? 'N' : ' ';
1822 formatBuffer_[3] = wasReset ? 'R' : ' ';
1823 formatBuffer_[4] = '\0';
1824
1825 return formatBuffer_;
1826 }
1827
1828 const char* Statistics::formatBudget(const SliceData& slice) {
1829 if (nonincrementalReason_ != GCAbortReason::None ||
1830 !slice.budget.isTimeBudget()) {
1831 formatBuffer_[0] = '\0';
1832 return formatBuffer_;
1833 }
1834
1835 DebugOnly<int> r =
1836 SprintfLiteral(formatBuffer_, "%6" PRIi64, slice.budget.timeBudget());
1837 MOZ_ASSERT(r > 0 && r < FormatBufferLength);
1838 return formatBuffer_;
1839 }
1840
1841 /* static */
1842 void Statistics::printProfileTimes(const ProfileDurations& times,
1843 Sprinter& sprinter) {
1844 for (auto time : times) {
1845 int64_t millis = int64_t(time.ToMilliseconds());
1846 sprinter.printf(" %6" PRIi64, millis);
1847 }
1848
1849 sprinter.put("\n");
1850 }
1851
1852 constexpr size_t SliceMetadataFormatWidth() {
1853 size_t fieldCount = 0;
1854 size_t totalWidth = 0;
1855
1856 #define UPDATE_COUNT_AND_WIDTH(_1, width, _2, _3) \
1857 fieldCount++; \
1858 totalWidth += width;
1859 FOR_EACH_GC_PROFILE_SLICE_METADATA(UPDATE_COUNT_AND_WIDTH)
1860 #undef UPDATE_COUNT_AND_WIDTH
1861
1862 // Add padding between fields.
1863 totalWidth += fieldCount - 1;
1864
1865 return totalWidth;
1866 }
1867
1868 void Statistics::printTotalProfileTimes() {
1869 if (!enableProfiling_) {
1870 return;
1871 }
1872
1873 Sprinter sprinter;
1874 if (!sprinter.init()) {
1875 return;
1876 }
1877 sprinter.put(MajorGCProfilePrefix);
1878
1879 size_t pid = getpid();
1880 JSRuntime* runtime = gc->rt;
1881
1882 #define PRINT_FIELD_VALUE(_1, _2, format, value) \
1883 sprinter.printf(" " format, value);
1884
1885 FOR_EACH_GC_PROFILE_COMMON_METADATA(PRINT_FIELD_VALUE)
1886 #undef PRINT_FIELD_VALUE
1887
1888 // Use whole width of per-slice metadata to print total slices so the profile
1889 // totals that follow line up.
1890 size_t width = SliceMetadataFormatWidth();
1891 sprinter.printf(" %-*s", int(width), formatTotalSlices());
1892 printProfileTimes(totalTimes_, sprinter);
1893
1894 JS::UniqueChars str = sprinter.release();
1895 if (!str) {
1896 return;
1897 }
1898 fputs(str.get(), profileFile());
1899 }
1900
1901 const char* Statistics::formatTotalSlices() {
1902 DebugOnly<int> r = SprintfLiteral(
1903 formatBuffer_, "TOTALS: %7" PRIu64 " slices:", sliceCount_);
1904 MOZ_ASSERT(r > 0 && r < FormatBufferLength);
1905 return formatBuffer_;
1906 }