• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 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_TASK_COMMON_TASK_ANNOTATOR_H_
6 #define BASE_TASK_COMMON_TASK_ANNOTATOR_H_
7 
8 #include <stdint.h>
9 
10 #include "base/auto_reset.h"
11 #include "base/base_export.h"
12 #include "base/memory/raw_ptr.h"
13 #include "base/memory/raw_ref.h"
14 #include "base/pending_task.h"
15 #include "base/strings/string_piece.h"
16 #include "base/time/tick_clock.h"
17 #include "base/trace_event/base_tracing.h"
18 
19 namespace base {
20 
21 // Constant used to measure which long-running tasks should be traced.
22 constexpr TimeDelta kMaxTaskDurationTimeDelta = Milliseconds(4);
23 
24 // Implements common debug annotations for posted tasks. This includes data
25 // such as task origins, IPC message contexts, queueing durations and memory
26 // usage.
27 class BASE_EXPORT TaskAnnotator {
28  public:
29   class ObserverForTesting {
30    public:
31     // Invoked just before RunTask() in the scope in which the task is about to
32     // be executed.
33     virtual void BeforeRunTask(const PendingTask* pending_task) = 0;
34   };
35 
36   // This is used to set the |ipc_hash| field for PendingTasks. It is intended
37   // to be used only from within generated IPC handler dispatch code.
38   class ScopedSetIpcHash;
39 
40   // This is used to track long-running browser-UI tasks. It is intended to
41   // be used for low-overhead logging to produce longer traces, particularly to
42   // help the scroll jank reduction effort.
43   class LongTaskTracker;
44 
45   static const PendingTask* CurrentTaskForThread();
46 
47   static void OnIPCReceived(const char* interface_name,
48                             uint32_t (*method_info)(),
49                             bool is_response);
50 
51   static void MarkCurrentTaskAsInterestingForTracing();
52 
53   TaskAnnotator();
54 
55   TaskAnnotator(const TaskAnnotator&) = delete;
56   TaskAnnotator& operator=(const TaskAnnotator&) = delete;
57 
58   ~TaskAnnotator();
59 
60   // Called to indicate that a task is about to be queued to run in the future,
61   // giving one last chance for this TaskAnnotator to add metadata to
62   // |pending_task| before it is moved into the queue.
63   void WillQueueTask(perfetto::StaticString trace_event_name,
64                      PendingTask* pending_task);
65 
66   // Creates a process-wide unique ID to represent this task in trace events.
67   // This will be mangled with a Process ID hash to reduce the likelyhood of
68   // colliding with TaskAnnotator pointers on other processes. Callers may use
69   // this when generating their own flow events (i.e. when passing
70   // |queue_function == nullptr| in above methods).
71   uint64_t GetTaskTraceID(const PendingTask& task) const;
72 
73   // Run the given task, emitting the toplevel trace event and additional
74   // trace event arguments. Like for TRACE_EVENT macros, all of the arguments
75   // are used (i.e. lambdas are invoked) before this function exits, so it's
76   // safe to pass reference-capturing lambdas here.
77   template <typename... Args>
RunTask(perfetto::StaticString event_name,PendingTask & pending_task,Args &&...args)78   void RunTask(perfetto::StaticString event_name,
79                PendingTask& pending_task,
80                Args&&... args) {
81     TRACE_EVENT(
82         "toplevel", event_name,
83         [&](perfetto::EventContext& ctx) {
84           EmitTaskLocation(ctx, pending_task);
85           MaybeEmitIncomingTaskFlow(ctx, pending_task);
86           MaybeEmitIPCHashAndDelay(ctx, pending_task);
87         },
88         std::forward<Args>(args)...);
89     RunTaskImpl(pending_task);
90   }
91 
92  private:
93   friend class TaskAnnotatorBacktraceIntegrationTest;
94 
95   // Run a previously queued task.
96   NOT_TAIL_CALLED void RunTaskImpl(PendingTask& pending_task);
97 
98   // Registers an ObserverForTesting that will be invoked by all TaskAnnotators'
99   // RunTask(). This registration and the implementation of BeforeRunTask() are
100   // responsible to ensure thread-safety.
101   static void RegisterObserverForTesting(ObserverForTesting* observer);
102   static void ClearObserverForTesting();
103 
104 #if BUILDFLAG(ENABLE_BASE_TRACING)
105   // TRACE_EVENT argument helper, writing the task location data into
106   // EventContext.
107   static void EmitTaskLocation(perfetto::EventContext& ctx,
108                                const PendingTask& task);
109 
110   // TRACE_EVENT argument helper, writing the incoming task flow information
111   // into EventContext if toplevel.flow category is enabled.
112   void MaybeEmitIncomingTaskFlow(perfetto::EventContext& ctx,
113                                  const PendingTask& task) const;
114 
115   void MaybeEmitIPCHashAndDelay(perfetto::EventContext& ctx,
116                                 const PendingTask& task) const;
117 #endif  //  BUILDFLAG(ENABLE_BASE_TRACING)
118 };
119 
120 class BASE_EXPORT [[maybe_unused, nodiscard]] TaskAnnotator::ScopedSetIpcHash {
121  public:
122   explicit ScopedSetIpcHash(uint32_t ipc_hash);
123 
124   // Compile-time-const string identifying the current IPC context. Not always
125   // available due to binary size constraints, so IPC hash might be set instead.
126   explicit ScopedSetIpcHash(const char* ipc_interface_name);
127 
128   ScopedSetIpcHash(const ScopedSetIpcHash&) = delete;
129   ScopedSetIpcHash& operator=(const ScopedSetIpcHash&) = delete;
130 
131   ~ScopedSetIpcHash();
132 
GetIpcHash()133   uint32_t GetIpcHash() const { return ipc_hash_; }
GetIpcInterfaceName()134   const char* GetIpcInterfaceName() const { return ipc_interface_name_; }
135 
136   static uint32_t MD5HashMetricName(base::StringPiece name);
137 
138  private:
139   ScopedSetIpcHash(uint32_t ipc_hash, const char* ipc_interface_name);
140 
141   const AutoReset<ScopedSetIpcHash*> resetter_;
142   uint32_t ipc_hash_;
143   const char* ipc_interface_name_;
144 };
145 
146 class BASE_EXPORT [[maybe_unused, nodiscard]] TaskAnnotator::LongTaskTracker {
147  public:
148   explicit LongTaskTracker(const TickClock* tick_clock,
149                            PendingTask& pending_task,
150                            TaskAnnotator* task_annotator);
151 
152   LongTaskTracker(const LongTaskTracker&) = delete;
153 
154   ~LongTaskTracker();
155 
156   void SetIpcDetails(const char* interface_name,
157                      uint32_t (*method_info)(),
158                      bool is_response);
159 
160   void MaybeTraceInterestingTaskDetails();
161 
162   // In long-task tracking, not every task (including its queue time) will be
163   // recorded in a trace. If a particular task + queue time needs to be
164   // recorded, flag it explicitly. For example, input tasks are required for
165   // calculating scroll jank metrics.
166   bool is_interesting_task = false;
167 
168  private:
169   void EmitReceivedIPCDetails(perfetto::EventContext& ctx);
170 
171   const AutoReset<LongTaskTracker*> resetter_;
172 
173   // For tracking task duration
174   raw_ptr<const TickClock> tick_clock_;  // Not owned.
175   TimeTicks task_start_time_;
176   TimeTicks task_end_time_;
177 
178   // Tracing variables.
179 
180   // Use this to ensure that tracing and NowTicks() are not called
181   // unnecessarily.
182   bool is_tracing_;
183   const char* ipc_interface_name_ = nullptr;
184   uint32_t ipc_hash_ = 0;
185 
186   // IPC method info to retrieve IPC hash and method address from trace, if
187   // known. Note that this will not compile in the Native client.
188   uint32_t (*ipc_method_info_)();
189   bool is_response_ = false;
190   [[maybe_unused]] const raw_ref<PendingTask> pending_task_;
191   [[maybe_unused]] raw_ptr<TaskAnnotator> task_annotator_;
192 };
193 
194 }  // namespace base
195 
196 #endif  // BASE_TASK_COMMON_TASK_ANNOTATOR_H_
197