cpu-profiler.cc 16.8 KB
Newer Older
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
// Copyright 2010 the V8 project authors. All rights reserved.
// 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"

mikhail.naganov@gmail.com's avatar
mikhail.naganov@gmail.com committed
32
#ifdef ENABLE_LOGGING_AND_PROFILING
33

34
#include "frames-inl.h"
35 36
#include "log-inl.h"

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

39 40 41 42 43 44 45 46 47 48
namespace v8 {
namespace internal {

static const int kEventsBufferSize = 256*KB;
static const int kTickSamplesBufferChunkSize = 64*KB;
static const int kTickSamplesBufferChunksCount = 16;


ProfilerEventsProcessor::ProfilerEventsProcessor(ProfileGenerator* generator)
    : generator_(generator),
49
      running_(true),
50 51 52
      ticks_buffer_(sizeof(TickSampleEventRecord),
                    kTickSamplesBufferChunkSize,
                    kTickSamplesBufferChunksCount),
53 54
      enqueue_order_(0) {
}
55 56


57 58 59 60
void ProfilerEventsProcessor::CallbackCreateEvent(Logger::LogEventsAndTags tag,
                                                  const char* prefix,
                                                  String* name,
                                                  Address start) {
61
  if (FilterOutCodeCreateEvent(tag)) return;
62 63 64 65 66 67 68 69 70 71 72
  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;
  events_buffer_.Enqueue(evt_rec);
}


73 74 75 76 77 78
void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              String* name,
                                              String* resource_name,
                                              int line_number,
                                              Address start,
                                              unsigned size) {
79
  if (FilterOutCodeCreateEvent(tag)) return;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
  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;
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              const char* name,
                                              Address start,
                                              unsigned size) {
95
  if (FilterOutCodeCreateEvent(tag)) return;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  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;
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::CodeCreateEvent(Logger::LogEventsAndTags tag,
                                              int args_count,
                                              Address start,
                                              unsigned size) {
111
  if (FilterOutCodeCreateEvent(tag)) return;
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
  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;
  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);
}


void ProfilerEventsProcessor::CodeDeleteEvent(Address from) {
  CodeEventsContainer evt_rec;
  CodeDeleteEventRecord* rec = &evt_rec.CodeDeleteEventRecord_;
  rec->type = CodeEventRecord::CODE_DELETE;
  rec->order = ++enqueue_order_;
  rec->start = from;
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::FunctionCreateEvent(Address alias,
145 146
                                                  Address start,
                                                  int security_token_id) {
147 148 149 150
  CodeEventsContainer evt_rec;
  CodeAliasEventRecord* rec = &evt_rec.CodeAliasEventRecord_;
  rec->type = CodeEventRecord::CODE_ALIAS;
  rec->order = ++enqueue_order_;
151 152 153
  rec->start = alias;
  rec->entry = generator_->NewCodeEntry(security_token_id);
  rec->code_start = start;
154 155 156 157 158 159 160 161 162 163 164 165 166 167
  events_buffer_.Enqueue(evt_rec);
}


void ProfilerEventsProcessor::FunctionMoveEvent(Address from, Address to) {
  CodeMoveEvent(from, to);
}


void ProfilerEventsProcessor::FunctionDeleteEvent(Address from) {
  CodeDeleteEvent(from);
}


168 169 170 171 172 173
void ProfilerEventsProcessor::RegExpCodeCreateEvent(
    Logger::LogEventsAndTags tag,
    const char* prefix,
    String* name,
    Address start,
    unsigned size) {
174
  if (FilterOutCodeCreateEvent(tag)) return;
175 176 177 178 179 180 181 182 183 184 185
  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);
}


186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
void ProfilerEventsProcessor::AddCurrentStack() {
  TickSampleEventRecord record;
  TickSample* sample = &record.sample;
  sample->state = VMState::current_state();
  sample->pc = reinterpret_cast<Address>(sample);  // Not NULL.
  sample->frames_count = 0;
  for (StackTraceFrameIterator it;
       !it.done() && sample->frames_count < TickSample::kMaxFramesCount;
       it.Advance()) {
    JavaScriptFrame* frame = it.frame();
    sample->stack[sample->frames_count++] =
        reinterpret_cast<Address>(frame->function());
  }
  record.order = enqueue_order_;
  ticks_from_vm_buffer_.Enqueue(record);
}


204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
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) {
228 229 230 231 232 233 234
    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);
    }

235
    const TickSampleEventRecord* rec =
236
        TickSampleEventRecord::cast(ticks_buffer_.StartDequeue());
