forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrace_log.cc
1742 lines (1512 loc) · 57.7 KB
/
trace_log.cc
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/trace_event/trace_log.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/leak_annotations.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/process/process_metrics.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_id_name_manager.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "base/trace_event/heap_profiler_allocation_context_tracker.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/process_memory_dump.h"
#include "base/trace_event/trace_buffer.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_synthetic_delay.h"
#include "base/trace_event/trace_sampling_thread.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include "base/trace_event/trace_event_etw_export_win.h"
#endif
// The thread buckets for the sampling profiler.
BASE_EXPORT TRACE_EVENT_API_ATOMIC_WORD g_trace_state[3];
namespace base {
namespace internal {
class DeleteTraceLogForTesting {
public:
static void Delete() {
Singleton<trace_event::TraceLog,
LeakySingletonTraits<trace_event::TraceLog>>::OnExit(0);
}
};
} // namespace internal
namespace trace_event {
namespace {
// Controls the number of trace events we will buffer in-memory
// before throwing them away.
const size_t kTraceBufferChunkSize = TraceBufferChunk::kTraceBufferChunkSize;
const size_t kTraceEventVectorBigBufferChunks =
512000000 / kTraceBufferChunkSize;
static_assert(
kTraceEventVectorBigBufferChunks <= TraceBufferChunk::kMaxChunkIndex,
"Too many big buffer chunks");
const size_t kTraceEventVectorBufferChunks = 256000 / kTraceBufferChunkSize;
static_assert(
kTraceEventVectorBufferChunks <= TraceBufferChunk::kMaxChunkIndex,
"Too many vector buffer chunks");
const size_t kTraceEventRingBufferChunks = kTraceEventVectorBufferChunks / 4;
// ECHO_TO_CONSOLE needs a small buffer to hold the unfinished COMPLETE events.
const size_t kEchoToConsoleTraceEventBufferChunks = 256;
const size_t kTraceEventBufferSizeInBytes = 100 * 1024;
const int kThreadFlushTimeoutMs = 3000;
#define MAX_CATEGORY_GROUPS 100
// Parallel arrays g_category_groups and g_category_group_enabled are separate
// so that a pointer to a member of g_category_group_enabled can be easily
// converted to an index into g_category_groups. This allows macros to deal
// only with char enabled pointers from g_category_group_enabled, and we can
// convert internally to determine the category name from the char enabled
// pointer.
const char* g_category_groups[MAX_CATEGORY_GROUPS] = {
"toplevel",
"tracing already shutdown",
"tracing categories exhausted; must increase MAX_CATEGORY_GROUPS",
"__metadata"};
// The enabled flag is char instead of bool so that the API can be used from C.
unsigned char g_category_group_enabled[MAX_CATEGORY_GROUPS] = {0};
// Indexes here have to match the g_category_groups array indexes above.
const int g_category_already_shutdown = 1;
const int g_category_categories_exhausted = 2;
const int g_category_metadata = 3;
const int g_num_builtin_categories = 4;
// Skip default categories.
base::subtle::AtomicWord g_category_index = g_num_builtin_categories;
// The name of the current thread. This is used to decide if the current
// thread name has changed. We combine all the seen thread names into the
// output name for the thread.
LazyInstance<ThreadLocalPointer<const char>>::Leaky g_current_thread_name =
LAZY_INSTANCE_INITIALIZER;
ThreadTicks ThreadNow() {
return ThreadTicks::IsSupported() ? ThreadTicks::Now() : ThreadTicks();
}
template <typename T>
void InitializeMetadataEvent(TraceEvent* trace_event,
int thread_id,
const char* metadata_name,
const char* arg_name,
const T& value) {
if (!trace_event)
return;
int num_args = 1;
unsigned char arg_type;
unsigned long long arg_value;
::trace_event_internal::SetTraceValue(value, &arg_type, &arg_value);
trace_event->Initialize(
thread_id,
TimeTicks(),
ThreadTicks(),
TRACE_EVENT_PHASE_METADATA,
&g_category_group_enabled[g_category_metadata],
metadata_name,
trace_event_internal::kGlobalScope, // scope
trace_event_internal::kNoId, // id
trace_event_internal::kNoId, // bind_id
num_args,
&arg_name,
&arg_type,
&arg_value,
nullptr,
TRACE_EVENT_FLAG_NONE);
}
class AutoThreadLocalBoolean {
public:
explicit AutoThreadLocalBoolean(ThreadLocalBoolean* thread_local_boolean)
: thread_local_boolean_(thread_local_boolean) {
DCHECK(!thread_local_boolean_->Get());
thread_local_boolean_->Set(true);
}
~AutoThreadLocalBoolean() { thread_local_boolean_->Set(false); }
private:
ThreadLocalBoolean* thread_local_boolean_;
DISALLOW_COPY_AND_ASSIGN(AutoThreadLocalBoolean);
};
// Use this function instead of TraceEventHandle constructor to keep the
// overhead of ScopedTracer (trace_event.h) constructor minimum.
void MakeHandle(uint32_t chunk_seq,
size_t chunk_index,
size_t event_index,
TraceEventHandle* handle) {
DCHECK(chunk_seq);
DCHECK(chunk_index <= TraceBufferChunk::kMaxChunkIndex);
DCHECK(event_index < TraceBufferChunk::kTraceBufferChunkSize);
handle->chunk_seq = chunk_seq;
handle->chunk_index = static_cast<uint16_t>(chunk_index);
handle->event_index = static_cast<uint16_t>(event_index);
}
} // namespace
// A helper class that allows the lock to be acquired in the middle of the scope
// and unlocks at the end of scope if locked.
class TraceLog::OptionalAutoLock {
public:
explicit OptionalAutoLock(Lock* lock) : lock_(lock), locked_(false) {}
~OptionalAutoLock() {
if (locked_)
lock_->Release();
}
void EnsureAcquired() {
if (!locked_) {
lock_->Acquire();
locked_ = true;
}
}
private:
Lock* lock_;
bool locked_;
DISALLOW_COPY_AND_ASSIGN(OptionalAutoLock);
};
class TraceLog::ThreadLocalEventBuffer
: public MessageLoop::DestructionObserver,
public MemoryDumpProvider {
public:
explicit ThreadLocalEventBuffer(TraceLog* trace_log);
~ThreadLocalEventBuffer() override;
TraceEvent* AddTraceEvent(TraceEventHandle* handle);
TraceEvent* GetEventByHandle(TraceEventHandle handle) {
if (!chunk_ || handle.chunk_seq != chunk_->seq() ||
handle.chunk_index != chunk_index_) {
return nullptr;
}
return chunk_->GetEventAt(handle.event_index);
}
int generation() const { return generation_; }
private:
// MessageLoop::DestructionObserver
void WillDestroyCurrentMessageLoop() override;
// MemoryDumpProvider implementation.
bool OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) override;
void FlushWhileLocked();
void CheckThisIsCurrentBuffer() const {
DCHECK(trace_log_->thread_local_event_buffer_.Get() == this);
}
// Since TraceLog is a leaky singleton, trace_log_ will always be valid
// as long as the thread exists.
TraceLog* trace_log_;
scoped_ptr<TraceBufferChunk> chunk_;
size_t chunk_index_;
int generation_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalEventBuffer);
};
TraceLog::ThreadLocalEventBuffer::ThreadLocalEventBuffer(TraceLog* trace_log)
: trace_log_(trace_log),
chunk_index_(0),
generation_(trace_log->generation()) {
// ThreadLocalEventBuffer is created only if the thread has a message loop, so
// the following message_loop won't be NULL.
MessageLoop* message_loop = MessageLoop::current();
message_loop->AddDestructionObserver(this);
// This is to report the local memory usage when memory-infra is enabled.
MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "ThreadLocalEventBuffer", ThreadTaskRunnerHandle::Get());
AutoLock lock(trace_log->lock_);
trace_log->thread_message_loops_.insert(message_loop);
}
TraceLog::ThreadLocalEventBuffer::~ThreadLocalEventBuffer() {
CheckThisIsCurrentBuffer();
MessageLoop::current()->RemoveDestructionObserver(this);
MemoryDumpManager::GetInstance()->UnregisterDumpProvider(this);
{
AutoLock lock(trace_log_->lock_);
FlushWhileLocked();
trace_log_->thread_message_loops_.erase(MessageLoop::current());
}
trace_log_->thread_local_event_buffer_.Set(NULL);
}
TraceEvent* TraceLog::ThreadLocalEventBuffer::AddTraceEvent(
TraceEventHandle* handle) {
CheckThisIsCurrentBuffer();
if (chunk_ && chunk_->IsFull()) {
AutoLock lock(trace_log_->lock_);
FlushWhileLocked();
chunk_.reset();
}
if (!chunk_) {
AutoLock lock(trace_log_->lock_);
chunk_ = trace_log_->logged_events_->GetChunk(&chunk_index_);
trace_log_->CheckIfBufferIsFullWhileLocked();
}
if (!chunk_)
return NULL;
size_t event_index;
TraceEvent* trace_event = chunk_->AddTraceEvent(&event_index);
if (trace_event && handle)
MakeHandle(chunk_->seq(), chunk_index_, event_index, handle);
return trace_event;
}
void TraceLog::ThreadLocalEventBuffer::WillDestroyCurrentMessageLoop() {
delete this;
}
bool TraceLog::ThreadLocalEventBuffer::OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) {
if (!chunk_)
return true;
std::string dump_base_name = StringPrintf(
"tracing/thread_%d", static_cast<int>(PlatformThread::CurrentId()));
TraceEventMemoryOverhead overhead;
chunk_->EstimateTraceMemoryOverhead(&overhead);
overhead.DumpInto(dump_base_name.c_str(), pmd);
return true;
}
void TraceLog::ThreadLocalEventBuffer::FlushWhileLocked() {
if (!chunk_)
return;
trace_log_->lock_.AssertAcquired();
if (trace_log_->CheckGeneration(generation_)) {
// Return the chunk to the buffer only if the generation matches.
trace_log_->logged_events_->ReturnChunk(chunk_index_, std::move(chunk_));
}
// Otherwise this method may be called from the destructor, or TraceLog will
// find the generation mismatch and delete this buffer soon.
}
TraceLogStatus::TraceLogStatus() : event_capacity(0), event_count(0) {}
TraceLogStatus::~TraceLogStatus() {}
// static
TraceLog* TraceLog::GetInstance() {
return Singleton<TraceLog, LeakySingletonTraits<TraceLog>>::get();
}
TraceLog::TraceLog()
: mode_(DISABLED),
num_traces_recorded_(0),
event_callback_(0),
dispatching_to_observer_list_(false),
process_sort_index_(0),
process_id_hash_(0),
process_id_(0),
watch_category_(0),
trace_options_(kInternalRecordUntilFull),
sampling_thread_handle_(0),
trace_config_(TraceConfig()),
event_callback_trace_config_(TraceConfig()),
thread_shared_chunk_index_(0),
generation_(0),
use_worker_thread_(false) {
// Trace is enabled or disabled on one thread while other threads are
// accessing the enabled flag. We don't care whether edge-case events are
// traced or not, so we allow races on the enabled flag to keep the trace
// macros fast.
// TODO(jbates): ANNOTATE_BENIGN_RACE_SIZED crashes windows TSAN bots:
// ANNOTATE_BENIGN_RACE_SIZED(g_category_group_enabled,
// sizeof(g_category_group_enabled),
// "trace_event category enabled");
for (int i = 0; i < MAX_CATEGORY_GROUPS; ++i) {
ANNOTATE_BENIGN_RACE(&g_category_group_enabled[i],
"trace_event category enabled");
}
#if defined(OS_NACL) // NaCl shouldn't expose the process id.
SetProcessID(0);
#else
SetProcessID(static_cast<int>(GetCurrentProcId()));
#endif
logged_events_.reset(CreateTraceBuffer());
MemoryDumpManager::GetInstance()->RegisterDumpProvider(this, "TraceLog",
nullptr);
}
TraceLog::~TraceLog() {}
void TraceLog::InitializeThreadLocalEventBufferIfSupported() {
// A ThreadLocalEventBuffer needs the message loop
// - to know when the thread exits;
// - to handle the final flush.
// For a thread without a message loop or the message loop may be blocked, the
// trace events will be added into the main buffer directly.
if (thread_blocks_message_loop_.Get() || !MessageLoop::current())
return;
auto thread_local_event_buffer = thread_local_event_buffer_.Get();
if (thread_local_event_buffer &&
!CheckGeneration(thread_local_event_buffer->generation())) {
delete thread_local_event_buffer;
thread_local_event_buffer = NULL;
}
if (!thread_local_event_buffer) {
thread_local_event_buffer = new ThreadLocalEventBuffer(this);
thread_local_event_buffer_.Set(thread_local_event_buffer);
}
}
bool TraceLog::OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) {
// TODO(ssid): Use MemoryDumpArgs to create light dumps when requested
// (crbug.com/499731).
TraceEventMemoryOverhead overhead;
overhead.Add("TraceLog", sizeof(*this));
{
AutoLock lock(lock_);
if (logged_events_)
logged_events_->EstimateTraceMemoryOverhead(&overhead);
for (auto& metadata_event : metadata_events_)
metadata_event->EstimateTraceMemoryOverhead(&overhead);
}
overhead.AddSelf();
overhead.DumpInto("tracing/main_trace_log", pmd);
return true;
}
const unsigned char* TraceLog::GetCategoryGroupEnabled(
const char* category_group) {
TraceLog* tracelog = GetInstance();
if (!tracelog) {
DCHECK(!g_category_group_enabled[g_category_already_shutdown]);
return &g_category_group_enabled[g_category_already_shutdown];
}
return tracelog->GetCategoryGroupEnabledInternal(category_group);
}
const char* TraceLog::GetCategoryGroupName(
const unsigned char* category_group_enabled) {
// Calculate the index of the category group by finding
// category_group_enabled in g_category_group_enabled array.
uintptr_t category_begin =
reinterpret_cast<uintptr_t>(g_category_group_enabled);
uintptr_t category_ptr = reinterpret_cast<uintptr_t>(category_group_enabled);
DCHECK(category_ptr >= category_begin &&
category_ptr < reinterpret_cast<uintptr_t>(g_category_group_enabled +
MAX_CATEGORY_GROUPS))
<< "out of bounds category pointer";
uintptr_t category_index =
(category_ptr - category_begin) / sizeof(g_category_group_enabled[0]);
return g_category_groups[category_index];
}
void TraceLog::UpdateCategoryGroupEnabledFlag(size_t category_index) {
unsigned char enabled_flag = 0;
const char* category_group = g_category_groups[category_index];
if (mode_ == RECORDING_MODE &&
trace_config_.IsCategoryGroupEnabled(category_group)) {
enabled_flag |= ENABLED_FOR_RECORDING;
}
if (event_callback_ &&
event_callback_trace_config_.IsCategoryGroupEnabled(category_group)) {
enabled_flag |= ENABLED_FOR_EVENT_CALLBACK;
}
#if defined(OS_WIN)
if (base::trace_event::TraceEventETWExport::IsCategoryGroupEnabled(
category_group)) {
enabled_flag |= ENABLED_FOR_ETW_EXPORT;
}
#endif
g_category_group_enabled[category_index] = enabled_flag;
}
void TraceLog::UpdateCategoryGroupEnabledFlags() {
size_t category_index = base::subtle::NoBarrier_Load(&g_category_index);
for (size_t i = 0; i < category_index; i++)
UpdateCategoryGroupEnabledFlag(i);
}
void TraceLog::UpdateSyntheticDelaysFromTraceConfig() {
ResetTraceEventSyntheticDelays();
const TraceConfig::StringList& delays =
trace_config_.GetSyntheticDelayValues();
TraceConfig::StringList::const_iterator ci;
for (ci = delays.begin(); ci != delays.end(); ++ci) {
StringTokenizer tokens(*ci, ";");
if (!tokens.GetNext())
continue;
TraceEventSyntheticDelay* delay =
TraceEventSyntheticDelay::Lookup(tokens.token());
while (tokens.GetNext()) {
std::string token = tokens.token();
char* duration_end;
double target_duration = strtod(token.c_str(), &duration_end);
if (duration_end != token.c_str()) {
delay->SetTargetDuration(TimeDelta::FromMicroseconds(
static_cast<int64_t>(target_duration * 1e6)));
} else if (token == "static") {
delay->SetMode(TraceEventSyntheticDelay::STATIC);
} else if (token == "oneshot") {
delay->SetMode(TraceEventSyntheticDelay::ONE_SHOT);
} else if (token == "alternating") {
delay->SetMode(TraceEventSyntheticDelay::ALTERNATING);
}
}
}
}
const unsigned char* TraceLog::GetCategoryGroupEnabledInternal(
const char* category_group) {
DCHECK(!strchr(category_group, '"'))
<< "Category groups may not contain double quote";
// The g_category_groups is append only, avoid using a lock for the fast path.
size_t current_category_index = base::subtle::Acquire_Load(&g_category_index);
// Search for pre-existing category group.
for (size_t i = 0; i < current_category_index; ++i) {
if (strcmp(g_category_groups[i], category_group) == 0) {
return &g_category_group_enabled[i];
}
}
unsigned char* category_group_enabled = NULL;
// This is the slow path: the lock is not held in the case above, so more
// than one thread could have reached here trying to add the same category.
// Only hold to lock when actually appending a new category, and
// check the categories groups again.
AutoLock lock(lock_);
size_t category_index = base::subtle::Acquire_Load(&g_category_index);
for (size_t i = 0; i < category_index; ++i) {
if (strcmp(g_category_groups[i], category_group) == 0) {
return &g_category_group_enabled[i];
}
}
// Create a new category group.
DCHECK(category_index < MAX_CATEGORY_GROUPS)
<< "must increase MAX_CATEGORY_GROUPS";
if (category_index < MAX_CATEGORY_GROUPS) {
// Don't hold on to the category_group pointer, so that we can create
// category groups with strings not known at compile time (this is
// required by SetWatchEvent).
const char* new_group = strdup(category_group);
ANNOTATE_LEAKING_OBJECT_PTR(new_group);
g_category_groups[category_index] = new_group;
DCHECK(!g_category_group_enabled[category_index]);
// Note that if both included and excluded patterns in the
// TraceConfig are empty, we exclude nothing,
// thereby enabling this category group.
UpdateCategoryGroupEnabledFlag(category_index);
category_group_enabled = &g_category_group_enabled[category_index];
// Update the max index now.
base::subtle::Release_Store(&g_category_index, category_index + 1);
} else {
category_group_enabled =
&g_category_group_enabled[g_category_categories_exhausted];
}
return category_group_enabled;
}
void TraceLog::GetKnownCategoryGroups(
std::vector<std::string>* category_groups) {
AutoLock lock(lock_);
size_t category_index = base::subtle::NoBarrier_Load(&g_category_index);
for (size_t i = g_num_builtin_categories; i < category_index; i++)
category_groups->push_back(g_category_groups[i]);
}
void TraceLog::SetEnabled(const TraceConfig& trace_config, Mode mode) {
std::vector<EnabledStateObserver*> observer_list;
{
AutoLock lock(lock_);
// Can't enable tracing when Flush() is in progress.
DCHECK(!flush_task_runner_);
InternalTraceOptions new_options =
GetInternalOptionsFromTraceConfig(trace_config);
InternalTraceOptions old_options = trace_options();
if (IsEnabled()) {
if (new_options != old_options) {
DLOG(ERROR) << "Attempting to re-enable tracing with a different "
<< "set of options.";
}
if (mode != mode_) {
DLOG(ERROR) << "Attempting to re-enable tracing with a different mode.";
}
trace_config_.Merge(trace_config);
UpdateCategoryGroupEnabledFlags();
return;
}
if (dispatching_to_observer_list_) {
DLOG(ERROR)
<< "Cannot manipulate TraceLog::Enabled state from an observer.";
return;
}
mode_ = mode;
if (new_options != old_options) {
subtle::NoBarrier_Store(&trace_options_, new_options);
UseNextTraceBuffer();
}
num_traces_recorded_++;
trace_config_ = TraceConfig(trace_config);
UpdateCategoryGroupEnabledFlags();
UpdateSyntheticDelaysFromTraceConfig();
if (new_options & kInternalEnableSampling) {
sampling_thread_.reset(new TraceSamplingThread);
sampling_thread_->RegisterSampleBucket(
&g_trace_state[0], "bucket0",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
sampling_thread_->RegisterSampleBucket(
&g_trace_state[1], "bucket1",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
sampling_thread_->RegisterSampleBucket(
&g_trace_state[2], "bucket2",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
if (!PlatformThread::Create(0, sampling_thread_.get(),
&sampling_thread_handle_)) {
DCHECK(false) << "failed to create thread";
}
}
dispatching_to_observer_list_ = true;
observer_list = enabled_state_observer_list_;
}
// Notify observers outside the lock in case they trigger trace events.
for (size_t i = 0; i < observer_list.size(); ++i)
observer_list[i]->OnTraceLogEnabled();
{
AutoLock lock(lock_);
dispatching_to_observer_list_ = false;
}
}
void TraceLog::SetArgumentFilterPredicate(
const ArgumentFilterPredicate& argument_filter_predicate) {
AutoLock lock(lock_);
DCHECK(!argument_filter_predicate.is_null());
DCHECK(argument_filter_predicate_.is_null());
argument_filter_predicate_ = argument_filter_predicate;
}
TraceLog::InternalTraceOptions TraceLog::GetInternalOptionsFromTraceConfig(
const TraceConfig& config) {
InternalTraceOptions ret =
config.IsSamplingEnabled() ? kInternalEnableSampling : kInternalNone;
if (config.IsArgumentFilterEnabled())
ret |= kInternalEnableArgumentFilter;
switch (config.GetTraceRecordMode()) {
case RECORD_UNTIL_FULL:
return ret | kInternalRecordUntilFull;
case RECORD_CONTINUOUSLY:
return ret | kInternalRecordContinuously;
case ECHO_TO_CONSOLE:
return ret | kInternalEchoToConsole;
case RECORD_AS_MUCH_AS_POSSIBLE:
return ret | kInternalRecordAsMuchAsPossible;
}
NOTREACHED();
return kInternalNone;
}
TraceConfig TraceLog::GetCurrentTraceConfig() const {
AutoLock lock(lock_);
return trace_config_;
}
void TraceLog::SetDisabled() {
AutoLock lock(lock_);
SetDisabledWhileLocked();
}
void TraceLog::SetDisabledWhileLocked() {
lock_.AssertAcquired();
if (!IsEnabled())
return;
if (dispatching_to_observer_list_) {
DLOG(ERROR)
<< "Cannot manipulate TraceLog::Enabled state from an observer.";
return;
}
mode_ = DISABLED;
if (sampling_thread_.get()) {
// Stop the sampling thread.
sampling_thread_->Stop();
lock_.Release();
PlatformThread::Join(sampling_thread_handle_);
lock_.Acquire();
sampling_thread_handle_ = PlatformThreadHandle();
sampling_thread_.reset();
}
trace_config_.Clear();
subtle::NoBarrier_Store(&watch_category_, 0);
watch_event_name_ = "";
UpdateCategoryGroupEnabledFlags();
AddMetadataEventsWhileLocked();
// Remove metadata events so they will not get added to a subsequent trace.
metadata_events_.clear();
dispatching_to_observer_list_ = true;
std::vector<EnabledStateObserver*> observer_list =
enabled_state_observer_list_;
{
// Dispatch to observers outside the lock in case the observer triggers a
// trace event.
AutoUnlock unlock(lock_);
for (size_t i = 0; i < observer_list.size(); ++i)
observer_list[i]->OnTraceLogDisabled();
}
dispatching_to_observer_list_ = false;
}
int TraceLog::GetNumTracesRecorded() {
AutoLock lock(lock_);
if (!IsEnabled())
return -1;
return num_traces_recorded_;
}
void TraceLog::AddEnabledStateObserver(EnabledStateObserver* listener) {
AutoLock lock(lock_);
enabled_state_observer_list_.push_back(listener);
}
void TraceLog::RemoveEnabledStateObserver(EnabledStateObserver* listener) {
AutoLock lock(lock_);
std::vector<EnabledStateObserver*>::iterator it =
std::find(enabled_state_observer_list_.begin(),
enabled_state_observer_list_.end(), listener);
if (it != enabled_state_observer_list_.end())
enabled_state_observer_list_.erase(it);
}
bool TraceLog::HasEnabledStateObserver(EnabledStateObserver* listener) const {
AutoLock lock(lock_);
return ContainsValue(enabled_state_observer_list_, listener);
}
TraceLogStatus TraceLog::GetStatus() const {
AutoLock lock(lock_);
TraceLogStatus result;
result.event_capacity = static_cast<uint32_t>(logged_events_->Capacity());
result.event_count = static_cast<uint32_t>(logged_events_->Size());
return result;
}
bool TraceLog::BufferIsFull() const {
AutoLock lock(lock_);
return logged_events_->IsFull();
}
TraceEvent* TraceLog::AddEventToThreadSharedChunkWhileLocked(
TraceEventHandle* handle,
bool check_buffer_is_full) {
lock_.AssertAcquired();
if (thread_shared_chunk_ && thread_shared_chunk_->IsFull()) {
logged_events_->ReturnChunk(thread_shared_chunk_index_,
std::move(thread_shared_chunk_));
}
if (!thread_shared_chunk_) {
thread_shared_chunk_ =
logged_events_->GetChunk(&thread_shared_chunk_index_);
if (check_buffer_is_full)
CheckIfBufferIsFullWhileLocked();
}
if (!thread_shared_chunk_)
return NULL;
size_t event_index;
TraceEvent* trace_event = thread_shared_chunk_->AddTraceEvent(&event_index);
if (trace_event && handle) {
MakeHandle(thread_shared_chunk_->seq(), thread_shared_chunk_index_,
event_index, handle);
}
return trace_event;
}
void TraceLog::CheckIfBufferIsFullWhileLocked() {
lock_.AssertAcquired();
if (logged_events_->IsFull()) {
if (buffer_limit_reached_timestamp_.is_null()) {
buffer_limit_reached_timestamp_ = OffsetNow();
}
SetDisabledWhileLocked();
}
}
void TraceLog::SetEventCallbackEnabled(const TraceConfig& trace_config,
EventCallback cb) {
AutoLock lock(lock_);
subtle::NoBarrier_Store(&event_callback_,
reinterpret_cast<subtle::AtomicWord>(cb));
event_callback_trace_config_ = trace_config;
UpdateCategoryGroupEnabledFlags();
}
void TraceLog::SetEventCallbackDisabled() {
AutoLock lock(lock_);
subtle::NoBarrier_Store(&event_callback_, 0);
UpdateCategoryGroupEnabledFlags();
}
// Flush() works as the following:
// 1. Flush() is called in thread A whose task runner is saved in
// flush_task_runner_;
// 2. If thread_message_loops_ is not empty, thread A posts task to each message
// loop to flush the thread local buffers; otherwise finish the flush;
// 3. FlushCurrentThread() deletes the thread local event buffer:
// - The last batch of events of the thread are flushed into the main buffer;
// - The message loop will be removed from thread_message_loops_;
// If this is the last message loop, finish the flush;
// 4. If any thread hasn't finish its flush in time, finish the flush.
void TraceLog::Flush(const TraceLog::OutputCallback& cb,
bool use_worker_thread) {
FlushInternal(cb, use_worker_thread, false);
}
void TraceLog::CancelTracing(const OutputCallback& cb) {
SetDisabled();
FlushInternal(cb, false, true);
}
void TraceLog::FlushInternal(const TraceLog::OutputCallback& cb,
bool use_worker_thread,
bool discard_events) {
use_worker_thread_ = use_worker_thread;
if (IsEnabled()) {
// Can't flush when tracing is enabled because otherwise PostTask would
// - generate more trace events;
// - deschedule the calling thread on some platforms causing inaccurate
// timing of the trace events.
scoped_refptr<RefCountedString> empty_result = new RefCountedString;
if (!cb.is_null())
cb.Run(empty_result, false);
LOG(WARNING) << "Ignored TraceLog::Flush called when tracing is enabled";
return;
}
int generation = this->generation();
// Copy of thread_message_loops_ to be used without locking.
std::vector<scoped_refptr<SingleThreadTaskRunner>>
thread_message_loop_task_runners;
{
AutoLock lock(lock_);
DCHECK(!flush_task_runner_);
flush_task_runner_ = ThreadTaskRunnerHandle::IsSet()
? ThreadTaskRunnerHandle::Get()
: nullptr;
DCHECK(!thread_message_loops_.size() || flush_task_runner_);
flush_output_callback_ = cb;
if (thread_shared_chunk_) {
logged_events_->ReturnChunk(thread_shared_chunk_index_,
std::move(thread_shared_chunk_));
}
if (thread_message_loops_.size()) {
for (hash_set<MessageLoop*>::const_iterator it =
thread_message_loops_.begin();
it != thread_message_loops_.end(); ++it) {
thread_message_loop_task_runners.push_back((*it)->task_runner());
}
}
}
if (thread_message_loop_task_runners.size()) {
for (size_t i = 0; i < thread_message_loop_task_runners.size(); ++i) {
thread_message_loop_task_runners[i]->PostTask(
FROM_HERE, Bind(&TraceLog::FlushCurrentThread, Unretained(this),
generation, discard_events));
}
flush_task_runner_->PostDelayedTask(
FROM_HERE, Bind(&TraceLog::OnFlushTimeout, Unretained(this), generation,
discard_events),
TimeDelta::FromMilliseconds(kThreadFlushTimeoutMs));
return;
}
FinishFlush(generation, discard_events);
}
// Usually it runs on a different thread.
void TraceLog::ConvertTraceEventsToTraceFormat(
scoped_ptr<TraceBuffer> logged_events,
const OutputCallback& flush_output_callback,
const ArgumentFilterPredicate& argument_filter_predicate) {
if (flush_output_callback.is_null())
return;
// The callback need to be called at least once even if there is no events
// to let the caller know the completion of flush.
scoped_refptr<RefCountedString> json_events_str_ptr = new RefCountedString();
while (const TraceBufferChunk* chunk = logged_events->NextChunk()) {
for (size_t j = 0; j < chunk->size(); ++j) {
size_t size = json_events_str_ptr->size();
if (size > kTraceEventBufferSizeInBytes) {
flush_output_callback.Run(json_events_str_ptr, true);
json_events_str_ptr = new RefCountedString();
} else if (size) {
json_events_str_ptr->data().append(",\n");
}
chunk->GetEventAt(j)->AppendAsJSON(&(json_events_str_ptr->data()),
argument_filter_predicate);
}
}
flush_output_callback.Run(json_events_str_ptr, false);
}
void TraceLog::FinishFlush(int generation, bool discard_events) {
scoped_ptr<TraceBuffer> previous_logged_events;
OutputCallback flush_output_callback;
ArgumentFilterPredicate argument_filter_predicate;
if (!CheckGeneration(generation))
return;
{
AutoLock lock(lock_);
previous_logged_events.swap(logged_events_);
UseNextTraceBuffer();
thread_message_loops_.clear();
flush_task_runner_ = NULL;
flush_output_callback = flush_output_callback_;
flush_output_callback_.Reset();
if (trace_options() & kInternalEnableArgumentFilter) {
CHECK(!argument_filter_predicate_.is_null());
argument_filter_predicate = argument_filter_predicate_;
}
}
if (discard_events) {
if (!flush_output_callback.is_null()) {
scoped_refptr<RefCountedString> empty_result = new RefCountedString;
flush_output_callback.Run(empty_result, false);
}
return;
}
if (use_worker_thread_ &&
WorkerPool::PostTask(
FROM_HERE, Bind(&TraceLog::ConvertTraceEventsToTraceFormat,
Passed(&previous_logged_events),
flush_output_callback, argument_filter_predicate),
true)) {
return;
}
ConvertTraceEventsToTraceFormat(std::move(previous_logged_events),
flush_output_callback,
argument_filter_predicate);
}
// Run in each thread holding a local event buffer.
void TraceLog::FlushCurrentThread(int generation, bool discard_events) {
{
AutoLock lock(lock_);
if (!CheckGeneration(generation) || !flush_task_runner_) {
// This is late. The corresponding flush has finished.
return;
}
}
// This will flush the thread local buffer.
delete thread_local_event_buffer_.Get();
AutoLock lock(lock_);
if (!CheckGeneration(generation) || !flush_task_runner_ ||
thread_message_loops_.size())
return;
flush_task_runner_->PostTask(
FROM_HERE, Bind(&TraceLog::FinishFlush, Unretained(this), generation,
discard_events));
}
void TraceLog::OnFlushTimeout(int generation, bool discard_events) {
{