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_
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"
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()),
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);
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
{
63 // Module represents the module (DLL or exe) corresponding to a stack frame.
64 struct BASE_EXPORT Module
{
66 Module(const void* base_address
, const std::string
& id
,
67 const FilePath
& filename
);
70 // Points to the base address of the module.
71 const void* base_address
;
73 // An opaque binary string that uniquely identifies a particular program
74 // version with high probability. This is parsed from headers of the loaded
76 // For binaries generated by GNU tools:
77 // Contents of the .note.gnu.build-id field.
79 // GUID + AGE in the debug image headers of a module.
82 // The filename of the module.
86 // Frame represents an individual sampled stack frame with module information.
87 struct BASE_EXPORT Frame
{
88 // Identifies an unknown module.
89 static const size_t kUnknownModuleIndex
= static_cast<size_t>(-1);
91 Frame(const void* instruction_pointer
, size_t module_index
);
94 // The sampled instruction pointer within the function.
95 const void* instruction_pointer
;
97 // Index of the module in CallStackProfile::modules. We don't represent
98 // module state directly here to save space.
102 // Sample represents a set of stack frames.
103 using Sample
= std::vector
<Frame
>;
105 // CallStackProfile represents a set of samples.
106 struct BASE_EXPORT CallStackProfile
{
110 std::vector
<Module
> modules
;
111 std::vector
<Sample
> samples
;
113 // Duration of this profile.
114 TimeDelta profile_duration
;
116 // Time between samples.
117 TimeDelta sampling_period
;
120 using CallStackProfiles
= std::vector
<CallStackProfile
>;
122 // Represents parameters that configure the sampling.
123 struct BASE_EXPORT SamplingParams
{
126 // Time to delay before first samples are taken. Defaults to 0.
127 TimeDelta initial_delay
;
129 // Number of sampling bursts to perform. Defaults to 1.
132 // Interval between sampling bursts. This is the desired duration from the
133 // start of one burst to the start of the next burst. Defaults to 10s.
134 TimeDelta burst_interval
;
136 // Number of samples to record per burst. Defaults to 300.
137 int samples_per_burst
;
139 // Interval between samples during a sampling burst. This is the desired
140 // duration from the start of one sample to the start of the next
141 // sample. Defaults to 100ms.
142 TimeDelta sampling_interval
;
145 // The callback type used to collect completed profiles.
147 // IMPORTANT NOTE: the callback is invoked on a thread the profiler
148 // constructs, rather than on the thread used to construct the profiler and
149 // set the callback, and thus the callback must be callable on any thread. For
150 // threads with message loops that create StackSamplingProfilers, posting a
151 // task to the message loop with a copy of the profiles is the recommended
152 // thread-safe callback implementation.
153 using CompletedCallback
= Callback
<void(const CallStackProfiles
&)>;
155 // Creates a profiler that sends completed profiles to |callback|.
156 StackSamplingProfiler(PlatformThreadId thread_id
,
157 const SamplingParams
& params
,
158 const CompletedCallback
& callback
);
159 // Stops any profiling currently taking place before destroying the profiler.
160 ~StackSamplingProfiler();
162 // The fire-and-forget interface: starts a profiler and allows it to complete
163 // without the caller needing to manage the profiler lifetime. May be invoked
164 // from any thread, but requires that the calling thread has a message loop.
165 static void StartAndRunAsync(PlatformThreadId thread_id
,
166 const SamplingParams
& params
,
167 const CompletedCallback
& callback
);
169 // Initializes the profiler and starts sampling.
172 // Stops the profiler and any ongoing sampling. Calling this function is
173 // optional; if not invoked profiling terminates when all the profiling bursts
174 // specified in the SamplingParams are completed or the profiler is destroyed,
175 // whichever occurs first.
179 // SamplingThread is a separate thread used to suspend and sample stacks from
180 // the target thread.
181 class SamplingThread
: public PlatformThread::Delegate
{
183 // Samples stacks using |native_sampler|. When complete, invokes
184 // |completed_callback| with the collected call stack profiles.
185 // |completed_callback| must be callable on any thread.
186 SamplingThread(scoped_ptr
<NativeStackSampler
> native_sampler
,
187 const SamplingParams
& params
,
188 const CompletedCallback
& completed_callback
);
189 ~SamplingThread() override
;
191 // PlatformThread::Delegate:
192 void ThreadMain() override
;
197 // Collects |profile| from a single burst. If the profiler was stopped
198 // during collection, sets |was_stopped| and provides the set of samples
199 // collected up to that point.
200 void CollectProfile(CallStackProfile
* profile
, TimeDelta
* elapsed_time
,
203 // Collects call stack profiles from all bursts, or until the sampling is
204 // stopped. If stopped before complete, the last profile in
205 // |call_stack_profiles| may contain a partial burst.
206 void CollectProfiles(CallStackProfiles
* profiles
);
208 scoped_ptr
<NativeStackSampler
> native_sampler_
;
209 const SamplingParams params_
;
211 // If Stop() is called, it signals this event to force the sampling to
212 // terminate before all the samples specified in |params_| are collected.
213 WaitableEvent stop_event_
;
215 const CompletedCallback completed_callback_
;
217 DISALLOW_COPY_AND_ASSIGN(SamplingThread
);
220 // The thread whose stack will be sampled.
221 PlatformThreadId thread_id_
;
223 const SamplingParams params_
;
225 scoped_ptr
<SamplingThread
> sampling_thread_
;
226 PlatformThreadHandle sampling_thread_handle_
;
228 const CompletedCallback completed_callback_
;
230 DISALLOW_COPY_AND_ASSIGN(StackSamplingProfiler
);
233 // The metrics provider code wants to put Samples in a map and compare them,
234 // which requires us to define a few operators.
235 BASE_EXPORT
bool operator==(const StackSamplingProfiler::Frame
& a
,
236 const StackSamplingProfiler::Frame
& b
);
237 BASE_EXPORT
bool operator<(const StackSamplingProfiler::Frame
& a
,
238 const StackSamplingProfiler::Frame
& b
);
242 #endif // BASE_PROFILER_STACK_SAMPLING_PROFILER_H_