trace_log.h 27 KB

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