summaryrefslogtreecommitdiff
path: root/chromium/base/profiler/stack_sampling_profiler.cc
blob: fa98bed116bb9b759ab610e5e0cd7ec77abc44a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/profiler/stack_sampling_profiler.h"

#include <algorithm>
#include <utility>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/profiler/native_stack_sampler.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/elapsed_timer.h"

namespace base {

namespace {

// Used to ensure only one profiler is running at a time.
LazyInstance<Lock>::Leaky concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER;

// AsyncRunner ----------------------------------------------------------------

// Helper class to allow a profiler to be run completely asynchronously from the
// initiator, without being concerned with the profiler's lifetime.
class AsyncRunner {
 public:
  // Sets up a profiler and arranges for it to be deleted on its completed
  // callback.
  static void Run(PlatformThreadId thread_id,
                  const StackSamplingProfiler::SamplingParams& params,
                  const StackSamplingProfiler::CompletedCallback& callback);

 private:
  AsyncRunner();

  // Runs the callback and deletes the AsyncRunner instance. |profiles| is not
  // const& because it must be passed with std::move.
  static void RunCallbackAndDeleteInstance(
      std::unique_ptr<AsyncRunner> object_to_be_deleted,
      const StackSamplingProfiler::CompletedCallback& callback,
      scoped_refptr<SingleThreadTaskRunner> task_runner,
      StackSamplingProfiler::CallStackProfiles profiles);

  std::unique_ptr<StackSamplingProfiler> profiler_;

  DISALLOW_COPY_AND_ASSIGN(AsyncRunner);
};

// static
void AsyncRunner::Run(
    PlatformThreadId thread_id,
    const StackSamplingProfiler::SamplingParams& params,
    const StackSamplingProfiler::CompletedCallback &callback) {
  std::unique_ptr<AsyncRunner> runner(new AsyncRunner);
  AsyncRunner* temp_ptr = runner.get();
  temp_ptr->profiler_.reset(
      new StackSamplingProfiler(thread_id, params,
                                Bind(&AsyncRunner::RunCallbackAndDeleteInstance,
                                     Passed(&runner), callback,
                                     ThreadTaskRunnerHandle::Get())));
  // The callback won't be called until after Start(), so temp_ptr will still
  // be valid here.
  temp_ptr->profiler_->Start();
}

AsyncRunner::AsyncRunner() {}

void AsyncRunner::RunCallbackAndDeleteInstance(
    std::unique_ptr<AsyncRunner> object_to_be_deleted,
    const StackSamplingProfiler::CompletedCallback& callback,
    scoped_refptr<SingleThreadTaskRunner> task_runner,
    StackSamplingProfiler::CallStackProfiles profiles) {
  callback.Run(std::move(profiles));
  // Delete the instance on the original calling thread.
  task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release());
}

void ChangeAtomicFlags(subtle::Atomic32* flags,
                       subtle::Atomic32 set,
                       subtle::Atomic32 clear) {
  DCHECK(set != 0 || clear != 0);
  DCHECK_EQ(0, set & clear);

  subtle::Atomic32 bits = subtle::NoBarrier_Load(flags);
  while (true) {
    subtle::Atomic32 existing =
        subtle::NoBarrier_CompareAndSwap(flags, bits, (bits | set) & ~clear);
    if (existing == bits)
      break;
    bits = existing;
  }
}

}  // namespace

// StackSamplingProfiler::Module ----------------------------------------------

StackSamplingProfiler::Module::Module() : base_address(0u) {}
StackSamplingProfiler::Module::Module(uintptr_t base_address,
                                      const std::string& id,
                                      const FilePath& filename)
    : base_address(base_address), id(id), filename(filename) {}

StackSamplingProfiler::Module::~Module() {}

// StackSamplingProfiler::Frame -----------------------------------------------

StackSamplingProfiler::Frame::Frame(uintptr_t instruction_pointer,
                                    size_t module_index)
    : instruction_pointer(instruction_pointer), module_index(module_index) {}

StackSamplingProfiler::Frame::~Frame() {}

StackSamplingProfiler::Frame::Frame()
    : instruction_pointer(0), module_index(kUnknownModuleIndex) {
}

// StackSamplingProfiler::Sample ----------------------------------------------

StackSamplingProfiler::Sample::Sample() {}

StackSamplingProfiler::Sample::Sample(const Sample& sample) = default;

StackSamplingProfiler::Sample::~Sample() {}

