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