• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TRACE_EVENT_TRACE_LOG_H_
6 #define BASE_TRACE_EVENT_TRACE_LOG_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <atomic>
12 #include <map>
13 #include <memory>
14 #include <optional>
15 #include <string>
16 #include <unordered_map>
17 #include <vector>
18 
19 #include "base/base_export.h"
20 #include "base/containers/stack.h"
21 #include "base/gtest_prod_util.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/scoped_refptr.h"
24 #include "base/no_destructor.h"
25 #include "base/task/single_thread_task_runner.h"
26 #include "base/threading/platform_thread.h"
27 #include "base/time/time_override.h"
28 #include "base/trace_event/category_registry.h"
29 #include "base/trace_event/memory_dump_provider.h"
30 #include "base/trace_event/trace_config.h"
31 #include "base/trace_event/trace_event_impl.h"
32 #include "build/build_config.h"
33 
34 #include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h"
35 
36 namespace perfetto {
37 namespace trace_processor {
38 class TraceProcessorStorage;
39 }  // namespace trace_processor
40 }  // namespace perfetto
41 
42 namespace base {
43 class RefCountedString;
44 
45 namespace trace_event {
46 
47 struct TraceCategory;
48 class TraceBuffer;
49 class TraceBufferChunk;
50 class TraceEvent;
51 class TraceEventMemoryOverhead;
52 class JsonStringOutputWriter;
53 
54 struct BASE_EXPORT TraceLogStatus {
55   TraceLogStatus();
56   ~TraceLogStatus();
57   uint32_t event_capacity;
58   uint32_t event_count;
59 };
60 
61 class BASE_EXPORT TraceLog :
62     public perfetto::TrackEventSessionObserver,
63     public MemoryDumpProvider {
64  public:
65   class ThreadLocalEventBuffer;
66 
67   // Argument passed to TraceLog::SetEnabled.
68   enum Mode : uint8_t {
69     // Enables normal tracing (recording trace events in the trace buffer).
70     // This is the only tracing mode supported now.
71     // TODO(khokhlov): Clean up all uses of tracing mode and remove this enum
72     // completely.
73     RECORDING_MODE = 1 << 0,
74   };
75 
76   static TraceLog* GetInstance();
77 
78   TraceLog(const TraceLog&) = delete;
79   TraceLog& operator=(const TraceLog&) = delete;
80 
81   // Retrieves a copy (for thread-safety) of the current TraceConfig.
82   TraceConfig GetCurrentTraceConfig() const;
83 
84   // Initializes the thread-local event buffer, if not already initialized and
85   // if the current thread supports that (has a message loop).
86   void InitializeThreadLocalEventBufferIfSupported();
87 
88   // See TraceConfig comments for details on how to control which categories
89   // will be traced. Only RECORDING_MODE is supported.
90   void SetEnabled(const TraceConfig& trace_config, uint8_t modes_to_enable);
91 
92   // Enable tracing using a customized Perfetto trace config. This allows, for
93   // example, enabling additional data sources and enabling protobuf output
94   // instead of the legacy JSON trace format.
95   void SetEnabled(const TraceConfig& trace_config,
96                   const perfetto::TraceConfig& perfetto_config);
97 
98   // Disables tracing for all categories. Only RECORDING_MODE is supported.
99   void SetDisabled();
100   void SetDisabled(uint8_t modes_to_disable);
101 
102   // Returns true if TraceLog is enabled on recording mode.
103   // Note: Returns false even if FILTERING_MODE is enabled.
IsEnabled()104   bool IsEnabled() {
105     // In SDK build we return true as soon as the datasource has been set up and
106     // we know the config. This doesn't necessarily mean that the tracing has
107     // already started.
108     // Note that TrackEvent::IsEnabled() can be true even earlier, before the
109     // OnSetup call, so we can't guarantee that we know the config by the time
110     // TrackEvent::IsEnabled() is true.
111     AutoLock lock(track_event_lock_);
112     return track_event_sessions_.size() > 0;
113   }
114 
115   // The number of times we have begun recording traces. If tracing is off,
116   // returns -1. If tracing is on, then it returns the number of times we have
117   // recorded a trace. By watching for this number to increment, you can
118   // passively discover when a new trace has begun. This is then used to
119   // implement the TRACE_EVENT_IS_NEW_TRACE() primitive.
120   int GetNumTracesRecorded();
121 
122   // Enabled state listeners give a callback when tracing is enabled or
123   // disabled. This can be used to tie into other library's tracing systems
124   // on-demand.
125   class BASE_EXPORT EnabledStateObserver {
126    public:
127     virtual ~EnabledStateObserver() = default;
128 
129     // Called just after the tracing system becomes enabled, outside of the
130     // |lock_|. TraceLog::IsEnabled() is true at this point.
131     virtual void OnTraceLogEnabled() = 0;
132 
133     // Called just after the tracing system disables, outside of the |lock_|.
134     // TraceLog::IsEnabled() is false at this point.
135     virtual void OnTraceLogDisabled() = 0;
136   };
137   // Adds an observer. Cannot be called from within the observer callback.
138   void AddEnabledStateObserver(EnabledStateObserver* listener);
139   // Removes an observer. Cannot be called from within the observer callback.
140   void RemoveEnabledStateObserver(EnabledStateObserver* listener);
141   // Adds an observer that is owned by TraceLog. This is useful for agents that
142   // implement tracing feature that needs to stay alive as long as TraceLog
143   // does.
144   void AddOwnedEnabledStateObserver(
145       std::unique_ptr<EnabledStateObserver> listener);
146   bool HasEnabledStateObserver(EnabledStateObserver* listener) const;
147 
148   // Asynchronous enabled state listeners. When tracing is enabled or disabled,
149   // for each observer, a task for invoking its appropriate callback is posted
150   // to the `SequencedTaskRunner` from which AddAsyncEnabledStateObserver() was
151   // called. This allows the observer to be safely destroyed, provided that it
152   // happens on the same `SequencedTaskRunner` that invoked
153   // AddAsyncEnabledStateObserver().
154   class BASE_EXPORT AsyncEnabledStateObserver {
155    public:
156     virtual ~AsyncEnabledStateObserver() = default;
157 
158     // Posted just after the tracing system becomes enabled, outside |lock_|.
159     // TraceLog::IsEnabled() is true at this point.
160     virtual void OnTraceLogEnabled() = 0;
161 
162     // Posted just after the tracing system becomes disabled, outside |lock_|.
163     // TraceLog::IsEnabled() is false at this point.
164     virtual void OnTraceLogDisabled() = 0;
165   };
166   // TODO(oysteine): This API originally needed to use WeakPtrs as the observer
167   // list was copied under the global trace lock, but iterated over outside of
168   // that lock so that observers could add tracing. The list is now protected by
169   // its own lock, so this can be changed to a raw ptr.
170   void AddAsyncEnabledStateObserver(
171       WeakPtr<AsyncEnabledStateObserver> listener);
172   void RemoveAsyncEnabledStateObserver(AsyncEnabledStateObserver* listener);
173   bool HasAsyncEnabledStateObserver(AsyncEnabledStateObserver* listener) const;
174 
175   // Observers that are notified when incremental state is cleared. This only
176   // happens when tracing using the perfetto backend.
177   class BASE_EXPORT IncrementalStateObserver {
178    public:
179     virtual ~IncrementalStateObserver() = default;
180 
181     // Called just after the tracing system has cleared incremental state, while
182     // a tracing session is active.
183     virtual void OnIncrementalStateCleared() = 0;
184   };
185   // Adds an observer. Cannot be called from within the observer callback.
186   void AddIncrementalStateObserver(IncrementalStateObserver* listener);
187   // Removes an observer. Cannot be called from within the observer callback.
188   void RemoveIncrementalStateObserver(IncrementalStateObserver* listener);
189 
190   TraceLogStatus GetStatus() const;
191 
192   // Computes an estimate of the size of the TraceLog including all the retained
193   // objects.
194   void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead);
195 
196   void SetArgumentFilterPredicate(
197       const ArgumentFilterPredicate& argument_filter_predicate);
198   ArgumentFilterPredicate GetArgumentFilterPredicate() const;
199 
200   void SetMetadataFilterPredicate(
201       const MetadataFilterPredicate& metadata_filter_predicate);
202   MetadataFilterPredicate GetMetadataFilterPredicate() const;
203 
204   void SetRecordHostAppPackageName(bool record_host_app_package_name);
205   bool ShouldRecordHostAppPackageName() const;
206 
207   // Flush all collected events to the given output callback. The callback will
208   // be called one or more times either synchronously or asynchronously from
209   // the current thread with IPC-bite-size chunks. The string format is
210   // undefined. Use TraceResultBuffer to convert one or more trace strings to
211   // JSON. The callback can be null if the caller doesn't want any data.
212   // Due to the implementation of thread-local buffers, flush can't be
213   // done when tracing is enabled. If called when tracing is enabled, the
214   // callback will be called directly with (empty_string, false) to indicate
215   // the end of this unsuccessful flush. Flush does the serialization
216   // on the same thread if the caller doesn't set use_worker_thread explicitly.
217   using OutputCallback =
218       base::RepeatingCallback<void(const scoped_refptr<base::RefCountedString>&,
219                                    bool has_more_events)>;
220   void Flush(const OutputCallback& cb, bool use_worker_thread = false);
221 
222   // Cancels tracing and discards collected data.
223   void CancelTracing(const OutputCallback& cb);
224 
225   using AddTraceEventOverrideFunction = void (*)(TraceEvent*,
226                                                  bool thread_will_flush,
227                                                  TraceEventHandle* handle);
228   using OnFlushFunction = void (*)();
229   using UpdateDurationFunction =
230       void (*)(const unsigned char* category_group_enabled,
231                const char* name,
232                TraceEventHandle handle,
233                PlatformThreadId thread_id,
234                bool explicit_timestamps,
235                const TimeTicks& now,
236                const ThreadTicks& thread_now);
237   // The callbacks will be called up until the point where the flush is
238   // finished, i.e. must be callable until OutputCallback is called with
239   // has_more_events==false.
240   void SetAddTraceEventOverrides(
241       const AddTraceEventOverrideFunction& add_event_override,
242       const OnFlushFunction& on_flush_callback,
243       const UpdateDurationFunction& update_duration_callback);
244 
245   // Called by TRACE_EVENT* macros, don't call this directly.
246   // The name parameter is a category group for example:
247   // TRACE_EVENT0("renderer,webkit", "WebViewImpl::HandleInputEvent")
248   static const unsigned char* GetCategoryGroupEnabled(const char* name);
249   static const char* GetCategoryGroupName(
250       const unsigned char* category_group_enabled);
GetBuiltinCategoryEnabled(const char * name)251   static constexpr const unsigned char* GetBuiltinCategoryEnabled(
252       const char* name) {
253     TraceCategory* builtin_category =
254         CategoryRegistry::GetBuiltinCategoryByName(name);
255     if (builtin_category)
256       return builtin_category->state_ptr();
257     return nullptr;
258   }
259 
260   // Called by TRACE_EVENT* macros, don't call this directly.
261   // If |copy| is set, |name|, |arg_name1| and |arg_name2| will be deep copied
262   // into the event; see "Memory scoping note" and TRACE_EVENT_COPY_XXX above.
263   bool ShouldAddAfterUpdatingState(char phase,
264                                    const unsigned char* category_group_enabled,
265                                    const char* name,
266                                    uint64_t id,
267                                    PlatformThreadId thread_id,
268                                    const TimeTicks timestamp,
269                                    TraceArguments* args);
270   TraceEventHandle AddTraceEvent(char phase,
271                                  const unsigned char* category_group_enabled,
272                                  const char* name,
273                                  const char* scope,
274                                  uint64_t id,
275                                  TraceArguments* args,
276                                  unsigned int flags);
277   TraceEventHandle AddTraceEventWithBindId(
278       char phase,
279       const unsigned char* category_group_enabled,
280       const char* name,
281       const char* scope,
282       uint64_t id,
283       uint64_t bind_id,
284       TraceArguments* args,
285       unsigned int flags);
286   TraceEventHandle AddTraceEventWithProcessId(
287       char phase,
288       const unsigned char* category_group_enabled,
289       const char* name,
290       const char* scope,
291       uint64_t id,
292       ProcessId process_id,
293       TraceArguments* args,
294       unsigned int flags);
295   TraceEventHandle AddTraceEventWithThreadIdAndTimestamp(
296       char phase,
297       const unsigned char* category_group_enabled,
298       const char* name,
299       const char* scope,
300       uint64_t id,
301       PlatformThreadId thread_id,
302       const TimeTicks& timestamp,
303       TraceArguments* args,
304       unsigned int flags);
305   TraceEventHandle AddTraceEventWithThreadIdAndTimestamp(
306       char phase,
307       const unsigned char* category_group_enabled,
308       const char* name,
309       const char* scope,
310       uint64_t id,
311       uint64_t bind_id,
312       PlatformThreadId thread_id,
313       const TimeTicks& timestamp,
314       TraceArguments* args,
315       unsigned int flags);
316   TraceEventHandle AddTraceEventWithThreadIdAndTimestamps(
317       char phase,
318       const unsigned char* category_group_enabled,
319       const char* name,
320       const char* scope,
321       uint64_t id,
322       uint64_t bind_id,
323       PlatformThreadId thread_id,
324       const TimeTicks& timestamp,
325       const ThreadTicks& thread_timestamp,
326       TraceArguments* args,
327       unsigned int flags);
328 
329   // Adds a metadata event that will be written when the trace log is flushed.
330   void AddMetadataEvent(const unsigned char* category_group_enabled,
331                         const char* name,
332                         TraceArguments* args,
333                         unsigned int flags);
334 
335   void UpdateTraceEventDuration(const unsigned char* category_group_enabled,
336                                 const char* name,
337                                 TraceEventHandle handle);
338 
339   void UpdateTraceEventDurationExplicit(
340       const unsigned char* category_group_enabled,
341       const char* name,
342       TraceEventHandle handle,
343       PlatformThreadId thread_id,
344       bool explicit_timestamps,
345       const TimeTicks& now,
346       const ThreadTicks& thread_now);
347 
process_id()348   ProcessId process_id() const { return process_id_; }
349 
process_labels()350   std::unordered_map<int, std::string> process_labels() const {
351     AutoLock lock(lock_);
352     return process_labels_;
353   }
354 
355   uint64_t MangleEventId(uint64_t id);
356 
357   // Exposed for unittesting:
358   // Allows clearing up our singleton instance.
359   static void ResetForTesting();
360 
361   // Allow tests to inspect TraceEvents.
362   TraceEvent* GetEventByHandle(TraceEventHandle handle);
363 
364   void SetProcessID(ProcessId process_id);
365 
366   // Process sort indices, if set, override the order of a process will appear
367   // relative to other processes in the trace viewer. Processes are sorted first
368   // on their sort index, ascending, then by their name, and then tid.
369   void SetProcessSortIndex(int sort_index);
370 
371   // Helper function to set process_name in base::CurrentProcess.
372   void OnSetProcessName(const std::string& process_name);
373 
374   // Processes can have labels in addition to their names. Use labels, for
375   // instance, to list out the web page titles that a process is handling.
376   int GetNewProcessLabelId();
377   void UpdateProcessLabel(int label_id, const std::string& current_label);
378   void RemoveProcessLabel(int label_id);
379 
380   // Thread sort indices, if set, override the order of a thread will appear
381   // within its process in the trace viewer. Threads are sorted first on their
382   // sort index, ascending, then by their name, and then tid.
383   void SetThreadSortIndex(PlatformThreadId thread_id, int sort_index);
384 
385   size_t GetObserverCountForTest() const;
386 
387   // Call this method if the current thread may block the message loop to
388   // prevent the thread from using the thread-local buffer because the thread
389   // may not handle the flush request in time causing lost of unflushed events.
390   void SetCurrentThreadBlocksMessageLoop();
391 
392 #if BUILDFLAG(IS_WIN)
393   // This function is called by the ETW exporting module whenever the ETW
394   // keyword (flags) changes. This keyword indicates which categories should be
395   // exported, so whenever it changes, we adjust accordingly.
396   void UpdateETWCategoryGroupEnabledFlags();
397 #endif
398 
399   // Replaces |logged_events_| with a new TraceBuffer for testing.
400   void SetTraceBufferForTesting(std::unique_ptr<TraceBuffer> trace_buffer);
401 
402   struct TrackEventSession {
403     uint32_t internal_instance_index;
404     perfetto::DataSourceConfig config;
405     perfetto::BackendType backend_type = perfetto::kUnspecifiedBackend;
406   };
407   std::vector<TrackEventSession> GetTrackEventSessions() const;
408 
409   // DEPRECATED. In the presence of multiple simultaneous sessions, this method
410   // returns only the first session's config. When no tracing sessions are
411   // active, returns an empty config for compatibility with legacy code.
412   // TODO(khokhlov): Remove this method and migrate all its uses to
413   // GetTrackEventSessions().
414   perfetto::DataSourceConfig GetCurrentTrackEventDataSourceConfig() const;
415   void InitializePerfettoIfNeeded();
416   bool IsPerfettoInitializedByTraceLog() const;
417   void SetEnabledImpl(const TraceConfig& trace_config,
418                       const perfetto::TraceConfig& perfetto_config);
419 
420   // perfetto::TrackEventSessionObserver implementation.
421   void OnSetup(const perfetto::DataSourceBase::SetupArgs&) override;
422   void OnStart(const perfetto::DataSourceBase::StartArgs&) override;
423   void OnStop(const perfetto::DataSourceBase::StopArgs&) override;
424 
425   // Called by the perfetto backend just after incremental state was cleared.
426   void OnIncrementalStateCleared();
427 
428  private:
429   typedef unsigned int InternalTraceOptions;
430 
431   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
432                            TraceBufferRingBufferGetReturnChunk);
433   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
434                            TraceBufferRingBufferHalfIteration);
435   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
436                            TraceBufferRingBufferFullIteration);
437   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture, TraceBufferVectorReportFull);
438   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
439                            ConvertTraceConfigToInternalOptions);
440   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture,
441                            TraceRecordAsMuchAsPossibleMode);
442   FRIEND_TEST_ALL_PREFIXES(TraceEventTestFixture, ConfigTraceBufferLimit);
443 
444   friend class base::NoDestructor<TraceLog>;
445 
446   // MemoryDumpProvider implementation.
447   bool OnMemoryDump(const MemoryDumpArgs& args,
448                     ProcessMemoryDump* pmd) override;
449 
450   // Enable/disable each category group based on the current mode_,
451   // category_filter_ and event_filters_enabled_.
452   // Enable the category group in the recording mode if category_filter_ matches
453   // the category group, is not null.
454   void UpdateCategoryRegistry();
455   void UpdateCategoryState(TraceCategory* category);
456 
457   InternalTraceOptions GetInternalOptionsFromTraceConfig(
458       const TraceConfig& config);
459 
460   class OptionalAutoLock;
461   struct RegisteredAsyncObserver;
462 
463   explicit TraceLog(int generation);
464   ~TraceLog() override;
465   void AddMetadataEventsWhileLocked() EXCLUSIVE_LOCKS_REQUIRED(lock_);
466   template <typename T>
467   void AddMetadataEventWhileLocked(PlatformThreadId thread_id,
468                                    const char* metadata_name,
469                                    const char* arg_name,
470                                    const T& value)
471       EXCLUSIVE_LOCKS_REQUIRED(lock_);
472 
trace_options()473   InternalTraceOptions trace_options() const {
474     return trace_options_.load(std::memory_order_relaxed);
475   }
476 
trace_buffer()477   TraceBuffer* trace_buffer() const { return logged_events_.get(); }
478   TraceBuffer* CreateTraceBuffer();
479 
480   std::string EventToConsoleMessage(char phase,
481                                     const TimeTicks& timestamp,
482                                     TraceEvent* trace_event);
483 
484   TraceEvent* AddEventToThreadSharedChunkWhileLocked(TraceEventHandle* handle,
485                                                      bool check_buffer_is_full)
486       EXCLUSIVE_LOCKS_REQUIRED(lock_);
487   void CheckIfBufferIsFullWhileLocked() EXCLUSIVE_LOCKS_REQUIRED(lock_);
488   void SetDisabledWhileLocked(uint8_t modes) EXCLUSIVE_LOCKS_REQUIRED(lock_);
489 
490   TraceEvent* GetEventByHandleInternal(TraceEventHandle handle,
491                                        OptionalAutoLock* lock);
492 
493   void FlushInternal(const OutputCallback& cb,
494                      bool use_worker_thread,
495                      bool discard_events);
496 
497   void OnTraceData(const char* data, size_t size, bool has_more);
498 
499   // |generation| is used in the following callbacks to check if the callback
500   // is called for the flush of the current |logged_events_|.
501   void FlushCurrentThread(int generation, bool discard_events);
502   // Usually it runs on a different thread.
503   static void ConvertTraceEventsToTraceFormat(
504       std::unique_ptr<TraceBuffer> logged_events,
505       const TraceLog::OutputCallback& flush_output_callback,
506       const ArgumentFilterPredicate& argument_filter_predicate);
507   void FinishFlush(int generation, bool discard_events);
508   void OnFlushTimeout(int generation, bool discard_events);
509 
generation()510   int generation() const {
511     return generation_.load(std::memory_order_relaxed);
512   }
CheckGeneration(int generation)513   bool CheckGeneration(int generation) const {
514     return generation == this->generation();
515   }
516   void UseNextTraceBuffer();
517 
OffsetNow()518   TimeTicks OffsetNow() const {
519     // This should be TRACE_TIME_TICKS_NOW but include order makes that hard.
520     return OffsetTimestamp(base::subtle::TimeTicksNowIgnoringOverride());
521   }
OffsetTimestamp(const TimeTicks & timestamp)522   TimeTicks OffsetTimestamp(const TimeTicks& timestamp) const {
523     return timestamp - time_offset_;
524   }
525 
526   // Internal representation of trace options since we store the currently used
527   // trace option as an AtomicWord.
528   static const InternalTraceOptions kInternalNone;
529   static const InternalTraceOptions kInternalRecordUntilFull;
530   static const InternalTraceOptions kInternalRecordContinuously;
531   static const InternalTraceOptions kInternalEchoToConsole;
532   static const InternalTraceOptions kInternalRecordAsMuchAsPossible;
533   static const InternalTraceOptions kInternalEnableArgumentFilter;
534 
535   // This lock protects TraceLog member accesses (except for members protected
536   // by thread_info_lock_) from arbitrary threads.
537   mutable Lock lock_;
538   Lock thread_info_lock_;
539   bool enabled_{false};
540   int num_traces_recorded_{0};
541   std::unique_ptr<TraceBuffer> logged_events_;
542   std::vector<std::unique_ptr<TraceEvent>> metadata_events_;
543 
544   // The lock protects observers access.
545   mutable Lock observers_lock_;
546   bool dispatching_to_observers_ = false;
547   std::vector<raw_ptr<EnabledStateObserver, VectorExperimental>>
548       enabled_state_observers_ GUARDED_BY(observers_lock_);
549   std::map<AsyncEnabledStateObserver*, RegisteredAsyncObserver> async_observers_
550       GUARDED_BY(observers_lock_);
551   // Manages ownership of the owned observers. The owned observers will also be
552   // added to |enabled_state_observers_|.
553   std::vector<std::unique_ptr<EnabledStateObserver>>
554       owned_enabled_state_observer_copy_ GUARDED_BY(observers_lock_);
555   std::vector<raw_ptr<IncrementalStateObserver, VectorExperimental>>
556       incremental_state_observers_ GUARDED_BY(observers_lock_);
557 
558   int next_process_label_id_ GUARDED_BY(lock_) = 0;
559   std::unordered_map<int, std::string> process_labels_;
560   int process_sort_index_;
561   std::unordered_map<PlatformThreadId, int> thread_sort_indices_;
562   std::unordered_map<PlatformThreadId, std::string> thread_names_
563       GUARDED_BY(thread_info_lock_);
564 
565   // The following two maps are used only when ECHO_TO_CONSOLE.
566   std::unordered_map<PlatformThreadId, base::stack<TimeTicks>>
567       thread_event_start_times_ GUARDED_BY(thread_info_lock_);
568   std::unordered_map<std::string, size_t> thread_colors_
569       GUARDED_BY(thread_info_lock_);
570 
571   TimeTicks buffer_limit_reached_timestamp_;
572 
573   // XORed with TraceID to make it unlikely to collide with other processes.
574   uint64_t process_id_hash_;
575 
576   ProcessId process_id_;
577 
578   TimeDelta time_offset_;
579 
580   std::atomic<InternalTraceOptions> trace_options_;
581 
582   TraceConfig trace_config_;
583 
584   // Contains task runners for the threads that have had at least one event
585   // added into the local event buffer.
586   std::unordered_map<PlatformThreadId, scoped_refptr<SingleThreadTaskRunner>>
587       thread_task_runners_;
588 
589   // For events which can't be added into the thread local buffer, e.g. events
590   // from threads without a message loop.
591   std::unique_ptr<TraceBufferChunk> thread_shared_chunk_;
592   size_t thread_shared_chunk_index_;
593 
594   // Set when asynchronous Flush is in progress.
595   OutputCallback flush_output_callback_;
596   scoped_refptr<SequencedTaskRunner> flush_task_runner_;
597   ArgumentFilterPredicate argument_filter_predicate_;
598   MetadataFilterPredicate metadata_filter_predicate_;
599   bool record_host_app_package_name_{false};
600   std::atomic<int> generation_;
601   bool use_worker_thread_;
602   std::atomic<AddTraceEventOverrideFunction> add_trace_event_override_{nullptr};
603   std::atomic<OnFlushFunction> on_flush_override_{nullptr};
604   std::atomic<UpdateDurationFunction> update_duration_override_{nullptr};
605 
606   std::unique_ptr<perfetto::TracingSession> tracing_session_;
607   perfetto::TraceConfig perfetto_config_;
608   std::vector<TrackEventSession> track_event_sessions_
609       GUARDED_BY(track_event_lock_);
610   int active_track_event_sessions_ = 0;
611   mutable Lock track_event_lock_;
612 #if BUILDFLAG(USE_PERFETTO_TRACE_PROCESSOR)
613   std::unique_ptr<perfetto::trace_processor::TraceProcessorStorage>
614       trace_processor_;
615   std::unique_ptr<JsonStringOutputWriter> json_output_writer_;
616   OutputCallback proto_output_callback_;
617 #endif  // BUILDFLAG(USE_PERFETTO_TRACE_PROCESSOR)
618 
619 #if BUILDFLAG(IS_ANDROID)
620   std::optional<TraceConfig> atrace_startup_config_;
621 #endif
622 };
623 
624 }  // namespace trace_event
625 }  // namespace base
626 
627 #endif  // BASE_TRACE_EVENT_TRACE_LOG_H_
628