cpu-profiler.cc 18.6 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
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
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "cpu-profiler-inl.h"

32
#include "frames-inl.h"
33
#include "hashmap.h"
34
#include "log-inl.h"
35
#include "vm-state-inl.h"
36

37 38
#include "../include/v8-profiler.h"

39 40 41
namespace v8 {
namespace internal {

42 43
static const int kEventsBufferSize = 256 * KB;
static const int kTickSamplesBufferChunkSize = 64 * KB;
44
static const int kTickSamplesBufferChunksCount = 16;
45
static const int kProfilerStackSize = 64 * KB;
46 47


48
ProfilerEventsProcessor::ProfilerEventsProcessor(ProfileGenerator* generator)
49
    : Thread(Thread::Options("v8:ProfEvntProc", kProfilerStackSize)),
50
      generator_(generator),
51
      running_(true),
52 53 54
      ticks_buffer_(sizeof(TickSampleEventRecord),
                    kTickSamplesBufferChunkSize,
                    kTickSamplesBufferChunksCount),
55
      enqueue_order_(0) {
56
}
57 58


59 60 61 62
void ProfilerEventsProcessor::CallbackCreateEvent(Logger::LogEventsAndTags tag,
                                                  const char* prefix,
                                                  String* name,
                                                  Address start) {
63
  if (FilterOutCodeCreateEvent(tag)) return;
64 65 66 67 68 69 70
  CodeEventsContainer evt_rec;
  CodeCreateEventRecord* rec = &evt_rec.CodeCreateEventRecord_;
  rec->type = CodeEventRecord::CODE_CREATION;
  rec->order = ++enqueue_order_;
  rec->start = start;
  rec->entry = generator_->NewCodeEntry(tag, prefix, name);
  rec->size = 1;
71
  rec->shared = NULL;
72 73 74 75
  events_buffer_.Enqueue(evt_rec);
}


76 77 78 79 80
void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              String* name,
                                              String* resource_name,
                                              int line_number,
                                              Address start,
81
                                              unsigned size,
82
                                              Address shared) {
83
  if (FilterOutCodeCreateEvent(tag)) return;
84 85 86 87 88 89 90
  CodeEventsContainer evt_rec;
  CodeCreateEventRecord* rec = &evt_rec.CodeCreateEventRecord_;
  rec->type = CodeEventRecord::CODE_CREATION;
  rec->order = ++enqueue_order_;
  rec->start = start;
  rec->entry = generator_->NewCodeEntry(tag, name, resource_name, line_number);
  rec->size = size;
91
  rec->shared = shared;
92 93 94 95 96 97 98 99
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              const char* name,
                                              Address start,
                                              unsigned size) {
100
  if (FilterOutCodeCreateEvent(tag)) return;
101 102 103 104 105 106 107
  CodeEventsContainer evt_rec;
  CodeCreateEventRecord* rec = &evt_rec.CodeCreateEventRecord_;
  rec->type = CodeEventRecord::CODE_CREATION;
  rec->order = ++enqueue_order_;
  rec->start = start;
  rec->entry = generator_->NewCodeEntry(tag, name);
  rec->size = size;
108
  rec->shared = NULL;
109 110 111 112 113 114 115 116
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              int args_count,
                                              Address start,
                                              unsigned size) {
117
  if (FilterOutCodeCreateEvent(tag)) return;
118 119 120 121 122 123 124
  CodeEventsContainer evt_rec;
  CodeCreateEventRecord* rec = &evt_rec.CodeCreateEventRecord_;
  rec->type = CodeEventRecord::CODE_CREATION;
  rec->order = ++enqueue_order_;
  rec->start = start;
  rec->entry = generator_->NewCodeEntry(tag, args_count);
  rec->size = size;
125
  rec->shared = NULL;
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::CodeMoveEvent(Address from, Address to) {
  CodeEventsContainer evt_rec;
  CodeMoveEventRecord* rec = &evt_rec.CodeMoveEventRecord_;
  rec->type = CodeEventRecord::CODE_MOVE;
  rec->order = ++enqueue_order_;
  rec->from = from;
  rec->to = to;
  events_buffer_.Enqueue(evt_rec);
}


141 142
void ProfilerEventsProcessor::SharedFunctionInfoMoveEvent(Address from,
                                                          Address to) {
143
  CodeEventsContainer evt_rec;
144 145 146
  SharedFunctionInfoMoveEventRecord* rec =
      &evt_rec.SharedFunctionInfoMoveEventRecord_;
  rec->type = CodeEventRecord::SHARED_FUNC_MOVE;
147
  rec->order = ++enqueue_order_;
148 149
  rec->from = from;
  rec->to = to;
150
  events_buffer_.Enqueue(evt_rec);
151 152 153
}


154 155 156 157 158 159
void ProfilerEventsProcessor::RegExpCodeCreateEvent(
    Logger::LogEventsAndTags tag,
    const char* prefix,
    String* name,
    Address start,
    unsigned size) {
160
  if (FilterOutCodeCreateEvent(tag)) return;
161 162 163 164 165 166 167 168 169 170 171
  CodeEventsContainer evt_rec;
  CodeCreateEventRecord* rec = &evt_rec.CodeCreateEventRecord_;
  rec->type = CodeEventRecord::CODE_CREATION;
  rec->order = ++enqueue_order_;
  rec->start = start;
  rec->entry = generator_->NewCodeEntry(tag, prefix, name);
  rec->size = size;
  events_buffer_.Enqueue(evt_rec);
}


172
void ProfilerEventsProcessor::AddCurrentStack() {
173
  TickSampleEventRecord record(enqueue_order_);
174
  TickSample* sample = &record.sample;
175 176
  Isolate* isolate = Isolate::Current();
  sample->state = isolate->current_vm_state();
177
  sample->pc = reinterpret_cast<Address>(sample);  // Not NULL.
178
  for (StackTraceFrameIterator it(isolate);
179 180
       !it.done() && sample->frames_count < TickSample::kMaxFramesCount;
       it.Advance()) {
181
    sample->stack[sample->frames_count++] = it.frame()->pc();
182 183 184 185 186
  }
  ticks_from_vm_buffer_.Enqueue(record);
}


187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
bool ProfilerEventsProcessor::ProcessCodeEvent(unsigned* dequeue_order) {
  if (!events_buffer_.IsEmpty()) {
    CodeEventsContainer record;
    events_buffer_.Dequeue(&record);
    switch (record.generic.type) {
#define PROFILER_TYPE_CASE(type, clss)                          \
      case CodeEventRecord::type:                               \
        record.clss##_.UpdateCodeMap(generator_->code_map());   \
        break;

      CODE_EVENTS_TYPE_LIST(PROFILER_TYPE_CASE)

#undef PROFILER_TYPE_CASE
      default: return true;  // Skip record.
    }
    *dequeue_order = record.generic.order;
    return true;
  }
  return false;
}


bool ProfilerEventsProcessor::ProcessTicks(unsigned dequeue_order) {
  while (true) {
211 212 213 214 215 216 217
    if (!ticks_from_vm_buffer_.IsEmpty()
        && ticks_from_vm_buffer_.Peek()->order == dequeue_order) {
      TickSampleEventRecord record;
      ticks_from_vm_buffer_.Dequeue(&record);
      generator_->RecordTickSample(record.sample);
    }

218
    const TickSampleEventRecord* rec =
219
        TickSampleEventRecord::cast(ticks_buffer_.StartDequeue());
220
    if (rec == NULL) return !ticks_from_vm_buffer_.IsEmpty();
221 222 223 224 225 226 227 228 229 230
    // Make a local copy of tick sample record to ensure that it won't
    // be modified as we are processing it. This is possible as the
    // sampler writes w/o any sync to the queue, so if the processor
    // will get far behind, a record may be modified right under its
    // feet.
    TickSampleEventRecord record = *rec;
    if (record.order == dequeue_order) {
      // A paranoid check to make sure that we don't get a memory overrun
      // in case of frames_count having a wild value.
      if (record.sample.frames_count < 0
231
          || record.sample.frames_count > TickSample::kMaxFramesCount)
232 233
        record.sample.frames_count = 0;
      generator_->RecordTickSample(record.sample);
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
      ticks_buffer_.FinishDequeue();
    } else {
      return true;
    }
  }
}


void ProfilerEventsProcessor::Run() {
  unsigned dequeue_order = 0;

  while (running_) {
    // Process ticks until we have any.
    if (ProcessTicks(dequeue_order)) {
      // All ticks of the current dequeue_order are processed,
      // proceed to the next code event.
      ProcessCodeEvent(&dequeue_order);
    }
    YieldCPU();
  }

  // Process remaining tick events.
  ticks_buffer_.FlushResidualRecords();
  // Perform processing until we have tick events, skip remaining code events.
  while (ProcessTicks(dequeue_order) && ProcessCodeEvent(&dequeue_order)) { }
}

261 262

void CpuProfiler::StartProfiling(const char* title) {
263 264
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  Isolate::Current()->cpu_profiler()->StartCollectingProfile(title);
265 266 267 268
}


void CpuProfiler::StartProfiling(String* title) {
269 270
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  Isolate::Current()->cpu_profiler()->StartCollectingProfile(title);
271 272 273 274
}


CpuProfile* CpuProfiler::StopProfiling(const char* title) {
275 276 277
  Isolate* isolate = Isolate::Current();
  return is_profiling(isolate) ?
      isolate->cpu_profiler()->StopCollectingProfile(title) : NULL;
278 279 280
}


281
CpuProfile* CpuProfiler::StopProfiling(Object* security_token, String* title) {
282 283 284
  Isolate* isolate = Isolate::Current();
  return is_profiling(isolate) ?
      isolate->cpu_profiler()->StopCollectingProfile(
285
          security_token, title) : NULL;
286 287 288 289
}


int CpuProfiler::GetProfilesCount() {
290
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
291
  // The count of profiles doesn't depend on a security token.
292
  return Isolate::Current()->cpu_profiler()->profiles_->Profiles(
293
      TokenEnumerator::kNoSecurityToken)->length();
294 295 296
}


297
CpuProfile* CpuProfiler::GetProfile(Object* security_token, int index) {
298 299 300 301
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  CpuProfiler* profiler = Isolate::Current()->cpu_profiler();
  const int token = profiler->token_enumerator_->GetTokenId(security_token);
  return profiler->profiles_->Profiles(token)->at(index);
302 303 304
}


305
CpuProfile* CpuProfiler::FindProfile(Object* security_token, unsigned uid) {
306 307 308 309
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  CpuProfiler* profiler = Isolate::Current()->cpu_profiler();
  const int token = profiler->token_enumerator_->GetTokenId(security_token);
  return profiler->profiles_->GetProfile(token, uid);
310 311 312
}


313 314 315
TickSample* CpuProfiler::TickSampleEvent(Isolate* isolate) {
  if (CpuProfiler::is_profiling(isolate)) {
    return isolate->cpu_profiler()->processor_->TickSampleEvent();
316 317 318 319 320 321
  } else {
    return NULL;
  }
}


322
void CpuProfiler::DeleteAllProfiles() {
323 324
  Isolate* isolate = Isolate::Current();
  ASSERT(isolate->cpu_profiler() != NULL);
325
  if (is_profiling(isolate)) {
326
    isolate->cpu_profiler()->StopProcessor();
327
  }
328
  isolate->cpu_profiler()->ResetProfiles();
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
}


void CpuProfiler::DeleteProfile(CpuProfile* profile) {
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  Isolate::Current()->cpu_profiler()->profiles_->RemoveProfile(profile);
  delete profile;
}


bool CpuProfiler::HasDetachedProfiles() {
  ASSERT(Isolate::Current()->cpu_profiler() != NULL);
  return Isolate::Current()->cpu_profiler()->profiles_->HasDetachedProfiles();
}


345
void CpuProfiler::CallbackEvent(String* name, Address entry_point) {
346
  Isolate::Current()->cpu_profiler()->processor_->CallbackCreateEvent(
347 348 349 350 351 352
      Logger::CALLBACK_TAG, CodeEntry::kEmptyNamePrefix, name, entry_point);
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, const char* comment) {
353
  Isolate::Current()->cpu_profiler()->processor_->CodeCreateEvent(
354 355 356 357 358 359
      tag, comment, code->address(), code->ExecutableSize());
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, String* name) {
360 361
  Isolate* isolate = Isolate::Current();
  isolate->cpu_profiler()->processor_->CodeCreateEvent(
362 363
      tag,
      name,
364
      isolate->heap()->empty_string(),
365
      v8::CpuProfileNode::kNoLineNumberInfo,
366
      code->address(),
367 368
      code->ExecutableSize(),
      NULL);
369 370 371 372
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
373 374 375
                                  Code* code,
                                  SharedFunctionInfo* shared,
                                  String* name) {
376 377
  Isolate* isolate = Isolate::Current();
  isolate->cpu_profiler()->processor_->CodeCreateEvent(
378 379
      tag,
      name,
380
      isolate->heap()->empty_string(),
381 382 383 384 385 386 387 388 389 390 391
      v8::CpuProfileNode::kNoLineNumberInfo,
      code->address(),
      code->ExecutableSize(),
      shared->address());
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                  Code* code,
                                  SharedFunctionInfo* shared,
                                  String* source, int line) {
392
  Isolate::Current()->cpu_profiler()->processor_->CodeCreateEvent(
393 394
      tag,
      shared->DebugName(),
395 396 397
      source,
      line,
      code->address(),
398 399
      code->ExecutableSize(),
      shared->address());
400 401 402 403 404
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, int args_count) {
405
  Isolate::Current()->cpu_profiler()->processor_->CodeCreateEvent(
406 407 408 409 410 411 412 413
      tag,
      args_count,
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::CodeMoveEvent(Address from, Address to) {
414
  Isolate::Current()->cpu_profiler()->processor_->CodeMoveEvent(from, to);
415 416 417 418 419 420 421
}


void CpuProfiler::CodeDeleteEvent(Address from) {
}


422
void CpuProfiler::SharedFunctionInfoMoveEvent(Address from, Address to) {
423 424
  CpuProfiler* profiler = Isolate::Current()->cpu_profiler();
  profiler->processor_->SharedFunctionInfoMoveEvent(from, to);
425 426 427 428
}


void CpuProfiler::GetterCallbackEvent(String* name, Address entry_point) {
429
  Isolate::Current()->cpu_profiler()->processor_->CallbackCreateEvent(
430 431 432 433 434
      Logger::CALLBACK_TAG, "get ", name, entry_point);
}


void CpuProfiler::RegExpCodeCreateEvent(Code* code, String* source) {
435
  Isolate::Current()->cpu_profiler()->processor_->RegExpCodeCreateEvent(
436
      Logger::REG_EXP_TAG,
437
      "RegExp: ",
438 439 440 441 442 443 444
      source,
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::SetterCallbackEvent(String* name, Address entry_point) {
445
  Isolate::Current()->cpu_profiler()->processor_->CallbackCreateEvent(
446 447 448 449 450 451 452
      Logger::CALLBACK_TAG, "set ", name, entry_point);
}


CpuProfiler::CpuProfiler()
    : profiles_(new CpuProfilesCollection()),
      next_profile_uid_(1),
453
      token_enumerator_(new TokenEnumerator()),
454
      generator_(NULL),
455
      processor_(NULL),
456
      need_to_stop_sampler_(false),
457
      is_profiling_(false) {
458 459 460 461
}


CpuProfiler::~CpuProfiler() {
462
  delete token_enumerator_;
463 464 465 466
  delete profiles_;
}


467 468 469 470 471
void CpuProfiler::ResetProfiles() {
  delete profiles_;
  profiles_ = new CpuProfilesCollection();
}

472
void CpuProfiler::StartCollectingProfile(const char* title) {
473
  if (profiles_->StartProfiling(title, next_profile_uid_++)) {
474 475
    StartProcessorIfNotStarted();
  }
476
  processor_->AddCurrentStack();
477 478 479 480
}


void CpuProfiler::StartCollectingProfile(String* title) {
481
  StartCollectingProfile(profiles_->GetName(title));
482 483 484 485 486
}


void CpuProfiler::StartProcessorIfNotStarted() {
  if (processor_ == NULL) {
487 488
    Isolate* isolate = Isolate::Current();

489
    // Disable logging when using the new implementation.
490 491
    saved_logging_nesting_ = isolate->logger()->logging_nesting_;
    isolate->logger()->logging_nesting_ = 0;
492
    generator_ = new ProfileGenerator(profiles_);
493
    processor_ = new ProfilerEventsProcessor(generator_);
494
    NoBarrier_Store(&is_profiling_, true);
495 496
    processor_->Start();
    // Enumerate stuff we already have in the heap.
497
    if (isolate->heap()->HasBeenSetUp()) {
498 499 500
      if (!FLAG_prof_browser_mode) {
        bool saved_log_code_flag = FLAG_log_code;
        FLAG_log_code = true;
501
        isolate->logger()->LogCodeObjects();
502 503
        FLAG_log_code = saved_log_code_flag;
      }
504 505
      isolate->logger()->LogCompiledFunctions();
      isolate->logger()->LogAccessorCallbacks();
506
    }
507
    // Enable stack sampling.
508
    Sampler* sampler = reinterpret_cast<Sampler*>(isolate->logger()->ticker_);
509 510 511 512
    if (!sampler->IsActive()) {
      sampler->Start();
      need_to_stop_sampler_ = true;
    }
513
    sampler->IncreaseProfilingDepth();
514 515 516 517 518
  }
}


CpuProfile* CpuProfiler::StopCollectingProfile(const char* title) {
519
  const double actual_sampling_rate = generator_->actual_sampling_rate();
520
  StopProcessorIfLastProfile(title);
521 522 523 524
  CpuProfile* result =
      profiles_->StopProfiling(TokenEnumerator::kNoSecurityToken,
                               title,
                               actual_sampling_rate);
525 526 527 528 529 530 531
  if (result != NULL) {
    result->Print();
  }
  return result;
}


532 533
CpuProfile* CpuProfiler::StopCollectingProfile(Object* security_token,
                                               String* title) {
534
  const double actual_sampling_rate = generator_->actual_sampling_rate();
535 536
  const char* profile_title = profiles_->GetName(title);
  StopProcessorIfLastProfile(profile_title);
537
  int token = token_enumerator_->GetTokenId(security_token);
538
  return profiles_->StopProfiling(token, profile_title, actual_sampling_rate);
539 540 541
}


542
void CpuProfiler::StopProcessorIfLastProfile(const char* title) {
543 544 545 546 547
  if (profiles_->IsLastProfile(title)) StopProcessor();
}


void CpuProfiler::StopProcessor() {
548 549
  Logger* logger = Isolate::Current()->logger();
  Sampler* sampler = reinterpret_cast<Sampler*>(logger->ticker_);
550 551 552 553
  sampler->DecreaseProfilingDepth();
  if (need_to_stop_sampler_) {
    sampler->Stop();
    need_to_stop_sampler_ = false;
554
  }
555
  NoBarrier_Store(&is_profiling_, false);
556 557 558 559 560 561
  processor_->Stop();
  processor_->Join();
  delete processor_;
  delete generator_;
  processor_ = NULL;
  generator_ = NULL;
562
  logger->logging_nesting_ = saved_logging_nesting_;
563 564 565
}


566
void CpuProfiler::SetUp() {
567 568 569
  Isolate* isolate = Isolate::Current();
  if (isolate->cpu_profiler() == NULL) {
    isolate->set_cpu_profiler(new CpuProfiler());
570 571 572 573 574
  }
}


void CpuProfiler::TearDown() {
575 576 577
  Isolate* isolate = Isolate::Current();
  if (isolate->cpu_profiler() != NULL) {
    delete isolate->cpu_profiler();
578
  }
579
  isolate->set_cpu_profiler(NULL);
580 581 582
}

} }  // namespace v8::internal