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 #include "base/task/common/task_annotator.h"
6
7 #include <stdint.h>
8
9 #include <algorithm>
10 #include <array>
11 #include <string_view>
12
13 #include "base/auto_reset.h"
14 #include "base/check_op.h"
15 #include "base/compiler_specific.h"
16 #include "base/containers/span.h"
17 #include "base/debug/alias.h"
18 #include "base/hash/md5.h"
19 #include "base/logging.h"
20 #include "base/metrics/metrics_hashes.h"
21 #include "base/ranges/algorithm.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/base_tracing.h"
24 #include "base/tracing_buildflags.h"
25
26 #if BUILDFLAG(ENABLE_BASE_TRACING)
27 #include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_mojo_event_info.pbzero.h" // nogncheck
28 #endif
29
30 namespace base {
31
32 namespace {
33
34 TaskAnnotator::ObserverForTesting* g_task_annotator_observer = nullptr;
35
36 // The PendingTask currently in progress on each thread. Used to allow creating
37 // a breadcrumb of program counters on the stack to help identify a task's
38 // origin in crashes.
39 constinit thread_local const PendingTask* current_pending_task = nullptr;
40
41 // Scoped IPC-related data (IPC hash and/or IPC interface name). IPC hash or
42 // interface name can be known before the associated task object is created;
43 // thread-local so that this data can be affixed to the associated task.
44 constinit thread_local TaskAnnotator::ScopedSetIpcHash*
45 current_scoped_ipc_hash = nullptr;
46
47 constinit thread_local TaskAnnotator::LongTaskTracker*
48 current_long_task_tracker = nullptr;
49
50 // These functions can be removed, and the calls below replaced with direct
51 // variable accesses, once the MSAN workaround is not necessary.
GetCurrentScopedIpcHash()52 TaskAnnotator::ScopedSetIpcHash* GetCurrentScopedIpcHash() {
53 // Workaround false-positive MSAN use-of-uninitialized-value on
54 // thread_local storage for loaded libraries:
55 // https://github.com/google/sanitizers/issues/1265
56 MSAN_UNPOISON(¤t_scoped_ipc_hash,
57 sizeof(TaskAnnotator::ScopedSetIpcHash*));
58
59 return current_scoped_ipc_hash;
60 }
61
GetCurrentLongTaskTracker()62 TaskAnnotator::LongTaskTracker* GetCurrentLongTaskTracker() {
63 // Workaround false-positive MSAN use-of-uninitialized-value on
64 // thread_local storage for loaded libraries:
65 // https://github.com/google/sanitizers/issues/1265
66 MSAN_UNPOISON(¤t_long_task_tracker,
67 sizeof(TaskAnnotator::LongTaskTracker*));
68
69 return current_long_task_tracker;
70 }
71
72 #if BUILDFLAG(ENABLE_BASE_TRACING)
ToProtoEnum(subtle::DelayPolicy type)73 perfetto::protos::pbzero::ChromeTaskAnnotator::DelayPolicy ToProtoEnum(
74 subtle::DelayPolicy type) {
75 using ProtoType = perfetto::protos::pbzero::ChromeTaskAnnotator::DelayPolicy;
76 switch (type) {
77 case subtle::DelayPolicy::kFlexibleNoSooner:
78 return ProtoType::FLEXIBLE_NO_SOONER;
79 case subtle::DelayPolicy::kFlexiblePreferEarly:
80 return ProtoType::FLEXIBLE_PREFER_EARLY;
81 case subtle::DelayPolicy::kPrecise:
82 return ProtoType::PRECISE;
83 }
84 }
85 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
86
87 } // namespace
88
CurrentTaskForThread()89 const PendingTask* TaskAnnotator::CurrentTaskForThread() {
90 // Workaround false-positive MSAN use-of-uninitialized-value on
91 // thread_local storage for loaded libraries:
92 // https://github.com/google/sanitizers/issues/1265
93 MSAN_UNPOISON(¤t_pending_task, sizeof(PendingTask*));
94
95 return current_pending_task;
96 }
97
SetCurrentTaskForThread(PassKey<sequence_manager::internal::WorkQueue>,const PendingTask * pending_task)98 void TaskAnnotator::SetCurrentTaskForThread(
99 PassKey<sequence_manager::internal::WorkQueue>,
100 const PendingTask* pending_task) {
101 current_pending_task = pending_task;
102 }
103
OnIPCReceived(const char * interface_name,uint32_t (* method_info)(),bool is_response)104 void TaskAnnotator::OnIPCReceived(const char* interface_name,
105 uint32_t (*method_info)(),
106 bool is_response) {
107 auto* const tracker = GetCurrentLongTaskTracker();
108 if (!tracker) {
109 return;
110 }
111
112 tracker->SetIpcDetails(interface_name, method_info, is_response);
113 }
114
MarkCurrentTaskAsInterestingForTracing()115 void TaskAnnotator::MarkCurrentTaskAsInterestingForTracing() {
116 auto* const tracker = GetCurrentLongTaskTracker();
117 if (!tracker) {
118 return;
119 }
120
121 tracker->is_interesting_task = true;
122 }
123
124 TaskAnnotator::TaskAnnotator() = default;
125 TaskAnnotator::~TaskAnnotator() = default;
126
WillQueueTask(perfetto::StaticString trace_event_name,TaskMetadata * pending_task)127 void TaskAnnotator::WillQueueTask(perfetto::StaticString trace_event_name,
128 TaskMetadata* pending_task) {
129 DCHECK(pending_task);
130 TRACE_EVENT_INSTANT(
131 "toplevel.flow", trace_event_name,
132 perfetto::Flow::ProcessScoped(GetTaskTraceID(*pending_task)));
133
134 DCHECK(!pending_task->task_backtrace[0])
135 << "Task backtrace was already set, task posted twice??";
136 if (pending_task->task_backtrace[0])
137 return;
138
139 DCHECK(!pending_task->ipc_interface_name);
140 DCHECK(!pending_task->ipc_hash);
141 const auto* const hash = GetCurrentScopedIpcHash();
142 if (hash) {
143 pending_task->ipc_interface_name = hash->GetIpcInterfaceName();
144 pending_task->ipc_hash = hash->GetIpcHash();
145 }
146
147 const auto* parent_task = CurrentTaskForThread();
148 if (!parent_task)
149 return;
150
151 pending_task->task_backtrace[0] = parent_task->posted_from.program_counter();
152 std::copy(parent_task->task_backtrace.begin(),
153 parent_task->task_backtrace.end() - 1,
154 pending_task->task_backtrace.begin() + 1);
155 pending_task->task_backtrace_overflow =
156 parent_task->task_backtrace_overflow ||
157 parent_task->task_backtrace.back() != nullptr;
158 }
159
RunTaskImpl(PendingTask & pending_task)160 void TaskAnnotator::RunTaskImpl(PendingTask& pending_task) {
161 TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION(
162 pending_task.posted_from.file_name());
163
164 // Before running the task, store the IPC context and the task backtrace with
165 // the chain of PostTasks that resulted in this call and deliberately alias it
166 // to ensure it is on the stack if the task crashes. Be careful not to assume
167 // that the variable itself will have the expected value when displayed by the
168 // optimizer in an optimized build. Look at a memory dump of the stack.
169 static constexpr int kStackTaskTraceSnapshotSize =
170 PendingTask::kTaskBacktraceLength + 4;
171 std::array<const void*, kStackTaskTraceSnapshotSize> task_backtrace;
172
173 // Store a marker to locate |task_backtrace| content easily on a memory
174 // dump. The layout is as follows:
175 //
176 // +------------ +----+---------+-----+-----------+----------+-------------+
177 // | Head Marker | PC | frame 0 | ... | frame N-1 | IPC hash | Tail Marker |
178 // +------------ +----+---------+-----+-----------+----------+-------------+
179 //
180 // Markers glossary (compliments of wez):
181 // cool code,do it dude!
182 // 0x c001 c0de d0 17 d00d
183 // o dude,i did it biig
184 // 0x 0 d00d 1 d1d 17 8119
185 task_backtrace.front() = reinterpret_cast<void*>(0xc001c0ded017d00d);
186 task_backtrace.back() = reinterpret_cast<void*>(0x0d00d1d1d178119);
187
188 task_backtrace[1] = pending_task.posted_from.program_counter();
189 ranges::copy(pending_task.task_backtrace, task_backtrace.begin() + 2);
190 task_backtrace[kStackTaskTraceSnapshotSize - 2] =
191 reinterpret_cast<void*>(pending_task.ipc_hash);
192 debug::Alias(&task_backtrace);
193
194 // Record the task time in convenient units. This can be compared to times
195 // stored in places like ReportThreadHang() and BrowserMain() when analyzing
196 // hangs.
197 const int64_t task_time =
198 pending_task.GetDesiredExecutionTime().since_origin().InSeconds();
199 base::debug::Alias(&task_time);
200
201 {
202 const AutoReset<const PendingTask*> resetter(¤t_pending_task,
203 &pending_task);
204
205 if (g_task_annotator_observer) {
206 g_task_annotator_observer->BeforeRunTask(&pending_task);
207 }
208 std::move(pending_task.task).Run();
209 }
210
211 // Stomp the markers. Otherwise they can stick around on the unused parts of
212 // stack and cause |task_backtrace| to be associated with an unrelated stack
213 // sample on this thread later in the event of a crash. Alias once again after
214 // these writes to make sure the compiler doesn't optimize them out (unused
215 // writes to a local variable).
216 task_backtrace.front() = nullptr;
217 task_backtrace.back() = nullptr;
218 debug::Alias(&task_backtrace);
219 }
220
GetTaskTraceID(const TaskMetadata & task) const221 uint64_t TaskAnnotator::GetTaskTraceID(const TaskMetadata& task) const {
222 return (static_cast<uint64_t>(task.sequence_num) << 32) |
223 ((static_cast<uint64_t>(reinterpret_cast<intptr_t>(this)) << 32) >>
224 32);
225 }
226
227 // static
RegisterObserverForTesting(ObserverForTesting * observer)228 void TaskAnnotator::RegisterObserverForTesting(ObserverForTesting* observer) {
229 DCHECK(!g_task_annotator_observer);
230 g_task_annotator_observer = observer;
231 }
232
233 // static
ClearObserverForTesting()234 void TaskAnnotator::ClearObserverForTesting() {
235 g_task_annotator_observer = nullptr;
236 }
237
238 #if BUILDFLAG(ENABLE_BASE_TRACING)
239 // TRACE_EVENT argument helper, writing the task location data into
240 // EventContext.
EmitTaskLocation(perfetto::EventContext & ctx,const PendingTask & task)241 void TaskAnnotator::EmitTaskLocation(perfetto::EventContext& ctx,
242 const PendingTask& task) {
243 ctx.event()->set_task_execution()->set_posted_from_iid(
244 base::trace_event::InternedSourceLocation::Get(&ctx, task.posted_from));
245 }
246
247 // TRACE_EVENT argument helper, writing the incoming task flow information
248 // into EventContext if toplevel.flow category is enabled.
MaybeEmitIncomingTaskFlow(perfetto::EventContext & ctx,const PendingTask & task) const249 void TaskAnnotator::MaybeEmitIncomingTaskFlow(perfetto::EventContext& ctx,
250 const PendingTask& task) const {
251 static const uint8_t* flow_enabled =
252 TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED("toplevel.flow");
253 if (!*flow_enabled)
254 return;
255
256 perfetto::Flow::ProcessScoped(GetTaskTraceID(task))(ctx);
257 }
258
259 // static
EmitTaskTimingDetails(perfetto::EventContext & ctx)260 void TaskAnnotator::EmitTaskTimingDetails(perfetto::EventContext& ctx) {
261 auto* const pending_task = CurrentTaskForThread();
262 if (!pending_task) {
263 return;
264 }
265
266 base::TimeTicks event_start_time = base::TimeTicks::Now();
267 const base::TimeTicks queue_time = pending_task->queue_time;
268
269 perfetto::protos::pbzero::CurrentTask* current_task = nullptr;
270
271 if (!queue_time.is_null()) {
272 current_task = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>()
273 ->set_current_task();
274 current_task->set_task_queueing_time_us(static_cast<uint64_t>(
275 (event_start_time - queue_time).InMicroseconds()));
276 current_task->set_task_queued_time_us(
277 static_cast<uint64_t>(queue_time.since_origin().InMicroseconds()));
278 }
279
280 auto* const tracker = GetCurrentLongTaskTracker();
281 if (tracker) {
282 const base::TimeTicks task_start_time = tracker->GetTaskStartTime();
283 if (!current_task) {
284 current_task = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>()
285 ->set_current_task();
286 }
287 current_task->set_event_offset_from_task_start_time_us(
288 static_cast<uint64_t>(
289 (event_start_time - task_start_time).InMicroseconds()));
290 current_task->set_task_start_time_us(
291 static_cast<uint64_t>(task_start_time.since_origin().InMicroseconds()));
292 }
293 }
294
295 // static
MaybeEmitDelayAndPolicy(perfetto::EventContext & ctx,const PendingTask & task)296 void TaskAnnotator::MaybeEmitDelayAndPolicy(perfetto::EventContext& ctx,
297 const PendingTask& task) {
298 if (task.delayed_run_time.is_null()) {
299 return;
300 }
301 auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
302 auto* annotator = event->set_chrome_task_annotator();
303 annotator->set_task_delay_us(static_cast<uint64_t>(
304 (task.delayed_run_time - task.queue_time).InMicroseconds()));
305 annotator->set_delay_policy(ToProtoEnum(task.delay_policy));
306 }
307
MaybeEmitIPCHash(perfetto::EventContext & ctx,const PendingTask & task) const308 void TaskAnnotator::MaybeEmitIPCHash(perfetto::EventContext& ctx,
309 const PendingTask& task) const {
310 static const uint8_t* toplevel_ipc_enabled =
311 TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
312 TRACE_DISABLED_BY_DEFAULT("toplevel.ipc"));
313 if (!*toplevel_ipc_enabled)
314 return;
315
316 auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
317 auto* annotator = event->set_chrome_task_annotator();
318 annotator->set_ipc_hash(task.ipc_hash);
319 }
320 #endif // BUILDFLAG(ENABLE_BASE_TRACING)
321
ScopedSetIpcHash(uint32_t ipc_hash)322 TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(uint32_t ipc_hash)
323 : ScopedSetIpcHash(ipc_hash, nullptr) {}
324
ScopedSetIpcHash(const char * ipc_interface_name)325 TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(
326 const char* ipc_interface_name)
327 : ScopedSetIpcHash(0, ipc_interface_name) {}
328
ScopedSetIpcHash(uint32_t ipc_hash,const char * ipc_interface_name)329 TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(
330 uint32_t ipc_hash,
331 const char* ipc_interface_name)
332 : resetter_(¤t_scoped_ipc_hash, this),
333 ipc_hash_(ipc_hash),
334 ipc_interface_name_(ipc_interface_name) {}
335
336 // Static
MD5HashMetricName(std::string_view name)337 uint32_t TaskAnnotator::ScopedSetIpcHash::MD5HashMetricName(
338 std::string_view name) {
339 return HashMetricNameAs32Bits(name);
340 }
341
~ScopedSetIpcHash()342 TaskAnnotator::ScopedSetIpcHash::~ScopedSetIpcHash() {
343 DCHECK_EQ(this, GetCurrentScopedIpcHash());
344 }
345
LongTaskTracker(const TickClock * tick_clock,PendingTask & pending_task,TaskAnnotator * task_annotator,TimeTicks task_start_time)346 TaskAnnotator::LongTaskTracker::LongTaskTracker(const TickClock* tick_clock,
347 PendingTask& pending_task,
348 TaskAnnotator* task_annotator,
349 TimeTicks task_start_time)
350 : resetter_(¤t_long_task_tracker, this),
351 tick_clock_(tick_clock),
352 task_start_time_(task_start_time),
353 pending_task_(pending_task),
354 task_annotator_(task_annotator) {}
355
~LongTaskTracker()356 TaskAnnotator::LongTaskTracker::~LongTaskTracker() {
357 DCHECK_EQ(this, GetCurrentLongTaskTracker());
358
359 // Use this to ensure that NowTicks() are not called
360 // unnecessarily.
361 bool is_tracing = false;
362 TRACE_EVENT_CATEGORY_GROUP_ENABLED("scheduler.long_tasks", &is_tracing);
363
364 if (!is_tracing) {
365 return;
366 }
367
368 task_end_time_ = tick_clock_->NowTicks();
369 MaybeTraceInterestingTaskDetails();
370
371 if ((task_end_time_ - task_start_time_) >= kMaxTaskDurationTimeDelta) {
372 TRACE_EVENT_BEGIN("scheduler.long_tasks", "LongTaskTracker",
373 perfetto::Track::ThreadScoped(task_annotator_),
374 task_start_time_, [&](perfetto::EventContext& ctx) {
375 TaskAnnotator::EmitTaskLocation(ctx, pending_task_);
376 EmitReceivedIPCDetails(ctx);
377 });
378 TRACE_EVENT_END("scheduler.long_tasks",
379 perfetto::Track::ThreadScoped(task_annotator_),
380 task_end_time_);
381 }
382 }
383
SetIpcDetails(const char * interface_name,uint32_t (* method_info)(),bool is_response)384 void TaskAnnotator::LongTaskTracker::SetIpcDetails(const char* interface_name,
385 uint32_t (*method_info)(),
386 bool is_response) {
387 ipc_interface_name_ = interface_name;
388 is_response_ = is_response;
389
390 if (!method_info)
391 return;
392
393 ipc_hash_ = (*method_info)();
394 ipc_method_info_ = method_info;
395 }
396
EmitReceivedIPCDetails(perfetto::EventContext & ctx)397 void TaskAnnotator::LongTaskTracker::EmitReceivedIPCDetails(
398 perfetto::EventContext& ctx) {
399 if (!ipc_interface_name_ || !ipc_hash_ || !ipc_method_info_)
400 return;
401 #if BUILDFLAG(ENABLE_BASE_TRACING) && !BUILDFLAG(IS_NACL)
402 // Emit all of the IPC hash information if this task
403 // comes from a mojo interface.
404 auto* info = ctx.event()->set_chrome_mojo_event_info();
405 info->set_mojo_interface_tag(ipc_interface_name_);
406 info->set_ipc_hash(ipc_hash_);
407 info->set_is_reply(is_response_);
408
409 // The Native client will not build as the relevant implementation of
410 // base::ModuleCache::CreateModuleForAddress is not implemented for it.
411 // Thus the below code must be included on a conditional basis.
412 const auto ipc_method_address = reinterpret_cast<uintptr_t>(ipc_method_info_);
413 const std::optional<size_t> location_iid =
414 base::trace_event::InternedUnsymbolizedSourceLocation::Get(
415 &ctx, ipc_method_address);
416 if (location_iid) {
417 info->set_mojo_interface_method_iid(*location_iid);
418 }
419 #endif
420 }
421
422 // This method is used to record the queueing time and task start time for tasks
423 // that may be of interest during a trace, even if they are not considered long
424 // tasks. For example, input - the queue time and flow information is required
425 // to calculate chrome input to browser intervals in perfetto, and further
426 // calculate the chrome tasks blocking input. We need LatencyInfo slices to be
427 // associated with the correct input IPCs, hence record in the LongTaskTracker.
MaybeTraceInterestingTaskDetails()428 void TaskAnnotator::LongTaskTracker::MaybeTraceInterestingTaskDetails() {
429 if (is_interesting_task && ipc_interface_name_) {
430 // Record the equivalent of a delayed instant trace event, acting as the
431 // start of the flow between task queue time and task execution start time.
432 TRACE_EVENT_INSTANT("scheduler.long_tasks", "InterestingTask_QueueingTime",
433 perfetto::Track::ThreadScoped(task_annotator_),
434 pending_task_.queue_time,
435 perfetto::Flow::ProcessScoped(
436 task_annotator_->GetTaskTraceID(pending_task_)));
437
438 // Record the equivalent of a top-level event with enough IPC information
439 // to calculate the input to browser interval. This event will be the
440 // termination of the event above, aka the start of task execution.
441 TRACE_EVENT_BEGIN(
442 "scheduler.long_tasks", "InterestingTask_ProcessingTime",
443 perfetto::Track::ThreadScoped(task_annotator_), task_start_time_,
444 [&](perfetto::EventContext& ctx) {
445 perfetto::TerminatingFlow::ProcessScoped(
446 task_annotator_->GetTaskTraceID(pending_task_))(ctx);
447 auto* info = ctx.event()->set_chrome_mojo_event_info();
448 info->set_mojo_interface_tag(ipc_interface_name_);
449 });
450
451 TRACE_EVENT_END("scheduler.long_tasks",
452 perfetto::Track::ThreadScoped(task_annotator_),
453 task_end_time_);
454 }
455 }
456
457 } // namespace base
458