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.
8 #include "base/compiler_specific.h"
9 #include "base/path_service.h"
10 #include "base/profiler/stack_sampling_profiler.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "base/threading/platform_thread.h"
13 #include "base/time/time.h"
14 #include "testing/gtest/include/gtest/gtest.h"
18 using Frame
= StackSamplingProfiler::Frame
;
19 using Module
= StackSamplingProfiler::Module
;
20 using Sample
= StackSamplingProfiler::Sample
;
21 using Profile
= StackSamplingProfiler::Profile
;
24 // A thread to target for profiling, whose stack is guaranteed to contain
25 // SignalAndWaitUntilSignaled() when coordinated with the main thread.
26 class TargetThread
: public PlatformThread::Delegate
{
30 // Implementation of PlatformThread::Delegate:
31 void ThreadMain() override
;
33 // Wait for the thread to have started and be executing in
34 // SignalAndWaitUntilSignaled().
35 void WaitForThreadStart();
36 // Allow the thread to return from SignalAndWaitUntilSignaled() and finish
38 void SignalThreadToFinish();
40 // This function is guaranteed to be executing between calls to
41 // WaitForThreadStart() and SignalThreadToFinish().
42 static void SignalAndWaitUntilSignaled(WaitableEvent
* thread_started_event
,
43 WaitableEvent
* finish_event
);
45 PlatformThreadId
id() const { return id_
; }
48 WaitableEvent thread_started_event_
;
49 WaitableEvent finish_event_
;
52 DISALLOW_COPY_AND_ASSIGN(TargetThread
);
55 TargetThread::TargetThread()
56 : thread_started_event_(false, false), finish_event_(false, false),
59 void TargetThread::ThreadMain() {
60 id_
= PlatformThread::CurrentId();
61 SignalAndWaitUntilSignaled(&thread_started_event_
, &finish_event_
);
64 void TargetThread::WaitForThreadStart() {
65 thread_started_event_
.Wait();
68 void TargetThread::SignalThreadToFinish() {
69 finish_event_
.Signal();
73 // Disable inlining for this function so that it gets its own stack frame.
74 NOINLINE
void TargetThread::SignalAndWaitUntilSignaled(
75 WaitableEvent
* thread_started_event
,
76 WaitableEvent
* finish_event
) {
77 thread_started_event
->Signal();
80 x
= 0; // Prevent tail call to WaitableEvent::Wait().
81 ALLOW_UNUSED_LOCAL(x
);
84 // Called on the profiler thread when complete. Collects profiles produced by
85 // the profiler, and signals an event to allow the main thread to know that that
86 // the profiler is done.
87 void SaveProfilesAndSignalEvent(std::vector
<Profile
>* profiles
,
89 const std::vector
<Profile
>& pending_profiles
) {
90 *profiles
= pending_profiles
;
94 // Captures profiles as specified by |params| on the TargetThread, and returns
95 // them in |profiles|. Waits up to |profiler_wait_time| for the profiler to
97 void CaptureProfiles(const StackSamplingProfiler::SamplingParams
& params
,
98 std::vector
<Profile
>* profiles
,
99 TimeDelta profiler_wait_time
) {
100 TargetThread target_thread
;
101 PlatformThreadHandle target_thread_handle
;
102 EXPECT_TRUE(PlatformThread::Create(0, &target_thread
, &target_thread_handle
));
104 target_thread
.WaitForThreadStart();
106 WaitableEvent
sampling_thread_completed(true, false);
108 StackSamplingProfiler
profiler(target_thread
.id(), params
);
109 profiler
.SetCustomCompletedCallback(
110 Bind(&SaveProfilesAndSignalEvent
, Unretained(profiles
),
111 Unretained(&sampling_thread_completed
)));
113 sampling_thread_completed
.TimedWait(profiler_wait_time
);
115 sampling_thread_completed
.Wait();
117 target_thread
.SignalThreadToFinish();
119 PlatformThread::Join(target_thread_handle
);
122 // If this executable was linked with /INCREMENTAL (the default for non-official
123 // debug and release builds on Windows), function addresses do not correspond to
124 // function code itself, but instead to instructions in the Incremental Link
125 // Table that jump to the functions. Check for a jump instruction and if present
126 // do a little decompilation to find the function's actual starting address.
127 const void* MaybeFixupFunctionAddressForILT(const void* function_address
) {
129 const unsigned char* opcode
=
130 reinterpret_cast<const unsigned char*>(function_address
);
131 if (*opcode
== 0xe9) {
132 // This is a relative jump instruction. Assume we're in the ILT and compute
133 // the function start address from the instruction offset.
134 const unsigned char* offset
= opcode
+ 1;
135 const unsigned char* next_instruction
= opcode
+ 5;
136 return next_instruction
+
137 static_cast<int64
>(*reinterpret_cast<const int32
*>(offset
));
140 return function_address
;
143 // Searches through the frames in |sample|, returning an iterator to the first
144 // frame that has an instruction pointer between |function_address| and
145 // |function_address| + |size|. Returns sample.end() if no such frames are
147 Sample::const_iterator
FindFirstFrameWithinFunction(
148 const Sample
& sample
,
149 const void* function_address
,
151 function_address
= MaybeFixupFunctionAddressForILT(function_address
);
152 for (auto it
= sample
.begin(); it
!= sample
.end(); ++it
) {
153 if ((reinterpret_cast<const unsigned char*>(it
->instruction_pointer
) >=
154 reinterpret_cast<const unsigned char*>(function_address
)) &&
155 (reinterpret_cast<const unsigned char*>(it
->instruction_pointer
) <
156 (reinterpret_cast<const unsigned char*>(function_address
) +
163 // Formats a sample into a string that can be output for test diagnostics.
164 std::string
FormatSampleForDiagnosticOutput(
165 const Sample
& sample
,
166 const std::vector
<Module
>& modules
) {
167 std::ostringstream stream
;
168 for (const Frame
& frame
: sample
) {
169 stream
<< frame
.instruction_pointer
<< " "
170 << modules
[frame
.module_index
].filename
.value() << std::endl
;
175 // Returns a duration that is longer than the test timeout. We would use
176 // TimeDelta::Max() but https://crbug.com/465948.
177 TimeDelta
AVeryLongTimeDelta() { return TimeDelta::FromDays(1); }
181 // The tests below are enabled for Win x64 only, pending implementation of the
182 // tested functionality on other platforms/architectures.
184 // Checks that the basic expected information is present in a sampled profile.
186 #define MAYBE_Basic Basic
188 #define MAYBE_Basic DISABLED_Basic
190 TEST(StackSamplingProfilerTest
, MAYBE_Basic
) {
191 StackSamplingProfiler::SamplingParams params
;
192 params
.initial_delay
= params
.burst_interval
= params
.sampling_interval
=
193 TimeDelta::FromMilliseconds(0);
195 params
.samples_per_burst
= 1;
197 std::vector
<Profile
> profiles
;
198 CaptureProfiles(params
, &profiles
, AVeryLongTimeDelta());
200 // Check that the profile and samples sizes are correct, and the module
201 // indices are in range.
203 ASSERT_EQ(1u, profiles
.size());
204 const Profile
& profile
= profiles
[0];
205 ASSERT_EQ(1u, profile
.samples
.size());
206 EXPECT_EQ(params
.sampling_interval
, profile
.sampling_period
);
207 const Sample
& sample
= profile
.samples
[0];
208 for (const auto& frame
: sample
) {
209 ASSERT_GE(frame
.module_index
, 0);
210 ASSERT_LT(frame
.module_index
, static_cast<int>(profile
.modules
.size()));
213 // Check that the stack contains a frame for
214 // TargetThread::SignalAndWaitUntilSignaled() and that the frame has this
215 // executable's module.
217 // Since we don't have a good way to know the function size, use 100 bytes as
218 // a reasonable window to locate the instruction pointer.
219 Sample::const_iterator loc
= FindFirstFrameWithinFunction(
221 reinterpret_cast<const void*>(&TargetThread::SignalAndWaitUntilSignaled
),
223 ASSERT_TRUE(loc
!= sample
.end())
225 << MaybeFixupFunctionAddressForILT(
226 reinterpret_cast<const void*>(
227 &TargetThread::SignalAndWaitUntilSignaled
))
228 << " was not found in stack:" << std::endl
229 << FormatSampleForDiagnosticOutput(sample
, profile
.modules
);
231 FilePath executable_path
;
232 bool got_executable_path
= PathService::Get(FILE_EXE
, &executable_path
);
233 EXPECT_TRUE(got_executable_path
);
234 EXPECT_EQ(executable_path
, profile
.modules
[loc
->module_index
].filename
);
237 // Checks that the expected number of profiles and samples are present in the
238 // profiles produced.
240 #define MAYBE_MultipleProfilesAndSamples MultipleProfilesAndSamples
242 #define MAYBE_MultipleProfilesAndSamples DISABLED_MultipleProfilesAndSamples
244 TEST(StackSamplingProfilerTest
, MAYBE_MultipleProfilesAndSamples
) {
245 StackSamplingProfiler::SamplingParams params
;
246 params
.initial_delay
= params
.burst_interval
= params
.sampling_interval
=
247 TimeDelta::FromMilliseconds(0);
249 params
.samples_per_burst
= 3;
251 std::vector
<Profile
> profiles
;
252 CaptureProfiles(params
, &profiles
, AVeryLongTimeDelta());
254 ASSERT_EQ(2u, profiles
.size());
255 EXPECT_EQ(3u, profiles
[0].samples
.size());
256 EXPECT_EQ(3u, profiles
[1].samples
.size());
259 // Checks that no profiles are captured if the profiling is stopped during the
262 #define MAYBE_StopDuringInitialDelay StopDuringInitialDelay
264 #define MAYBE_StopDuringInitialDelay DISABLED_StopDuringInitialDelay
266 TEST(StackSamplingProfilerTest
, MAYBE_StopDuringInitialDelay
) {
267 StackSamplingProfiler::SamplingParams params
;
268 params
.burst_interval
= params
.sampling_interval
=
269 TimeDelta::FromMilliseconds(0);
270 params
.initial_delay
= TimeDelta::FromSeconds(60);
271 params
.bursts
= params
.samples_per_burst
= 1;
273 std::vector
<Profile
> profiles
;
274 CaptureProfiles(params
, &profiles
, TimeDelta::FromMilliseconds(0));
276 EXPECT_TRUE(profiles
.empty());
279 // Checks that the single completed profile is captured if the profiling is
280 // stopped between bursts.
282 #define MAYBE_StopDuringInterBurstInterval StopDuringInterBurstInterval
284 #define MAYBE_StopDuringInterBurstInterval DISABLED_StopDuringInterBurstInterval
286 TEST(StackSamplingProfilerTest
, MAYBE_StopDuringInterBurstInterval
) {
287 StackSamplingProfiler::SamplingParams params
;
288 params
.initial_delay
= params
.sampling_interval
=
289 TimeDelta::FromMilliseconds(0);
290 params
.burst_interval
= TimeDelta::FromSeconds(60);
292 params
.samples_per_burst
= 1;
294 std::vector
<Profile
> profiles
;
295 CaptureProfiles(params
, &profiles
, TimeDelta::FromMilliseconds(50));
297 ASSERT_EQ(1u, profiles
.size());
298 EXPECT_EQ(1u, profiles
[0].samples
.size());
301 // Checks that only completed profiles are captured.
303 #define MAYBE_StopDuringInterSampleInterval StopDuringInterSampleInterval
305 #define MAYBE_StopDuringInterSampleInterval \
306 DISABLED_StopDuringInterSampleInterval
308 TEST(StackSamplingProfilerTest
, MAYBE_StopDuringInterSampleInterval
) {
309 StackSamplingProfiler::SamplingParams params
;
310 params
.initial_delay
= params
.burst_interval
= TimeDelta::FromMilliseconds(0);
311 params
.sampling_interval
= TimeDelta::FromSeconds(60);
313 params
.samples_per_burst
= 2;
315 std::vector
<Profile
> profiles
;
316 CaptureProfiles(params
, &profiles
, TimeDelta::FromMilliseconds(50));
318 EXPECT_TRUE(profiles
.empty());
321 } // namespace tracked_objects