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