Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / base / profiler / stack_sampling_profiler.h
blob9aa9c31d67afd31a12113f5caeeb1b53e3ae771e
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.
5 #ifndef BASE_PROFILER_STACK_SAMPLING_PROFILER_H_
6 #define BASE_PROFILER_STACK_SAMPLING_PROFILER_H_
8 #include <string>
9 #include <vector>
11 #include "base/base_export.h"
12 #include "base/callback.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/strings/string16.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/threading/platform_thread.h"
18 #include "base/time/time.h"
20 namespace base {
22 class NativeStackSampler;
24 // StackSamplingProfiler periodically stops a thread to sample its stack, for
25 // the purpose of collecting information about which code paths are
26 // executing. This information is used in aggregate by UMA to identify hot
27 // and/or janky code paths.
29 // Sample StackSamplingProfiler usage:
31 // // Create and customize params as desired.
32 // base::StackStackSamplingProfiler::SamplingParams params;
33 // // Any thread's ID may be passed as the target.
34 // base::StackSamplingProfiler profiler(base::PlatformThread::CurrentId()),
35 // params);
37 // // Or, to process the profiles within Chrome rather than via UMA, use a
38 // // custom completed callback:
39 // base::StackStackSamplingProfiler::CompletedCallback
40 // thread_safe_callback = ...;
41 // base::StackSamplingProfiler profiler(base::PlatformThread::CurrentId()),
42 // params, thread_safe_callback);
44 // profiler.Start();
45 // // ... work being done on the target thread here ...
46 // profiler.Stop(); // optional, stops collection before complete per params
48 // The default SamplingParams causes stacks to be recorded in a single burst at
49 // a 10Hz interval for a total of 30 seconds. All of these parameters may be
50 // altered as desired.
52 // When all call stack profiles are complete, or the profiler is stopped, the
53 // completed callback is called from a thread created by the profiler with the
54 // collected profiles.
56 // The results of the profiling are passed to the completed callback and consist
57 // of a vector of CallStackProfiles. Each CallStackProfile corresponds to a
58 // burst as specified in SamplingParams and contains a set of Samples and
59 // Modules. One Sample corresponds to a single recorded stack, and the Modules
60 // record those modules associated with the recorded stack frames.
61 class BASE_EXPORT StackSamplingProfiler {
62 public:
63 // Module represents the module (DLL or exe) corresponding to a stack frame.
64 struct BASE_EXPORT Module {
65 Module();
66 Module(uintptr_t base_address,
67 const std::string& id,
68 const FilePath& filename);
69 ~Module();
71 // Points to the base address of the module.
72 uintptr_t base_address;
74 // An opaque binary string that uniquely identifies a particular program
75 // version with high probability. This is parsed from headers of the loaded
76 // module.
77 // For binaries generated by GNU tools:
78 // Contents of the .note.gnu.build-id field.
79 // On Windows:
80 // GUID + AGE in the debug image headers of a module.
81 std::string id;
83 // The filename of the module.
84 FilePath filename;
87 // Frame represents an individual sampled stack frame with module information.
88 struct BASE_EXPORT Frame {
89 // Identifies an unknown module.
90 static const size_t kUnknownModuleIndex = static_cast<size_t>(-1);
92 Frame(uintptr_t instruction_pointer, size_t module_index);
93 ~Frame();
95 // Default constructor to satisfy IPC macros. Do not use explicitly.
96 Frame();
98 // The sampled instruction pointer within the function.
99 uintptr_t instruction_pointer;
101 // Index of the module in CallStackProfile::modules. We don't represent
102 // module state directly here to save space.
103 size_t module_index;
106 // Sample represents a set of stack frames.
107 using Sample = std::vector<Frame>;
109 // CallStackProfile represents a set of samples.
110 struct BASE_EXPORT CallStackProfile {
111 CallStackProfile();
112 ~CallStackProfile();
114 std::vector<Module> modules;
115 std::vector<Sample> samples;
117 // Duration of this profile.
118 TimeDelta profile_duration;
120 // Time between samples.
121 TimeDelta sampling_period;
124 using CallStackProfiles = std::vector<CallStackProfile>;
126 // Represents parameters that configure the sampling.
127 struct BASE_EXPORT SamplingParams {
128 SamplingParams();
130 // Time to delay before first samples are taken. Defaults to 0.
131 TimeDelta initial_delay;
133 // Number of sampling bursts to perform. Defaults to 1.
134 int bursts;
136 // Interval between sampling bursts. This is the desired duration from the
137 // start of one burst to the start of the next burst. Defaults to 10s.
138 TimeDelta burst_interval;
140 // Number of samples to record per burst. Defaults to 300.
141 int samples_per_burst;
143 // Interval between samples during a sampling burst. This is the desired
144 // duration from the start of one sample to the start of the next
145 // sample. Defaults to 100ms.
146 TimeDelta sampling_interval;
149 // The callback type used to collect completed profiles.
151 // IMPORTANT NOTE: the callback is invoked on a thread the profiler
152 // constructs, rather than on the thread used to construct the profiler and
153 // set the callback, and thus the callback must be callable on any thread. For
154 // threads with message loops that create StackSamplingProfilers, posting a
155 // task to the message loop with a copy of the profiles is the recommended
156 // thread-safe callback implementation.
157 using CompletedCallback = Callback<void(const CallStackProfiles&)>;
159 // Creates a profiler that sends completed profiles to |callback|.
160 StackSamplingProfiler(PlatformThreadId thread_id,
161 const SamplingParams& params,
162 const CompletedCallback& callback);
163 // Stops any profiling currently taking place before destroying the profiler.
164 ~StackSamplingProfiler();
166 // The fire-and-forget interface: starts a profiler and allows it to complete
167 // without the caller needing to manage the profiler lifetime. May be invoked
168 // from any thread, but requires that the calling thread has a message loop.
169 static void StartAndRunAsync(PlatformThreadId thread_id,
170 const SamplingParams& params,
171 const CompletedCallback& callback);
173 // Initializes the profiler and starts sampling.
174 void Start();
176 // Stops the profiler and any ongoing sampling. Calling this function is
177 // optional; if not invoked profiling terminates when all the profiling bursts
178 // specified in the SamplingParams are completed or the profiler is destroyed,
179 // whichever occurs first.
180 void Stop();
182 private:
183 // SamplingThread is a separate thread used to suspend and sample stacks from
184 // the target thread.
185 class SamplingThread : public PlatformThread::Delegate {
186 public:
187 // Samples stacks using |native_sampler|. When complete, invokes
188 // |completed_callback| with the collected call stack profiles.
189 // |completed_callback| must be callable on any thread.
190 SamplingThread(scoped_ptr<NativeStackSampler> native_sampler,
191 const SamplingParams& params,
192 const CompletedCallback& completed_callback);
193 ~SamplingThread() override;
195 // PlatformThread::Delegate:
196 void ThreadMain() override;
198 void Stop();
200 private:
201 // Collects |profile| from a single burst. If the profiler was stopped
202 // during collection, sets |was_stopped| and provides the set of samples
203 // collected up to that point.
204 void CollectProfile(CallStackProfile* profile, TimeDelta* elapsed_time,
205 bool* was_stopped);
207 // Collects call stack profiles from all bursts, or until the sampling is
208 // stopped. If stopped before complete, the last profile in
209 // |call_stack_profiles| may contain a partial burst.
210 void CollectProfiles(CallStackProfiles* profiles);
212 scoped_ptr<NativeStackSampler> native_sampler_;
213 const SamplingParams params_;
215 // If Stop() is called, it signals this event to force the sampling to
216 // terminate before all the samples specified in |params_| are collected.
217 WaitableEvent stop_event_;
219 const CompletedCallback completed_callback_;
221 DISALLOW_COPY_AND_ASSIGN(SamplingThread);
224 // The thread whose stack will be sampled.
225 PlatformThreadId thread_id_;
227 const SamplingParams params_;
229 scoped_ptr<SamplingThread> sampling_thread_;
230 PlatformThreadHandle sampling_thread_handle_;
232 const CompletedCallback completed_callback_;
234 DISALLOW_COPY_AND_ASSIGN(StackSamplingProfiler);
237 // The metrics provider code wants to put Samples in a map and compare them,
238 // which requires us to define a few operators.
239 BASE_EXPORT bool operator==(const StackSamplingProfiler::Frame& a,
240 const StackSamplingProfiler::Frame& b);
241 BASE_EXPORT bool operator<(const StackSamplingProfiler::Frame& a,
242 const StackSamplingProfiler::Frame& b);
244 } // namespace base
246 #endif // BASE_PROFILER_STACK_SAMPLING_PROFILER_H_