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