StackSamplingProfiler::Sample::Sample(const Frame& frame) {
  frames.push_back(std::move(frame));
}

StackSamplingProfiler::Sample::Sample(const std::vector<Frame>& frames)
    : frames(frames) {}

// StackSamplingProfiler::CallStackProfile ------------------------------------

StackSamplingProfiler::CallStackProfile::CallStackProfile() {}

StackSamplingProfiler::CallStackProfile::CallStackProfile(
    CallStackProfile&& other) = default;

StackSamplingProfiler::CallStackProfile::~CallStackProfile() {}

StackSamplingProfiler::CallStackProfile&
StackSamplingProfiler::CallStackProfile::operator=(CallStackProfile&& other) =
    default;

StackSamplingProfiler::CallStackProfile
StackSamplingProfiler::CallStackProfile::CopyForTesting() const {
  return CallStackProfile(*this);
}

StackSamplingProfiler::CallStackProfile::CallStackProfile(
    const CallStackProfile& other) = default;

// StackSamplingProfiler::SamplingThread --------------------------------------

StackSamplingProfiler::SamplingThread::SamplingThread(
    std::unique_ptr<NativeStackSampler> native_sampler,
    const SamplingParams& params,
    const CompletedCallback& completed_callback)
    : native_sampler_(std::move(native_sampler)),
      params_(params),
      stop_event_(WaitableEvent::ResetPolicy::AUTOMATIC,
                  WaitableEvent::InitialState::NOT_SIGNALED),
      completed_callback_(completed_callback) {}

StackSamplingProfiler::SamplingThread::~SamplingThread() {}

void StackSamplingProfiler::SamplingThread::ThreadMain() {
  PlatformThread::SetName("Chrome_SamplingProfilerThread");

  // For now, just ignore any requests to profile while another profiler is
  // working.
  if (!concurrent_profiling_lock.Get().Try())
    return;

  CallStackProfiles profiles;
  CollectProfiles(&profiles);
  concurrent_profiling_lock.Get().Release();
  completed_callback_.Run(std::move(profiles));
}

// Depending on how long the sampling takes and the length of the sampling
// interval, a burst of samples could take arbitrarily longer than
// samples_per_burst * sampling_interval. In this case, we (somewhat
// arbitrarily) honor the number of samples requested rather than strictly
// adhering to the sampling intervals. Once we have established users for the
// StackSamplingProfiler and the collected data to judge, we may go the other
// way or make this behavior configurable.
void StackSamplingProfiler::SamplingThread::CollectProfile(
    CallStackProfile* profile,
    TimeDelta* elapsed_time,
    bool* was_stopped) {
  ElapsedTimer profile_timer;
  native_sampler_->ProfileRecordingStarting(&profile->modules);
  profile->sampling_period = params_.sampling_interval;
  *was_stopped = false;
  TimeDelta previous_elapsed_sample_time;
  for (int i = 0; i < params_.samples_per_burst; ++i) {
    if (i != 0) {
      // Always wait, even if for 0 seconds, so we can observe a signal on
      // stop_event_.
      if (stop_event_.TimedWait(
              std::max(params_.sampling_interval - previous_elapsed_sample_time,
                       TimeDelta()))) {
        *was_stopped = true;
        break;
      }
    }
    ElapsedTimer sample_timer;
    profile->samples.push_back(Sample());
    native_sampler_->RecordStackSample(&profile->samples.back());
    previous_elapsed_sample_time = sample_timer.Elapsed();
  }

  *elapsed_time = profile_timer.Elapsed();
  profile->profile_duration = *elapsed_time;
  native_sampler_->ProfileRecordingStopped();
}

// In an analogous manner to CollectProfile() and samples exceeding the expected
// total sampling time, bursts may also exceed the burst_interval. We adopt the
// same wait-and-see approach here.
void StackSamplingProfiler::SamplingThread::CollectProfiles(
    CallStackProfiles* profiles) {
  if (stop_event_.TimedWait(params_.initial_delay))
    return;

  TimeDelta previous_elapsed_profile_time;
  for (int i = 0; i < params_.bursts; ++i) {
    if (i != 0) {
      // Always wait, even if for 0 seconds, so we can observe a signal on
      // stop_event_.
      if (stop_event_.TimedWait(
              std::max(params_.burst_interval - previous_elapsed_profile_time,
                       TimeDelta())))
        return;
    }

    CallStackProfile profile;
    bool was_stopped = false;
    CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped);
    if (!profile.samples.empty())
      profiles->push_back(std::move(profile));

    if (was_stopped)
      return;
  }
}