237
    if (rec == NULL) return !ticks_from_vm_buffer_.IsEmpty();
238 239 240 241 242 243 244 245 246 247 248 249 250
    // 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
          || record.sample.frames_count >= TickSample::kMaxFramesCount)
        record.sample.frames_count = 0;
      generator_->RecordTickSample(record.sample);
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
      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)) { }
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

CpuProfiler* CpuProfiler::singleton_ = NULL;

void CpuProfiler::StartProfiling(const char* title) {
  ASSERT(singleton_ != NULL);
  singleton_->StartCollectingProfile(title);
}


void CpuProfiler::StartProfiling(String* title) {
  ASSERT(singleton_ != NULL);
  singleton_->StartCollectingProfile(title);
}


CpuProfile* CpuProfiler::StopProfiling(const char* title) {
294
  return is_profiling() ? singleton_->StopCollectingProfile(title) : NULL;
295 296 297
}


298 299 300
CpuProfile* CpuProfiler::StopProfiling(Object* security_token, String* title) {
  return is_profiling() ?
      singleton_->StopCollectingProfile(security_token, title) : NULL;
301 302 303 304 305
}


int CpuProfiler::GetProfilesCount() {
  ASSERT(singleton_ != NULL);
306
  // The count of profiles doesn't depend on a security token.
307 308
  return singleton_->profiles_->Profiles(
      TokenEnumerator::kNoSecurityToken)->length();
309 310 311
}


312
CpuProfile* CpuProfiler::GetProfile(Object* security_token, int index) {
313
  ASSERT(singleton_ != NULL);
314 315
  const int token = singleton_->token_enumerator_->GetTokenId(security_token);
  return singleton_->profiles_->Profiles(token)->at(index);
316 317 318
}


319
CpuProfile* CpuProfiler::FindProfile(Object* security_token, unsigned uid) {
320
  ASSERT(singleton_ != NULL);
321 322
  const int token = singleton_->token_enumerator_->GetTokenId(security_token);
  return singleton_->profiles_->GetProfile(token, uid);
323 324 325 326
}


TickSample* CpuProfiler::TickSampleEvent() {
327
  if (CpuProfiler::is_profiling()) {
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
    return singleton_->processor_->TickSampleEvent();
  } else {
    return NULL;
  }
}


