Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / base / trace_event / trace_event_impl.h
blob4274f807d2ae029da263dcd342377a2813808f7c
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 #ifndef BASE_TRACE_EVENT_TRACE_EVENT_IMPL_H_
7 #define BASE_TRACE_EVENT_TRACE_EVENT_IMPL_H_
9 #include <stack>
10 #include <string>
11 #include <vector>
13 #include "base/atomicops.h"
14 #include "base/base_export.h"
15 #include "base/callback.h"
16 #include "base/containers/hash_tables.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/memory/ref_counted_memory.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/observer_list.h"
21 #include "base/single_thread_task_runner.h"
22 #include "base/strings/string_util.h"
23 #include "base/synchronization/condition_variable.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/thread_local.h"
27 #include "base/trace_event/memory_dump_provider.h"
28 #include "base/trace_event/trace_config.h"
29 #include "base/trace_event/trace_event_memory_overhead.h"
31 // Older style trace macros with explicit id and extra data
32 // Only these macros result in publishing data to ETW as currently implemented.
33 // TODO(georgesak): Update/replace these with new ETW macros.
34 #define TRACE_EVENT_BEGIN_ETW(name, id, extra) \
35 base::trace_event::TraceLog::AddTraceEventEtw( \
36 TRACE_EVENT_PHASE_BEGIN, \
37 name, reinterpret_cast<const void*>(id), extra)
39 #define TRACE_EVENT_END_ETW(name, id, extra) \
40 base::trace_event::TraceLog::AddTraceEventEtw( \
41 TRACE_EVENT_PHASE_END, \
42 name, reinterpret_cast<const void*>(id), extra)
44 #define TRACE_EVENT_INSTANT_ETW(name, id, extra) \
45 base::trace_event::TraceLog::AddTraceEventEtw( \
46 TRACE_EVENT_PHASE_INSTANT, \
47 name, reinterpret_cast<const void*>(id), extra)
49 template <typename Type>
50 struct DefaultSingletonTraits;
52 namespace base {
54 class WaitableEvent;
55 class MessageLoop;
57 namespace trace_event {
59 // For any argument of type TRACE_VALUE_TYPE_CONVERTABLE the provided
60 // class must implement this interface.
61 class BASE_EXPORT ConvertableToTraceFormat
62 : public RefCounted<ConvertableToTraceFormat> {
63 public:
64 // Append the class info to the provided |out| string. The appended
65 // data must be a valid JSON object. Strings must be properly quoted, and
66 // escaped. There is no processing applied to the content after it is
67 // appended.
68 virtual void AppendAsTraceFormat(std::string* out) const = 0;
70 virtual void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead);
72 std::string ToString() const {
73 std::string result;
74 AppendAsTraceFormat(&result);
75 return result;
78 protected:
79 virtual ~ConvertableToTraceFormat() {}
81 private:
82 friend class RefCounted<ConvertableToTraceFormat>;
85 struct TraceEventHandle {
86 uint32 chunk_seq;
87 uint16 chunk_index;
88 uint16 event_index;
91 const int kTraceMaxNumArgs = 2;
93 class BASE_EXPORT TraceEvent {
94 public:
95 union TraceValue {
96 bool as_bool;
97 unsigned long long as_uint;
98 long long as_int;
99 double as_double;
100 const void* as_pointer;
101 const char* as_string;
104 TraceEvent();
105 ~TraceEvent();
107 // We don't need to copy TraceEvent except when TraceEventBuffer is cloned.
108 // Use explicit copy method to avoid accidentally misuse of copy.
109 void CopyFrom(const TraceEvent& other);
111 void Initialize(
112 int thread_id,
113 TraceTicks timestamp,
114 ThreadTicks thread_timestamp,
115 char phase,
116 const unsigned char* category_group_enabled,
117 const char* name,
118 unsigned long long id,
119 unsigned long long context_id,
120 int num_args,
121 const char** arg_names,
122 const unsigned char* arg_types,
123 const unsigned long long* arg_values,
124 const scoped_refptr<ConvertableToTraceFormat>* convertable_values,
125 unsigned int flags);
127 void Reset();
129 void UpdateDuration(const TraceTicks& now, const ThreadTicks& thread_now);
131 void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead*);
133 // Serialize event data to JSON
134 typedef base::Callback<bool(const char* category_group_name,
135 const char* event_name)> ArgumentFilterPredicate;
136 void AppendAsJSON(
137 std::string* out,
138 const ArgumentFilterPredicate& argument_filter_predicate) const;
139 void AppendPrettyPrinted(std::ostringstream* out) const;
141 static void AppendValueAsJSON(unsigned char type,
142 TraceValue value,
143 std::string* out);
145 TraceTicks timestamp() const { return timestamp_; }
146 ThreadTicks thread_timestamp() const { return thread_timestamp_; }
147 char phase() const { return phase_; }
148 int thread_id() const { return thread_id_; }
149 TimeDelta duration() const { return duration_; }
150 TimeDelta thread_duration() const { return thread_duration_; }
151 unsigned long long id() const { return id_; }
152 unsigned long long context_id() const { return context_id_; }
153 unsigned int flags() const { return flags_; }
155 // Exposed for unittesting:
157 const base::RefCountedString* parameter_copy_storage() const {
158 return parameter_copy_storage_.get();
161 const unsigned char* category_group_enabled() const {
162 return category_group_enabled_;
165 const char* name() const { return name_; }
167 #if defined(OS_ANDROID)
168 void SendToATrace();
169 #endif
171 private:
172 // Note: these are ordered by size (largest first) for optimal packing.
173 TraceTicks timestamp_;
174 ThreadTicks thread_timestamp_;
175 TimeDelta duration_;
176 TimeDelta thread_duration_;
177 // id_ can be used to store phase-specific data.
178 unsigned long long id_;
179 // context_id_ is used to store context information.
180 unsigned long long context_id_;
181 TraceValue arg_values_[kTraceMaxNumArgs];
182 const char* arg_names_[kTraceMaxNumArgs];
183 scoped_refptr<ConvertableToTraceFormat> convertable_values_[kTraceMaxNumArgs];
184 const unsigned char* category_group_enabled_;
185 const char* name_;
186 scoped_refptr<base::RefCountedString> parameter_copy_storage_;
187 int thread_id_;
188 char phase_;
189 unsigned int flags_;
190 unsigned char arg_types_[kTraceMaxNumArgs];
192 DISALLOW_COPY_AND_ASSIGN(TraceEvent);
195 // TraceBufferChunk is the basic unit of TraceBuffer.
196 class BASE_EXPORT TraceBufferChunk {
197 public:
198 explicit TraceBufferChunk(uint32 seq);
199 ~TraceBufferChunk();
201 void Reset(uint32 new_seq);
202 TraceEvent* AddTraceEvent(size_t* event_index);
203 bool IsFull() const { return next_free_ == kTraceBufferChunkSize; }
205 uint32 seq() const { return seq_; }
206 size_t capacity() const { return kTraceBufferChunkSize; }
207 size_t size() const { return next_free_; }
209 TraceEvent* GetEventAt(size_t index) {
210 DCHECK(index < size());
211 return &chunk_[index];
213 const TraceEvent* GetEventAt(size_t index) const {
214 DCHECK(index < size());
215 return &chunk_[index];
218 scoped_ptr<TraceBufferChunk> Clone() const;
220 void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead);
222 static const size_t kTraceBufferChunkSize = 64;
224 private:
225 size_t next_free_;
226 scoped_ptr<TraceEventMemoryOverhead> cached_overhead_estimate_;
227 TraceEvent chunk_[kTraceBufferChunkSize];
228 uint32 seq_;
231 // TraceBuffer holds the events as they are collected.
232 class BASE_EXPORT TraceBuffer {
233 public:
234 virtual ~TraceBuffer() {}
236 virtual scoped_ptr<TraceBufferChunk> GetChunk(size_t *index) = 0;
237 virtual void ReturnChunk(size_t index,
238 scoped_ptr<TraceBufferChunk> chunk) = 0;
240 virtual bool IsFull() const = 0;
241 virtual size_t Size() const = 0;
242 virtual size_t Capacity() const = 0;
243 virtual TraceEvent* GetEventByHandle(TraceEventHandle handle) = 0;
245 // For iteration. Each TraceBuffer can only be iterated once.
246 virtual const TraceBufferChunk* NextChunk() = 0;
248 virtual scoped_ptr<TraceBuffer> CloneForIteration() const = 0;
250 // Computes an estimate of the size of the buffer, including all the retained
251 // objects.
252 virtual void EstimateTraceMemoryOverhead(
253 TraceEventMemoryOverhead* overhead) = 0;
256 // TraceResultBuffer collects and converts trace fragments returned by TraceLog
257 // to JSON output.
258 class BASE_EXPORT TraceResultBuffer {
259 public:
260 typedef base::Callback<void(const std::string&)> OutputCallback;
262 // If you don't need to stream JSON chunks out efficiently, and just want to
263 // get a complete JSON string after calling Finish, use this struct to collect
264 // JSON trace output.
265 struct BASE_EXPORT SimpleOutput {
266 OutputCallback GetCallback();
267 void Append(const std::string& json_string);
269 // Do what you want with the json_output_ string after calling
270 // TraceResultBuffer::Finish.
271 std::string json_output;
274 TraceResultBuffer();
275 ~TraceResultBuffer();
277 // Set callback. The callback will be called during Start with the initial
278 // JSON output and during AddFragment and Finish with following JSON output
279 // chunks. The callback target must live past the last calls to
280 // TraceResultBuffer::Start/AddFragment/Finish.
281 void SetOutputCallback(const OutputCallback& json_chunk_callback);
283 // Start JSON output. This resets all internal state, so you can reuse
284 // the TraceResultBuffer by calling Start.
285 void Start();
287 // Call AddFragment 0 or more times to add trace fragments from TraceLog.
288 void AddFragment(const std::string& trace_fragment);
290 // When all fragments have been added, call Finish to complete the JSON
291 // formatted output.
292 void Finish();
294 private:
295 OutputCallback output_callback_;
296 bool append_comma_;
299 class TraceSamplingThread;
301 struct BASE_EXPORT TraceLogStatus {
302 TraceLogStatus();
303 ~TraceLogStatus();
304 size_t event_capacity;
305 size_t event_count;
308 class BASE_EXPORT TraceLog : public MemoryDumpProvider {
309 public:
310 enum Mode {
311 DISABLED = 0,
312 RECORDING_MODE,
313 MONITORING_MODE,
316 // The pointer returned from GetCategoryGroupEnabledInternal() points to a
317 // value with zero or more of the following bits. Used in this class only.
318 // The TRACE_EVENT macros should only use the value as a bool.
319 // These values must be in sync with macro values in TraceEvent.h in Blink.
320 enum CategoryGroupEnabledFlags {
321 // Category group enabled for the recording mode.
322 ENABLED_FOR_RECORDING = 1 << 0,
323 // Category group enabled for the monitoring mode.
324 ENABLED_FOR_MONITORING = 1 << 1,
325 // Category group enabled by SetEventCallbackEnabled().
326 ENABLED_FOR_EVENT_CALLBACK = 1 << 2,
327 // Category group enabled to export events to ETW.
328 ENABLED_FOR_ETW_EXPORT = 1 << 3
331 static TraceLog* GetInstance();
333 // Get set of known category groups. This can change as new code paths are
334 // reached. The known category groups are inserted into |category_groups|.
335 void GetKnownCategoryGroups(std::vector<std::string>* category_groups);
337 // Retrieves a copy (for thread-safety) of the current TraceConfig.
338 TraceConfig GetCurrentTraceConfig() const;
340 // Initializes the thread-local event buffer, if not already initialized and
341 // if the current thread supports that (has a message loop).
342 void InitializeThreadLocalEventBufferIfSupported();
344 // Enables normal tracing (recording trace events in the trace buffer).
345 // See TraceConfig comments for details on how to control what categories
346 // will be traced. If tracing has already been enabled, |category_filter| will
347 // be merged into the current category filter.
348 void SetEnabled(const TraceConfig& trace_config, Mode mode);
350 // Disables normal tracing for all categories.
351 void SetDisabled();
353 bool IsEnabled() { return mode_ != DISABLED; }
355 // The number of times we have begun recording traces. If tracing is off,
356 // returns -1. If tracing is on, then it returns the number of times we have
357 // recorded a trace. By watching for this number to increment, you can
358 // passively discover when a new trace has begun. This is then used to
359 // implement the TRACE_EVENT_IS_NEW_TRACE() primitive.
360 int GetNumTracesRecorded();
362 #if defined(OS_ANDROID)
363 void StartATrace();
364 void StopATrace();
365 void AddClockSyncMetadataEvent();
366 #endif
368 // Enabled state listeners give a callback when tracing is enabled or
369 // disabled. This can be used to tie into other library's tracing systems
370 // on-demand.
371 class BASE_EXPORT EnabledStateObserver {
372 public:
373 virtual ~EnabledStateObserver() = default;
375 // Called just after the tracing system becomes enabled, outside of the
376 // |lock_|. TraceLog::IsEnabled() is true at this point.
377 virtual void OnTraceLogEnabled() = 0;
379 // Called just after the tracing system disables, outside of the |lock_|.
380 // TraceLog::IsEnabled() is false at this point.
381 virtual void OnTraceLogDisabled() = 0;
383 void AddEnabledStateObserver(EnabledStateObserver* listener);
384 void RemoveEnabledStateObserver(EnabledStateObserver* listener);
385 bool HasEnabledStateObserver(EnabledStateObserver* listener) const;
387 TraceLogStatus GetStatus() const;
388 bool BufferIsFull() const;
390 // Computes an estimate of the size of the TraceLog including all the retained
391 // objects.
392 void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead);
394 // Not using base::Callback because of its limited by 7 parameters.
395 // Also, using primitive type allows directly passing callback from WebCore.
396 // WARNING: It is possible for the previously set callback to be called
397 // after a call to SetEventCallbackEnabled() that replaces or a call to
398 // SetEventCallbackDisabled() that disables the callback.
399 // This callback may be invoked on any thread.
400 // For TRACE_EVENT_PHASE_COMPLETE events, the client will still receive pairs
401 // of TRACE_EVENT_PHASE_BEGIN and TRACE_EVENT_PHASE_END events to keep the
402 // interface simple.
403 typedef void (*EventCallback)(TraceTicks timestamp,
404 char phase,
405 const unsigned char* category_group_enabled,
406 const char* name,
407 unsigned long long id,
408 int num_args,
409 const char* const arg_names[],
410 const unsigned char arg_types[],
411 const unsigned long long arg_values[],
412 unsigned int flags);
414 // Enable tracing for EventCallback.
415 void SetEventCallbackEnabled(const TraceConfig& trace_config,
416 EventCallback cb);
417 void SetEventCallbackDisabled();
418 void SetArgumentFilterPredicate(
419 const TraceEvent::ArgumentFilterPredicate& argument_filter_predicate);
421 // Flush all collected events to the given output callback. The callback will
422 // be called one or more times either synchronously or asynchronously from
423 // the current thread with IPC-bite-size chunks. The string format is
424 // undefined. Use TraceResultBuffer to convert one or more trace strings to
425 // JSON. The callback can be null if the caller doesn't want any data.
426 // Due to the implementation of thread-local buffers, flush can't be
427 // done when tracing is enabled. If called when tracing is enabled, the
428 // callback will be called directly with (empty_string, false) to indicate
429 // the end of this unsuccessful flush. Flush does the serialization
430 // on the same thread if the caller doesn't set use_worker_thread explicitly.
431 typedef base::Callback<void(const scoped_refptr<base::RefCountedString>&,
432 bool has_more_events)> OutputCallback;
433 void Flush(const OutputCallback& cb, bool use_worker_thread = false);
434 void FlushButLeaveBufferIntact(const OutputCallback& flush_output_callback);
436 // Cancels tracing and discards collected data.
437 void CancelTracing(const OutputCallback& cb);
439 // Called by TRACE_EVENT* macros, don't call this directly.
440 // The name parameter is a category group for example:
441 // TRACE_EVENT0("renderer,webkit", "WebViewImpl::HandleInputEvent")
442 static const unsigned char* GetCategoryGroupEnabled(const char* name);
443 static const char* GetCategoryGroupName(
444 const unsigned char* category_group_enabled);
446 // Called by TRACE_EVENT* macros, don't call this directly.
447 // If |copy| is set, |name|, |arg_name1| and |arg_name2| will be deep copied
448 // into the event; see "Memory scoping note" and TRACE_EVENT_COPY_XXX above.
449 TraceEventHandle AddTraceEvent(
450 char phase,
451 const unsigned char* category_group_enabled,
452 const char* name,
453 unsigned long long id,
454 int num_args,
455 const char** arg_names,
456 const unsigned char* arg_types,
457 const unsigned long long* arg_values,
458 const scoped_refptr<ConvertableToTraceFormat>* convertable_values,
459 unsigned int flags);
460 TraceEventHandle AddTraceEventWithContextId(
461 char phase,
462 const unsigned char* category_group_enabled,
463 const char* name,
464 unsigned long long id,
465 unsigned long long context_id,
466 int num_args,
467 const char** arg_names,
468 const unsigned char* arg_types,
469 const unsigned long long* arg_values,
470 const scoped_refptr<ConvertableToTraceFormat>* convertable_values,
471 unsigned int flags);
472 TraceEventHandle AddTraceEventWithThreadIdAndTimestamp(
473 char phase,
474 const unsigned char* category_group_enabled,
475 const char* name,
476 unsigned long long id,
477 unsigned long long context_id,
478 int thread_id,
479 const TraceTicks& timestamp,
480 int num_args,
481 const char** arg_names,
482 const unsigned char* arg_types,
483 const unsigned long long* arg_values,
484 const scoped_refptr<ConvertableToTraceFormat>* convertable_values,
485 unsigned int flags);
486 static void AddTraceEventEtw(char phase,
487 const char* category_group,
488 const void* id,
489 const char* extra);
490 static void AddTraceEventEtw(char phase,
491 const char* category_group,
492 const void* id,
493 const std::string& extra);
495 void UpdateTraceEventDuration(const unsigned char* category_group_enabled,
496 const char* name,
497 TraceEventHandle handle);
499 // For every matching event, the callback will be called.
500 typedef base::Callback<void()> WatchEventCallback;
501 void SetWatchEvent(const std::string& category_name,
502 const std::string& event_name,
503 const WatchEventCallback& callback);
504 // Cancel the watch event. If tracing is enabled, this may race with the
505 // watch event notification firing.
506 void CancelWatchEvent();
508 int process_id() const { return process_id_; }
510 uint64 MangleEventId(uint64 id);
512 // Exposed for unittesting:
514 void WaitSamplingEventForTesting();
516 // Allows deleting our singleton instance.
517 static void DeleteForTesting();
519 // Allow tests to inspect TraceEvents.
520 TraceEvent* GetEventByHandle(TraceEventHandle handle);
522 void SetProcessID(int process_id);
524 // Process sort indices, if set, override the order of a process will appear
525 // relative to other processes in the trace viewer. Processes are sorted first
526 // on their sort index, ascending, then by their name, and then tid.
527 void SetProcessSortIndex(int sort_index);
529 // Sets the name of the process.
530 void SetProcessName(const std::string& process_name);
532 // Processes can have labels in addition to their names. Use labels, for
533 // instance, to list out the web page titles that a process is handling.
534 void UpdateProcessLabel(int label_id, const std::string& current_label);
535 void RemoveProcessLabel(int label_id);
537 // Thread sort indices, if set, override the order of a thread will appear
538 // within its process in the trace viewer. Threads are sorted first on their
539 // sort index, ascending, then by their name, and then tid.
540 void SetThreadSortIndex(PlatformThreadId , int sort_index);
542 // Allow setting an offset between the current TraceTicks time and the time
543 // that should be reported.
544 void SetTimeOffset(TimeDelta offset);
546 size_t GetObserverCountForTest() const;
548 // Call this method if the current thread may block the message loop to
549 // prevent the thread from using the thread-local buffer because the thread
550 // may not handle the flush request in time causing lost of unflushed events.
551 void SetCurrentThreadBlocksMessageLoop();
553 private:
554 typedef unsigned int InternalTraceOptions;
556 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
557 TraceBufferRingBufferGetReturnChunk);
558 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
559 TraceBufferRingBufferHalfIteration);
560 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
561 TraceBufferRingBufferFullIteration);
562 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
563 TraceBufferVectorReportFull);
564 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
565 ConvertTraceConfigToInternalOptions);
566 FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
567 TraceRecordAsMuchAsPossibleMode);
569 // This allows constructor and destructor to be private and usable only
570 // by the Singleton class.
571 friend struct DefaultSingletonTraits<TraceLog>;
573 // MemoryDumpProvider implementation.
574 bool OnMemoryDump(ProcessMemoryDump* pmd) override;
576 // Enable/disable each category group based on the current mode_,
577 // category_filter_, event_callback_ and event_callback_category_filter_.
578 // Enable the category group in the enabled mode if category_filter_ matches
579 // the category group, or event_callback_ is not null and
580 // event_callback_category_filter_ matches the category group.
581 void UpdateCategoryGroupEnabledFlags();
582 void UpdateCategoryGroupEnabledFlag(size_t category_index);
584 // Configure synthetic delays based on the values set in the current
585 // trace config.
586 void UpdateSyntheticDelaysFromTraceConfig();
588 InternalTraceOptions GetInternalOptionsFromTraceConfig(
589 const TraceConfig& config);
591 class ThreadLocalEventBuffer;
592 class OptionalAutoLock;
594 TraceLog();
595 ~TraceLog() override;
596 const unsigned char* GetCategoryGroupEnabledInternal(const char* name);
597 void AddMetadataEventsWhileLocked();
599 InternalTraceOptions trace_options() const {
600 return static_cast<InternalTraceOptions>(
601 subtle::NoBarrier_Load(&trace_options_));
604 TraceBuffer* trace_buffer() const { return logged_events_.get(); }
605 TraceBuffer* CreateTraceBuffer();
606 TraceBuffer* CreateTraceBufferVectorOfSize(size_t max_chunks);
608 std::string EventToConsoleMessage(unsigned char phase,
609 const TraceTicks& timestamp,
610 TraceEvent* trace_event);
612 TraceEvent* AddEventToThreadSharedChunkWhileLocked(TraceEventHandle* handle,
613 bool check_buffer_is_full);
614 void CheckIfBufferIsFullWhileLocked();
615 void SetDisabledWhileLocked();
617 TraceEvent* GetEventByHandleInternal(TraceEventHandle handle,
618 OptionalAutoLock* lock);
620 void FlushInternal(const OutputCallback& cb,
621 bool use_worker_thread,
622 bool discard_events);
624 // |generation| is used in the following callbacks to check if the callback
625 // is called for the flush of the current |logged_events_|.
626 void FlushCurrentThread(int generation, bool discard_events);
627 // Usually it runs on a different thread.
628 static void ConvertTraceEventsToTraceFormat(
629 scoped_ptr<TraceBuffer> logged_events,
630 const TraceLog::OutputCallback& flush_output_callback,
631 const TraceEvent::ArgumentFilterPredicate& argument_filter_predicate);
632 void FinishFlush(int generation, bool discard_events);
633 void OnFlushTimeout(int generation, bool discard_events);
635 int generation() const {
636 return static_cast<int>(subtle::NoBarrier_Load(&generation_));
638 bool CheckGeneration(int generation) const {
639 return generation == this->generation();
641 void UseNextTraceBuffer();
643 TraceTicks OffsetNow() const {
644 return OffsetTimestamp(TraceTicks::Now());
646 TraceTicks OffsetTimestamp(const TraceTicks& timestamp) const {
647 return timestamp - time_offset_;
650 // Internal representation of trace options since we store the currently used
651 // trace option as an AtomicWord.
652 static const InternalTraceOptions kInternalNone;
653 static const InternalTraceOptions kInternalRecordUntilFull;
654 static const InternalTraceOptions kInternalRecordContinuously;
655 static const InternalTraceOptions kInternalEchoToConsole;
656 static const InternalTraceOptions kInternalEnableSampling;
657 static const InternalTraceOptions kInternalRecordAsMuchAsPossible;
658 static const InternalTraceOptions kInternalEnableArgumentFilter;
660 // This lock protects TraceLog member accesses (except for members protected
661 // by thread_info_lock_) from arbitrary threads.
662 mutable Lock lock_;
663 // This lock protects accesses to thread_names_, thread_event_start_times_
664 // and thread_colors_.
665 Lock thread_info_lock_;
666 Mode mode_;
667 int num_traces_recorded_;
668 scoped_ptr<TraceBuffer> logged_events_;
669 subtle::AtomicWord /* EventCallback */ event_callback_;
670 bool dispatching_to_observer_list_;
671 std::vector<EnabledStateObserver*> enabled_state_observer_list_;
673 std::string process_name_;
674 base::hash_map<int, std::string> process_labels_;
675 int process_sort_index_;
676 base::hash_map<int, int> thread_sort_indices_;
677 base::hash_map<int, std::string> thread_names_;
679 // The following two maps are used only when ECHO_TO_CONSOLE.
680 base::hash_map<int, std::stack<TraceTicks> > thread_event_start_times_;
681 base::hash_map<std::string, int> thread_colors_;
683 TraceTicks buffer_limit_reached_timestamp_;
685 // XORed with TraceID to make it unlikely to collide with other processes.
686 unsigned long long process_id_hash_;
688 int process_id_;
690 TimeDelta time_offset_;
692 // Allow tests to wake up when certain events occur.
693 WatchEventCallback watch_event_callback_;
694 subtle::AtomicWord /* const unsigned char* */ watch_category_;
695 std::string watch_event_name_;
697 subtle::AtomicWord /* Options */ trace_options_;
699 // Sampling thread handles.
700 scoped_ptr<TraceSamplingThread> sampling_thread_;
701 PlatformThreadHandle sampling_thread_handle_;
703 TraceConfig trace_config_;
704 TraceConfig event_callback_trace_config_;
706 ThreadLocalPointer<ThreadLocalEventBuffer> thread_local_event_buffer_;
707 ThreadLocalBoolean thread_blocks_message_loop_;
708 ThreadLocalBoolean thread_is_in_trace_event_;
710 // Contains the message loops of threads that have had at least one event
711 // added into the local event buffer. Not using SingleThreadTaskRunner
712 // because we need to know the life time of the message loops.
713 hash_set<MessageLoop*> thread_message_loops_;
715 // For events which can't be added into the thread local buffer, e.g. events
716 // from threads without a message loop.
717 scoped_ptr<TraceBufferChunk> thread_shared_chunk_;
718 size_t thread_shared_chunk_index_;
720 // Set when asynchronous Flush is in progress.
721 OutputCallback flush_output_callback_;
722 scoped_refptr<SingleThreadTaskRunner> flush_task_runner_;
723 TraceEvent::ArgumentFilterPredicate argument_filter_predicate_;
724 subtle::AtomicWord generation_;
725 bool use_worker_thread_;
727 DISALLOW_COPY_AND_ASSIGN(TraceLog);
730 } // namespace trace_event
731 } // namespace base
733 #endif // BASE_TRACE_EVENT_TRACE_EVENT_IMPL_H_