void StackSamplingProfiler::SamplingThread::Stop() {
  stop_event_.Signal();
}

// StackSamplingProfiler ------------------------------------------------------

subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0;

StackSamplingProfiler::StackSamplingProfiler(
    PlatformThreadId thread_id,
    const SamplingParams& params,
    const CompletedCallback& callback)
    : StackSamplingProfiler(thread_id, params, callback, nullptr) {}

StackSamplingProfiler::StackSamplingProfiler(
    PlatformThreadId thread_id,
    const SamplingParams& params,
    const CompletedCallback& callback,
    NativeStackSamplerTestDelegate* test_delegate)
    : thread_id_(thread_id), params_(params), completed_callback_(callback),
      test_delegate_(test_delegate) {
}

StackSamplingProfiler::~StackSamplingProfiler() {
  Stop();
  if (!sampling_thread_handle_.is_null())
    PlatformThread::Join(sampling_thread_handle_);
}

// static
void StackSamplingProfiler::StartAndRunAsync(
    PlatformThreadId thread_id,
    const SamplingParams& params,
    const CompletedCallback& callback) {
  CHECK(ThreadTaskRunnerHandle::Get());
  AsyncRunner::Run(thread_id, params, callback);
}

void StackSamplingProfiler::Start() {
  if (completed_callback_.is_null())
    return;

  std::unique_ptr<NativeStackSampler> native_sampler =
      NativeStackSampler::Create(thread_id_, &RecordAnnotations,
                                 test_delegate_);
  if (!native_sampler)
    return;

  sampling_thread_.reset(new SamplingThread(std::move(native_sampler), params_,
                                            completed_callback_));
  if (!PlatformThread::Create(0, sampling_thread_.get(),
                              &sampling_thread_handle_))
    sampling_thread_.reset();
}

void StackSamplingProfiler::Stop() {
  if (sampling_thread_)
    sampling_thread_->Stop();
}

// static
void StackSamplingProfiler::SetProcessMilestone(int milestone) {
  DCHECK_LE(0, milestone);
  DCHECK_GT(static_cast<int>(sizeof(process_milestones_) * 8), milestone);
  DCHECK_EQ(0, subtle::NoBarrier_Load(&process_milestones_) & (1 << milestone));
  ChangeAtomicFlags(&process_milestones_, 1 << milestone, 0);
}

// static
void StackSamplingProfiler::ResetAnnotationsForTesting() {
  subtle::NoBarrier_Store(&process_milestones_, 0u);
}

// static
void StackSamplingProfiler::RecordAnnotations(Sample* sample) {
  // The code inside this method must not do anything that could acquire a
  // mutex, including allocating memory (which includes LOG messages) because
  // that mutex could be held by a stopped thread, thus resulting in deadlock.
  sample->process_milestones = subtle::NoBarrier_Load(&process_milestones_);
}

// StackSamplingProfiler::Frame global functions ------------------------------

bool operator==(const StackSamplingProfiler::Module& a,
                const StackSamplingProfiler::Module& b) {
  return a.base_address == b.base_address && a.id == b.id &&
      a.filename == b.filename;
}

bool operator==(const StackSamplingProfiler::Sample& a,
                const StackSamplingProfiler::Sample& b) {
  return a.process_milestones == b.process_milestones && a.frames == b.frames;
}

bool operator!=(const StackSamplingProfiler::Sample& a,
                const StackSamplingProfiler::Sample& b) {
  return !(a == b);
}

bool operator<(const StackSamplingProfiler::Sample& a,
               const StackSamplingProfiler::Sample& b) {
  if (a.process_milestones < b.process_milestones)
    return true;
  if (a.process_milestones > b.process_milestones)
    return false;

  return a.frames < b.frames;
}

bool operator==(const StackSamplingProfiler::Frame &a,
                const StackSamplingProfiler::Frame &b) {
  return a.instruction_pointer == b.instruction_pointer &&
      a.module_index == b.module_index;
}

bool operator<(const StackSamplingProfiler::Frame &a,
               const StackSamplingProfiler::Frame &b) {
  return (a.module_index < b.module_index) ||
      (a.module_index == b.module_index &&
       a.instruction_pointer < b.instruction_pointer);
}

}  // namespace base