void CpuProfiler::CallbackEvent(String* name, Address entry_point) {
  singleton_->processor_->CallbackCreateEvent(
      Logger::CALLBACK_TAG, CodeEntry::kEmptyNamePrefix, name, entry_point);
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, const char* comment) {
  singleton_->processor_->CodeCreateEvent(
      tag, comment, code->address(), code->ExecutableSize());
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, String* name) {
  singleton_->processor_->CodeCreateEvent(
      tag,
      name,
      Heap::empty_string(),
354
      v8::CpuProfileNode::kNoLineNumberInfo,
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 380 381 382 383 384 385 386 387 388 389 390 391 392 393
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, String* name,
                           String* source, int line) {
  singleton_->processor_->CodeCreateEvent(
      tag,
      name,
      source,
      line,
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::CodeCreateEvent(Logger::LogEventsAndTags tag,
                           Code* code, int args_count) {
  singleton_->processor_->CodeCreateEvent(
      tag,
      args_count,
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::CodeMoveEvent(Address from, Address to) {
  singleton_->processor_->CodeMoveEvent(from, to);
}


void CpuProfiler::CodeDeleteEvent(Address from) {
  singleton_->processor_->CodeDeleteEvent(from);
}


void CpuProfiler::FunctionCreateEvent(JSFunction* function) {
394
  int security_token_id = TokenEnumerator::kNoSecurityToken;
395 396 397 398
  if (function->unchecked_context()->IsContext()) {
    security_token_id = singleton_->token_enumerator_->GetTokenId(
        function->context()->global_context()->security_token());
  }
399
  singleton_->processor_->FunctionCreateEvent(
400 401 402
      function->address(),
      function->code()->address(),
      security_token_id);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
}


void CpuProfiler::FunctionMoveEvent(Address from, Address to) {
  singleton_->processor_->FunctionMoveEvent(from, to);
}


void CpuProfiler::FunctionDeleteEvent(Address from) {
  singleton_->processor_->FunctionDeleteEvent(from);
}


void CpuProfiler::GetterCallbackEvent(String* name, Address entry_point) {
  singleton_->processor_->CallbackCreateEvent(
      Logger::CALLBACK_TAG, "get ", name, entry_point);
}


void CpuProfiler::RegExpCodeCreateEvent(Code* code, String* source) {
423
  singleton_->processor_->RegExpCodeCreateEvent(
424
      Logger::REG_EXP_TAG,
425
      "RegExp: ",
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
      source,
      code->address(),
      code->ExecutableSize());
}


void CpuProfiler::SetterCallbackEvent(String* name, Address entry_point) {
  singleton_->processor_->CallbackCreateEvent(
      Logger::CALLBACK_TAG, "set ", name, entry_point);
}


CpuProfiler::CpuProfiler()
    : profiles_(new CpuProfilesCollection()),
      next_profile_uid_(1),
441
      token_enumerator_(new TokenEnumerator()),
442 443 444 445 446 447
      generator_(NULL),
      processor_(NULL) {
}


CpuProfiler::~CpuProfiler() {
448
  delete token_enumerator_;
449 450 451 452 453
  delete profiles_;
}


void CpuProfiler::StartCollectingProfile(const char* title) {
454
  if (profiles_->StartProfiling(title, next_profile_uid_++)) {
455 456
    StartProcessorIfNotStarted();
  }
457
  processor_->AddCurrentStack();
458 459 460 461
}


void CpuProfiler::StartCollectingProfile(String* title) {
462
  StartCollectingProfile(profiles_->GetName(title));
463 464 465 466 467
}


void CpuProfiler::StartProcessorIfNotStarted() {
  if (processor_ == NULL) {
468 469 470
    // Disable logging when using the new implementation.
    saved_logging_nesting_ = Logger::logging_nesting_;
    Logger::logging_nesting_ = 0;
471 472 473 474 475 476 477 478 479 480
    generator_ = new ProfileGenerator(profiles_);
    processor_ = new ProfilerEventsProcessor(generator_);
    processor_->Start();
    // Enumerate stuff we already have in the heap.
    if (Heap::HasBeenSetup()) {
      Logger::LogCodeObjects();
      Logger::LogCompiledFunctions();
      Logger::LogFunctionObjects();
      Logger::LogAccessorCallbacks();
    }
481 482
    // Enable stack sampling.
    reinterpret_cast<Sampler*>(Logger::ticker_)->Start();
483 484 485 486 487
  }
}


CpuProfile* CpuProfiler::StopCollectingProfile(const char* title) {
488
  const double actual_sampling_rate = generator_->actual_sampling_rate();
489
  StopProcessorIfLastProfile(title);
490 491 492 493
  CpuProfile* result =
      profiles_->StopProfiling(TokenEnumerator::kNoSecurityToken,
                               title,
                               actual_sampling_rate);
494 495 496 497 498 499 500
  if (result != NULL) {
    result->Print();
  }
  return result;
}


501 502
CpuProfile* CpuProfiler::StopCollectingProfile(Object* security_token,
                                               String* title) {
503
  const double actual_sampling_rate = generator_->actual_sampling_rate();
504 505
  const char* profile_title = profiles_->GetName(title);
  StopProcessorIfLastProfile(profile_title);
506
  int token = token_enumerator_->GetTokenId(security_token);
507
  return profiles_->StopProfiling(token, profile_title, actual_sampling_rate);
508 509 510
}


511 512
void CpuProfiler::StopProcessorIfLastProfile(const char* title) {
  if (profiles_->IsLastProfile(title)) {
513
    reinterpret_cast<Sampler*>(Logger::ticker_)->Stop();
514 515 516 517 518 519
    processor_->Stop();
    processor_->Join();
    delete processor_;
    delete generator_;
    processor_ = NULL;
    generator_ = NULL;
520
    Logger::logging_nesting_ = saved_logging_nesting_;
521 522 523
  }
}

524
} }  // namespace v8::internal
525

mikhail.naganov@gmail.com's avatar
mikhail.naganov@gmail.com committed
526
#endif  // ENABLE_LOGGING_AND_PROFILING
527 528 529 530 531

namespace v8 {
namespace internal {

void CpuProfiler::Setup() {
mikhail.naganov@gmail.com's avatar
mikhail.naganov@gmail.com committed
532
#ifdef ENABLE_LOGGING_AND_PROFILING
533 534 535 536 537 538 539 540
  if (singleton_ == NULL) {
    singleton_ = new CpuProfiler();
  }
#endif
}


void CpuProfiler::TearDown() {
mikhail.naganov@gmail.com's avatar
mikhail.naganov@gmail.com committed
541
#ifdef ENABLE_LOGGING_AND_PROFILING
542 543 544 545 546 547 548 549
  if (singleton_ != NULL) {
    delete singleton_;
  }
  singleton_ = NULL;
#endif
}

} }  // namespace v8::internal