1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
content / browser / tracing / background_tracing_rule.cc [blame]
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/tracing/background_tracing_rule.h"
#include <limits>
#include <optional>
#include <string>
#include <type_traits>
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/statistics_recorder.h"
#include "base/rand_util.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/strcat.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_id_helper.h"
#include "base/values.h"
#include "components/variations/hashing.h"
#include "content/browser/tracing/background_tracing_manager_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "services/tracing/public/cpp/perfetto/macros.h"
#include "services/tracing/public/mojom/background_tracing_agent.mojom.h"
#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_histogram_sample.pbzero.h"
namespace {
const char kConfigRuleKey[] = "rule";
const char kConfigRuleTriggerNameKey[] = "trigger_name";
const char kConfigRuleTriggerDelay[] = "trigger_delay";
const char kConfigRuleTriggerChance[] = "trigger_chance";
const char kConfigRuleIdKey[] = "rule_id";
const char kConfigIsCrashKey[] = "is_crash";
const char kConfigRuleHistogramNameKey[] = "histogram_name";
const char kConfigRuleHistogramValueOldKey[] = "histogram_value";
const char kConfigRuleHistogramValue1Key[] = "histogram_lower_value";
const char kConfigRuleHistogramValue2Key[] = "histogram_upper_value";
const char kConfigRuleTypeMonitorNamed[] =
"MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED";
const char kConfigRuleTypeMonitorHistogram[] =
"MONITOR_AND_DUMP_WHEN_SPECIFIC_HISTOGRAM_AND_VALUE";
} // namespace
namespace content {
BackgroundTracingRule::BackgroundTracingRule() = default;
BackgroundTracingRule::~BackgroundTracingRule() {
DCHECK(!installed());
}
void BackgroundTracingRule::Install(RuleTriggeredCallback trigger_callback) {
DCHECK(!installed());
installed_ = true;
trigger_callback_ = std::move(trigger_callback);
if (activation_delay_) {
activation_timer_.Start(FROM_HERE, *activation_delay_,
base::BindOnce(&BackgroundTracingRule::DoInstall,
base::Unretained(this)));
} else {
DoInstall();
}
}
void BackgroundTracingRule::Uninstall() {
if (!installed()) {
return;
}
installed_ = false;
trigger_timer_.Stop();
activation_timer_.Stop();
trigger_callback_.Reset();
DoUninstall();
}
bool BackgroundTracingRule::OnRuleTriggered(std::optional<int32_t> value) {
if (!installed()) {
return false;
}
DCHECK(trigger_callback_);
if (trigger_chance_ < 1.0 && base::RandDouble() > trigger_chance_) {
return false;
}
triggered_value_ = value;
if (delay_) {
trigger_timer_.Start(FROM_HERE, *delay_,
base::BindOnce(base::IgnoreResult(trigger_callback_),
base::Unretained(this)));
return true;
} else {
return trigger_callback_.Run(this);
}
}
base::TimeDelta BackgroundTracingRule::GetTraceDelay() const {
return trigger_delay_;
}
std::string BackgroundTracingRule::GetDefaultRuleId() const {
return "org.chromium.background_tracing.trigger";
}
base::Value::Dict BackgroundTracingRule::ToDict() const {
base::Value::Dict dict;
if (trigger_chance_ < 1.0)
dict.Set(kConfigRuleTriggerChance, trigger_chance_);
if (!trigger_delay_.is_zero()) {
dict.Set(kConfigRuleTriggerDelay,
static_cast<int>(trigger_delay_.InSeconds()));
}
if (rule_id_ != GetDefaultRuleId()) {
dict.Set(kConfigRuleIdKey, rule_id_);
}
if (is_crash_) {
dict.Set(kConfigIsCrashKey, is_crash_);
}
return dict;
}
perfetto::protos::gen::TriggerRule BackgroundTracingRule::ToProtoForTesting()
const {
perfetto::protos::gen::TriggerRule config;
if (trigger_chance_ < 1.0) {
config.set_trigger_chance(trigger_chance_);
}
if (delay_) {
config.set_delay_ms(delay_->InMilliseconds());
}
config.set_name(rule_id_);
return config;
}
void BackgroundTracingRule::GenerateMetadataProto(
BackgroundTracingRule::MetadataProto* out) const {
uint32_t name_hash = variations::HashName(rule_id());
out->set_name_hash(name_hash);
}
void BackgroundTracingRule::Setup(const base::Value::Dict& dict) {
if (auto trigger_chance = dict.FindDouble(kConfigRuleTriggerChance)) {
trigger_chance_ = *trigger_chance;
}
if (auto trigger_delay = dict.FindInt(kConfigRuleTriggerDelay)) {
trigger_delay_ = base::Seconds(*trigger_delay);
}
if (const std::string* rule_id = dict.FindString(kConfigRuleIdKey)) {
rule_id_ = *rule_id;
} else {
rule_id_ = GetDefaultRuleId();
}
if (auto is_crash = dict.FindBool(kConfigIsCrashKey)) {
is_crash_ = *is_crash;
}
}
void BackgroundTracingRule::Setup(
const perfetto::protos::gen::TriggerRule& config) {
if (config.has_trigger_chance()) {
trigger_chance_ = config.trigger_chance();
}
if (config.has_delay_ms()) {
delay_ = base::Milliseconds(config.delay_ms());
}
if (config.has_activation_delay_ms()) {
activation_delay_ = base::Milliseconds(config.activation_delay_ms());
}
if (config.has_name()) {
rule_id_ = config.name();
} else {
rule_id_ = GetDefaultRuleId();
}
}
namespace {
class NamedTriggerRule : public BackgroundTracingRule {
private:
explicit NamedTriggerRule(const std::string& named_event)
: named_event_(named_event) {}
public:
static std::unique_ptr<BackgroundTracingRule> Create(
const base::Value::Dict& dict) {
if (const std::string* trigger_name =
dict.FindString(kConfigRuleTriggerNameKey)) {
return base::WrapUnique<BackgroundTracingRule>(
new NamedTriggerRule(*trigger_name));
}
return nullptr;
}
static std::unique_ptr<BackgroundTracingRule> Create(
const perfetto::protos::gen::TriggerRule& config) {
if (config.has_manual_trigger_name()) {
return base::WrapUnique<BackgroundTracingRule>(
new NamedTriggerRule(config.manual_trigger_name()));
}
return nullptr;
}
void DoInstall() override {
BackgroundTracingManagerImpl::GetInstance().AddNamedTriggerObserver(
named_event_, this);
}
void DoUninstall() override {
BackgroundTracingManagerImpl::GetInstance().RemoveNamedTriggerObserver(
named_event_, this);
}
base::Value::Dict ToDict() const override {
return BackgroundTracingRule::ToDict()
.Set(kConfigRuleKey, kConfigRuleTypeMonitorNamed)
.Set(kConfigRuleTriggerNameKey, named_event_.c_str());
}
perfetto::protos::gen::TriggerRule ToProtoForTesting() const override {
perfetto::protos::gen::TriggerRule config =
BackgroundTracingRule::ToProtoForTesting();
config.set_manual_trigger_name(named_event_);
return config;
}
void GenerateMetadataProto(
BackgroundTracingRule::MetadataProto* out) const override {
DCHECK(out);
BackgroundTracingRule::GenerateMetadataProto(out);
out->set_trigger_type(MetadataProto::MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED);
auto* named_rule = out->set_named_rule();
if (named_event_ == "startup-config") {
named_rule->set_event_type(MetadataProto::NamedRule::STARTUP);
} else if (named_event_ == "navigation-config") {
named_rule->set_event_type(MetadataProto::NamedRule::NAVIGATION);
} else if (named_event_ == "session-restore-config") {
named_rule->set_event_type(MetadataProto::NamedRule::SESSION_RESTORE);
} else if (named_event_ == "reached-code-config") {
named_rule->set_event_type(MetadataProto::NamedRule::REACHED_CODE);
} else if (named_event_ ==
BackgroundTracingManager::kContentTriggerConfig) {
named_rule->set_event_type(MetadataProto::NamedRule::CONTENT_TRIGGER);
// TODO(chrisha): Set the |content_trigger_name_hash|.
} else if (named_event_ == "preemptive_test") {
named_rule->set_event_type(MetadataProto::NamedRule::TEST_RULE);
}
}
protected:
std::string GetDefaultRuleId() const override {
return base::StrCat({"org.chromium.background_tracing.", named_event_});
}
private:
std::string named_event_;
};
class HistogramRule : public BackgroundTracingRule,
public BackgroundTracingManagerImpl::AgentObserver {
private:
HistogramRule(const std::string& histogram_name,
int histogram_lower_value,
int histogram_upper_value)
: histogram_name_(histogram_name),
histogram_lower_value_(histogram_lower_value),
histogram_upper_value_(histogram_upper_value) {}
public:
static std::unique_ptr<BackgroundTracingRule> Create(
const base::Value::Dict& dict) {
const std::string* histogram_name =
dict.FindString(kConfigRuleHistogramNameKey);
if (!histogram_name)
return nullptr;
std::optional<int> histogram_lower_value =
dict.FindInt(kConfigRuleHistogramValue1Key);
if (!histogram_lower_value) {
// Check for the old naming.
histogram_lower_value = dict.FindInt(kConfigRuleHistogramValueOldKey);
if (!histogram_lower_value)
return nullptr;
}
int histogram_upper_value = dict.FindInt(kConfigRuleHistogramValue2Key)
.value_or(std::numeric_limits<int>::max());
if (*histogram_lower_value > histogram_upper_value)
return nullptr;
std::unique_ptr<BackgroundTracingRule> rule(new HistogramRule(
*histogram_name, *histogram_lower_value, histogram_upper_value));
return rule;
}
static std::unique_ptr<BackgroundTracingRule> Create(
const perfetto::protos::gen::TriggerRule& config) {
DCHECK(config.has_histogram());
if (!config.histogram().has_histogram_name() ||
!config.histogram().has_min_value()) {
return nullptr;
}
int histogram_lower_value = config.histogram().min_value();
int histogram_upper_value = std::numeric_limits<int>::max();
if (config.histogram().has_max_value()) {
histogram_upper_value = config.histogram().max_value();
}
if (histogram_lower_value > histogram_upper_value) {
return nullptr;
}
return base::WrapUnique(
new HistogramRule(config.histogram().histogram_name(),
histogram_lower_value, histogram_upper_value));
}
~HistogramRule() override = default;
// BackgroundTracingRule implementation
void DoInstall() override {
histogram_sample_callback_.emplace(
histogram_name_,
base::BindRepeating(&HistogramRule::OnHistogramChangedCallback,
base::Unretained(this), histogram_lower_value_,
histogram_upper_value_));
BackgroundTracingManagerImpl::GetInstance().AddNamedTriggerObserver(
rule_id(), this);
BackgroundTracingManagerImpl::GetInstance().AddAgentObserver(this);
}
void DoUninstall() override {
histogram_sample_callback_.reset();
BackgroundTracingManagerImpl::GetInstance().RemoveAgentObserver(this);
BackgroundTracingManagerImpl::GetInstance().RemoveNamedTriggerObserver(
rule_id(), this);
}
base::Value::Dict ToDict() const override {
return BackgroundTracingRule::ToDict()
.Set(kConfigRuleKey, kConfigRuleTypeMonitorHistogram)
.Set(kConfigRuleHistogramNameKey, histogram_name_.c_str())
.Set(kConfigRuleHistogramValue1Key, histogram_lower_value_)
.Set(kConfigRuleHistogramValue2Key, histogram_upper_value_);
}
perfetto::protos::gen::TriggerRule ToProtoForTesting() const override {
perfetto::protos::gen::TriggerRule config =
BackgroundTracingRule::ToProtoForTesting();
auto* histogram = config.mutable_histogram();
histogram->set_histogram_name(histogram_name_);
histogram->set_min_value(histogram_lower_value_);
histogram->set_max_value(histogram_upper_value_);
return config;
}
void GenerateMetadataProto(
BackgroundTracingRule::MetadataProto* out) const override {
DCHECK(out);
BackgroundTracingRule::GenerateMetadataProto(out);
out->set_trigger_type(
MetadataProto::MONITOR_AND_DUMP_WHEN_SPECIFIC_HISTOGRAM_AND_VALUE);
auto* rule = out->set_histogram_rule();
rule->set_histogram_name_hash(base::HashMetricName(histogram_name_));
rule->set_histogram_min_trigger(histogram_lower_value_);
rule->set_histogram_max_trigger(histogram_upper_value_);
}
// BackgroundTracingManagerImpl::AgentObserver implementation
void OnAgentAdded(tracing::mojom::BackgroundTracingAgent* agent) override {
agent->SetUMACallback(tracing::mojom::BackgroundTracingRule::New(rule_id()),
histogram_name_, histogram_lower_value_,
histogram_upper_value_);
}
void OnAgentRemoved(tracing::mojom::BackgroundTracingAgent* agent) override {
agent->ClearUMACallback(
tracing::mojom::BackgroundTracingRule::New(rule_id()));
}
void OnHistogramChangedCallback(base::Histogram::Sample reference_lower_value,
base::Histogram::Sample reference_upper_value,
const char* histogram_name,
uint64_t name_hash,
base::Histogram::Sample actual_value) {
DCHECK_EQ(histogram_name, histogram_name_);
if (reference_lower_value > actual_value ||
reference_upper_value < actual_value) {
return;
}
// Add the histogram name and its corresponding value to the trace.
const auto trace_details = [&](perfetto::EventContext ctx) {
perfetto::protos::pbzero::ChromeHistogramSample* new_sample =
ctx.event()->set_chrome_histogram_sample();
new_sample->set_name_hash(base::HashMetricName(histogram_name));
new_sample->set_sample(actual_value);
};
const auto track =
perfetto::Track::FromPointer(this, perfetto::ProcessTrack::Current());
TRACE_EVENT_INSTANT("toplevel", "HistogramSampleTrigger", track,
base::TimeTicks::Now(), trace_details);
OnRuleTriggered(actual_value);
}
protected:
std::string GetDefaultRuleId() const override {
return base::StrCat({"org.chromium.background_tracing.", histogram_name_});
}
private:
std::string histogram_name_;
int histogram_lower_value_;
int histogram_upper_value_;
std::optional<base::StatisticsRecorder::ScopedHistogramSampleObserver>
histogram_sample_callback_;
};
class TimerRule : public BackgroundTracingRule {
private:
explicit TimerRule() = default;
public:
static std::unique_ptr<BackgroundTracingRule> Create(
const perfetto::protos::gen::TriggerRule& config) {
return base::WrapUnique<TimerRule>(new TimerRule());
}
void DoInstall() override { OnRuleTriggered(std::nullopt); }
void DoUninstall() override {}
void GenerateMetadataProto(
BackgroundTracingRule::MetadataProto* out) const override {
DCHECK(out);
BackgroundTracingRule::GenerateMetadataProto(out);
out->set_trigger_type(MetadataProto::TRIGGER_UNSPECIFIED);
}
protected:
std::string GetDefaultRuleId() const override {
return "org.chromium.background_tracing.timer";
}
};
class RepeatingIntervalRule : public BackgroundTracingRule {
private:
RepeatingIntervalRule(base::TimeDelta period, bool randomized)
: period_(period),
randomized_(randomized),
interval_phase_(base::TimeTicks::Now()) {}
public:
static std::unique_ptr<BackgroundTracingRule> Create(
const perfetto::protos::gen::TriggerRule& config) {
DCHECK(config.has_repeating_interval());
const auto& interval = config.repeating_interval();
if (!interval.has_period_ms()) {
return nullptr;
}
return base::WrapUnique<RepeatingIntervalRule>(new RepeatingIntervalRule(
base::Milliseconds(interval.period_ms()), interval.randomized()));
}
void DoInstall() override { ScheduleNextTick(); }
void DoUninstall() override { timer_.Stop(); }
perfetto::protos::gen::TriggerRule ToProtoForTesting() const override {
perfetto::protos::gen::TriggerRule config =
BackgroundTracingRule::ToProtoForTesting();
auto* histogram = config.mutable_repeating_interval();
histogram->set_period_ms(period_.InMilliseconds());
histogram->set_randomized(randomized_);
return config;
}
void GenerateMetadataProto(
BackgroundTracingRule::MetadataProto* out) const override {
DCHECK(out);
BackgroundTracingRule::GenerateMetadataProto(out);
out->set_trigger_type(MetadataProto::TRIGGER_UNSPECIFIED);
}
protected:
std::string GetDefaultRuleId() const override {
return "org.chromium.background_tracing.repeating_interval";
}
private:
base::TimeTicks GetFireTimeForInterval(base::TimeTicks interval_start) const {
if (randomized_) {
return interval_start +
base::Microseconds(base::RandGenerator(period_.InMicroseconds()));
}
return interval_start;
}
base::TimeTicks GetNextIntervalStart(base::TimeTicks now) const {
base::TimeTicks next_interval_start =
now.SnappedToNextTick(interval_phase_, period_);
if (next_interval_start == now) {
return next_interval_start + period_;
}
return next_interval_start;
}
void UpdateNextFireTime(base::TimeTicks now) {
base::TimeTicks next_interval_start = GetNextIntervalStart(now);
base::TimeTicks prev_interval_start = next_interval_start - period_;
// If the previously scheduled fire time is in a past interval, the current
// interval can still fire. Compute a new fire time for the current
// interval and keep it if it hasn't passed, otherwise move on to the next
// interval.
if (randomized_ && (scheduled_fire_time_ < prev_interval_start)) {
scheduled_fire_time_ = GetFireTimeForInterval(prev_interval_start);
if (scheduled_fire_time_ >= now) {
return;
}
}
scheduled_fire_time_ = GetFireTimeForInterval(next_interval_start);
}
void ScheduleNextTick() {
base::TimeTicks now = base::TimeTicks::Now();
// Update the next fire time only if it's in the past.
if (scheduled_fire_time_ <= now) {
UpdateNextFireTime(now);
}
timer_.Start(
FROM_HERE, scheduled_fire_time_,
base::BindOnce(&RepeatingIntervalRule::OnTick, base::Unretained(this)),
base::subtle::DelayPolicy::kFlexibleNoSooner);
}
void OnTick() {
OnRuleTriggered(std::nullopt);
ScheduleNextTick();
}
const base::TimeDelta period_;
const bool randomized_;
const base::TimeTicks interval_phase_;
base::TimeTicks scheduled_fire_time_;
base::DeadlineTimer timer_;
};
} // namespace
std::unique_ptr<BackgroundTracingRule>
BackgroundTracingRule::CreateRuleFromDict(const base::Value::Dict& dict) {
const std::string* type = dict.FindString(kConfigRuleKey);
if (!type)
return nullptr;
std::unique_ptr<BackgroundTracingRule> tracing_rule;
if (*type == kConfigRuleTypeMonitorNamed) {
tracing_rule = NamedTriggerRule::Create(dict);
} else if (*type == kConfigRuleTypeMonitorHistogram) {
tracing_rule = HistogramRule::Create(dict);
}
if (tracing_rule)
tracing_rule->Setup(dict);
return tracing_rule;
}
std::unique_ptr<BackgroundTracingRule> BackgroundTracingRule::Create(
const perfetto::protos::gen::TriggerRule& config) {
std::unique_ptr<BackgroundTracingRule> tracing_rule;
if (config.has_manual_trigger_name()) {
tracing_rule = NamedTriggerRule::Create(config);
} else if (config.has_histogram()) {
tracing_rule = HistogramRule::Create(config);
} else if (config.has_repeating_interval()) {
tracing_rule = RepeatingIntervalRule::Create(config);
} else if (config.has_delay_ms()) {
tracing_rule = TimerRule::Create(config);
} else {
return nullptr;
}
if (tracing_rule) {
tracing_rule->Setup(config);
}
return tracing_rule;
}
bool BackgroundTracingRule::Append(
const std::vector<perfetto::protos::gen::TriggerRule>& configs,
std::vector<std::unique_ptr<BackgroundTracingRule>>& rules) {
for (const auto& rule_config : configs) {
auto rule = BackgroundTracingRule::Create(rule_config);
if (!rule) {
return false;
}
rules.push_back(std::move(rule));
}
return true;
}
} // namespace content