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 // // To process the call stack profiles within Chrome rather than via UMA,
38 // // set a custom completed callback:
39 // base::StackStackSamplingProfiler::CompletedCallback
40 // thread_safe_callback = ...;
41 // profiler.SetCustomCompletedCallback(thread_safe_callback);
44 // // ... work being done on the target thread here ...
45 // profiler.Stop(); // optional, stops collection before complete per params
47 // The default SamplingParams causes stacks to be recorded in a single burst at
48 // a 10Hz interval for a total of 30 seconds. All of these parameters may be
49 // altered as desired.
51 // When all call stack profiles are complete or the profiler is stopped, if the
52 // custom completed callback was set it is called from the profiler thread with
53 // the completed profiles. A profile is considered complete if all requested
54 // samples were recorded for the profile (i.e. it was not stopped
55 // prematurely). If no callback was set, the completed profiles are stored
56 // internally and retrieved for UMA through GetPendingProfiles().
57 // GetPendingProfiles() should never be called by other code; to retrieve
58 // profiles for in-process processing, set a completed callback.
60 // The results of the profiling are passed to the completed callback and consist
61 // of a vector of CallStackProfiles. Each CallStackProfile corresponds to a
62 // burst as specified in SamplingParams and contains a set of Samples and
63 // Modules. One Sample corresponds to a single recorded stack, and the Modules
64 // record those modules associated with the recorded stack frames.
65 class BASE_EXPORT StackSamplingProfiler
{
67 // Module represents the module (DLL or exe) corresponding to a stack frame.
68 struct BASE_EXPORT Module
{
70 Module(const void* base_address
, const std::string
& id
,
71 const FilePath
& filename
);
74 // Points to the base address of the module.
75 const void* base_address
;
77 // An opaque binary string that uniquely identifies a particular program
78 // version with high probability. This is parsed from headers of the loaded
80 // For binaries generated by GNU tools:
81 // Contents of the .note.gnu.build-id field.
83 // GUID + AGE in the debug image headers of a module.
86 // The filename of the module.
90 // Frame represents an individual sampled stack frame with module information.
91 struct BASE_EXPORT Frame
{
92 // Identifies an unknown module.
93 static const size_t kUnknownModuleIndex
= static_cast<size_t>(-1);
95 Frame(const void* instruction_pointer
, size_t module_index
);
98 // The sampled instruction pointer within the function.
99 const void* instruction_pointer
;
101 // Index of the module in CallStackProfile::modules. We don't represent
102 // module state directly here to save space.
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
{
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
;
123 // True if sample ordering is important and should be preserved if and when
124 // this profile is compressed and processed.
125 bool preserve_sample_ordering
;
128 using CallStackProfiles
= std::vector
<CallStackProfile
>;
130 // Represents parameters that configure the sampling.
131 struct BASE_EXPORT SamplingParams
{
134 // Time to delay before first samples are taken. Defaults to 0.
135 TimeDelta initial_delay
;
137 // Number of sampling bursts to perform. Defaults to 1.
140 // Interval between sampling bursts. This is the desired duration from the
141 // start of one burst to the start of the next burst. Defaults to 10s.
142 TimeDelta burst_interval
;
144 // Number of samples to record per burst. Defaults to 300.
145 int samples_per_burst
;
147 // Interval between samples during a sampling burst. This is the desired
148 // duration from the start of one sample to the start of the next
149 // sample. Defaults to 100ms.
150 TimeDelta sampling_interval
;
152 // True if sample ordering is important and should be preserved if and when
153 // this profile is compressed and processed. Defaults to false.
154 bool preserve_sample_ordering
;
157 // The callback type used to collect completed profiles.
159 // IMPORTANT NOTE: the callback is invoked on a thread the profiler
160 // constructs, rather than on the thread used to construct the profiler and
161 // set the callback, and thus the callback must be callable on any thread. For
162 // threads with message loops that create StackSamplingProfilers, posting a
163 // task to the message loop with a copy of the profiles is the recommended
164 // thread-safe callback implementation.
165 using CompletedCallback
= Callback
<void(const CallStackProfiles
&)>;
167 StackSamplingProfiler(PlatformThreadId thread_id
,
168 const SamplingParams
& params
);
169 ~StackSamplingProfiler();
171 // Initializes the profiler and starts sampling.
174 // Stops the profiler and any ongoing sampling. Calling this function is
175 // optional; if not invoked profiling terminates when all the profiling bursts
176 // specified in the SamplingParams are completed.
179 // Moves all pending call stack profiles from internal storage to
180 // |profiles|. This function is thread safe.
182 // ***This is intended for use only by UMA.*** Callers who want to process the
183 // collected profiles should use SetCustomCompletedCallback.
184 static void GetPendingProfiles(CallStackProfiles
* call_stack_profiles
);
186 // By default, collected call stack profiles are stored internally and can be
187 // retrieved by GetPendingProfiles. If a callback is provided via this
188 // function, however, it is called with the collected profiles instead.
189 void set_custom_completed_callback(CompletedCallback callback
) {
190 custom_completed_callback_
= callback
;
194 // SamplingThread is a separate thread used to suspend and sample stacks from
195 // the target thread.
196 class SamplingThread
: public PlatformThread::Delegate
{
198 // Samples stacks using |native_sampler|. When complete, invokes
199 // |completed_callback| with the collected call stack profiles.
200 // |completed_callback| must be callable on any thread.
201 SamplingThread(scoped_ptr
<NativeStackSampler
> native_sampler
,
202 const SamplingParams
& params
,
203 CompletedCallback completed_callback
);
204 ~SamplingThread() override
;
206 // PlatformThread::Delegate:
207 void ThreadMain() override
;
212 // Collects a call stack profile from a single burst. Returns true if the
213 // profile was collected, or false if collection was stopped before it
215 bool CollectProfile(CallStackProfile
* profile
, TimeDelta
* elapsed_time
);
217 // Collects call stack profiles from all bursts, or until the sampling is
218 // stopped. If stopped before complete, |call_stack_profiles| will contain
220 void CollectProfiles(CallStackProfiles
* profiles
);
222 scoped_ptr
<NativeStackSampler
> native_sampler_
;
223 const SamplingParams params_
;
225 // If Stop() is called, it signals this event to force the sampling to
226 // terminate before all the samples specified in |params_| are collected.
227 WaitableEvent stop_event_
;
229 CompletedCallback completed_callback_
;
231 DISALLOW_COPY_AND_ASSIGN(SamplingThread
);
234 // The thread whose stack will be sampled.
235 PlatformThreadId thread_id_
;
237 const SamplingParams params_
;
239 scoped_ptr
<SamplingThread
> sampling_thread_
;
241 CompletedCallback custom_completed_callback_
;
243 DISALLOW_COPY_AND_ASSIGN(StackSamplingProfiler
);
246 // The metrics provider code wants to put Samples in a map and compare them,
247 // which requires us to define a few operators.
248 BASE_EXPORT
bool operator==(const StackSamplingProfiler::Frame
& a
,
249 const StackSamplingProfiler::Frame
& b
);
250 BASE_EXPORT
bool operator<(const StackSamplingProfiler::Frame
& a
,
251 const StackSamplingProfiler::Frame
& b
);
255 #endif // BASE_PROFILER_STACK_SAMPLING_PROFILER_H_