xref: /aosp_15_r20/external/cronet/base/debug/task_trace.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2019 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_DEBUG_TASK_TRACE_H_
6 #define BASE_DEBUG_TASK_TRACE_H_
7 
8 #include <iosfwd>
9 #include <optional>
10 #include <string>
11 
12 #include "base/base_export.h"
13 #include "base/containers/span.h"
14 #include "base/debug/stack_trace.h"
15 
16 namespace base {
17 namespace debug {
18 
19 // Provides a snapshot of which places in the code called
20 // base::TaskRunner::PostTask() that led to the TaskTrace() constructor call.
21 // Analogous to base::StackTrace, but for posted tasks rather than function
22 // calls.
23 //
24 // Example usage:
25 //   TaskTrace().Print();
26 //
27 // Example output:
28 //   Task trace:
29 //   #0 content::ServiceWorkerContextWrapper::DidCheckHasServiceWorker()
30 //   #1 content::ServiceWorkerStorage::FindForDocumentInDB()
31 //   #2 content::ServiceWorkerStorage::FindRegistrationForDocument()
32 //   #3 content::ServiceWorkerContextWrapper::CheckHasServiceWorker()
33 //   #4 content::ManifestIconDownloader::ScaleIcon()
34 //   Task trace buffer limit hit, update PendingTask::kTaskBacktraceLength to
35 //   increase.
36 class BASE_EXPORT TaskTrace {
37  public:
38   TaskTrace();
39 
40   // Whether there is any trace data.
41   bool empty() const;
42 
43   // Outputs to stderr via OutputToStream.
44   void Print() const;
45 
46   // Outputs trace to |os|, may be called when empty() is true.
47   void OutputToStream(std::ostream* os) const;
48 
49   // Resolves trace to symbols and returns as string.
50   std::string ToString() const;
51 
52   // Reads the list of addresses currently in the task trace into `addresses`,
53   // and returns the maximum length of addresses that could have been read,
54   // which may differ from `addresses.size()`.
55   size_t GetAddresses(span<const void*> addresses) const;
56 
57  private:
58   std::optional<StackTrace> stack_trace_;
59   bool trace_overflow_ = false;
60 };
61 
62 // Forwards to TaskTrace::OutputToStream.
63 BASE_EXPORT std::ostream& operator<<(std::ostream& os,
64                                      const TaskTrace& task_trace);
65 
66 }  // namespace debug
67 }  // namespace base
68 
69 #endif  // BASE_DEBUG_TASK_TRACE_H_
70