v8-profiler-agent-impl.cc 20.2 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/inspector/v8-profiler-agent-impl.h"
6

7 8
#include <vector>

9
#include "src/base/atomicops.h"
10
#include "src/debug/debug-interface.h"
11
#include "src/flags.h"  // TODO(jgruber): Remove include and DEPS entry.
12
#include "src/inspector/protocol/Protocol.h"
13 14 15 16 17
#include "src/inspector/string-util.h"
#include "src/inspector/v8-debugger.h"
#include "src/inspector/v8-inspector-impl.h"
#include "src/inspector/v8-inspector-session-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"
18

19 20
#include "include/v8-profiler.h"

21 22 23 24 25 26
namespace v8_inspector {

namespace ProfilerAgentState {
static const char samplingInterval[] = "samplingInterval";
static const char userInitiatedProfiling[] = "userInitiatedProfiling";
static const char profilerEnabled[] = "profilerEnabled";
27
static const char preciseCoverageStarted[] = "preciseCoverageStarted";
28
static const char preciseCoverageCallCount[] = "preciseCoverageCallCount";
29
static const char preciseCoverageDetailed[] = "preciseCoverageDetailed";
30
static const char typeProfileStarted[] = "typeProfileStarted";
31 32 33 34
}

namespace {

35 36 37 38 39 40 41 42 43
String16 resourceNameToUrl(V8InspectorImpl* inspector,
                           v8::Local<v8::String> v8Name) {
  String16 name = toProtocolString(inspector->isolate(), v8Name);
  if (!inspector) return name;
  std::unique_ptr<StringBuffer> url =
      inspector->client()->resourceNameToUrl(toStringView(name));
  return url ? toString16(url->string()) : name;
}

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
std::unique_ptr<protocol::Array<protocol::Profiler::PositionTickInfo>>
buildInspectorObjectForPositionTicks(const v8::CpuProfileNode* node) {
  unsigned lineCount = node->GetHitLineCount();
  if (!lineCount) return nullptr;
  auto array = protocol::Array<protocol::Profiler::PositionTickInfo>::create();
  std::vector<v8::CpuProfileNode::LineTick> entries(lineCount);
  if (node->GetLineTicks(&entries[0], lineCount)) {
    for (unsigned i = 0; i < lineCount; i++) {
      std::unique_ptr<protocol::Profiler::PositionTickInfo> line =
          protocol::Profiler::PositionTickInfo::create()
              .setLine(entries[i].line)
              .setTicks(entries[i].hit_count)
              .build();
      array->addItem(std::move(line));
    }
  }
  return array;
}

std::unique_ptr<protocol::Profiler::ProfileNode> buildInspectorObjectFor(
64 65
    V8InspectorImpl* inspector, const v8::CpuProfileNode* node) {
  v8::Isolate* isolate = inspector->isolate();
66 67 68
  v8::HandleScope handleScope(isolate);
  auto callFrame =
      protocol::Runtime::CallFrame::create()
69
          .setFunctionName(toProtocolString(isolate, node->GetFunctionName()))
70
          .setScriptId(String16::fromInteger(node->GetScriptId()))
71
          .setUrl(resourceNameToUrl(inspector, node->GetScriptResourceName()))
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
          .setLineNumber(node->GetLineNumber() - 1)
          .setColumnNumber(node->GetColumnNumber() - 1)
          .build();
  auto result = protocol::Profiler::ProfileNode::create()
                    .setCallFrame(std::move(callFrame))
                    .setHitCount(node->GetHitCount())
                    .setId(node->GetNodeId())
                    .build();

  const int childrenCount = node->GetChildrenCount();
  if (childrenCount) {
    auto children = protocol::Array<int>::create();
    for (int i = 0; i < childrenCount; i++)
      children->addItem(node->GetChild(i)->GetNodeId());
    result->setChildren(std::move(children));
  }

  const char* deoptReason = node->GetBailoutReason();
  if (deoptReason && deoptReason[0] && strcmp(deoptReason, "no reason"))
    result->setDeoptReason(deoptReason);

  auto positionTicks = buildInspectorObjectForPositionTicks(node);
  if (positionTicks) result->setPositionTicks(std::move(positionTicks));

  return result;
}

std::unique_ptr<protocol::Array<int>> buildInspectorObjectForSamples(
    v8::CpuProfile* v8profile) {
  auto array = protocol::Array<int>::create();
  int count = v8profile->GetSamplesCount();
  for (int i = 0; i < count; i++)
    array->addItem(v8profile->GetSample(i)->GetNodeId());
  return array;
}

std::unique_ptr<protocol::Array<int>> buildInspectorObjectForTimestamps(
    v8::CpuProfile* v8profile) {
  auto array = protocol::Array<int>::create();
  int count = v8profile->GetSamplesCount();
  uint64_t lastTime = v8profile->GetStartTime();
  for (int i = 0; i < count; i++) {
    uint64_t ts = v8profile->GetSampleTimestamp(i);
    array->addItem(static_cast<int>(ts - lastTime));
    lastTime = ts;
  }
  return array;
}

121 122
void flattenNodesTree(V8InspectorImpl* inspector,
                      const v8::CpuProfileNode* node,
123
                      protocol::Array<protocol::Profiler::ProfileNode>* list) {
124
  list->addItem(buildInspectorObjectFor(inspector, node));
125 126
  const int childrenCount = node->GetChildrenCount();
  for (int i = 0; i < childrenCount; i++)
127
    flattenNodesTree(inspector, node->GetChild(i), list);
128 129 130
}

std::unique_ptr<protocol::Profiler::Profile> createCPUProfile(
131
    V8InspectorImpl* inspector, v8::CpuProfile* v8profile) {
132
  auto nodes = protocol::Array<protocol::Profiler::ProfileNode>::create();
133
  flattenNodesTree(inspector, v8profile->GetTopDownRoot(), nodes.get());
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
  return protocol::Profiler::Profile::create()
      .setNodes(std::move(nodes))
      .setStartTime(static_cast<double>(v8profile->GetStartTime()))
      .setEndTime(static_cast<double>(v8profile->GetEndTime()))
      .setSamples(buildInspectorObjectForSamples(v8profile))
      .setTimeDeltas(buildInspectorObjectForTimestamps(v8profile))
      .build();
}

std::unique_ptr<protocol::Debugger::Location> currentDebugLocation(
    V8InspectorImpl* inspector) {
  std::unique_ptr<V8StackTraceImpl> callStack =
      inspector->debugger()->captureStackTrace(false /* fullStack */);
  auto location = protocol::Debugger::Location::create()
                      .setScriptId(toString16(callStack->topScriptId()))
                      .setLineNumber(callStack->topLineNumber())
                      .build();
  location->setColumnNumber(callStack->topColumnNumber());
  return location;
}

volatile int s_lastProfileId = 0;

}  // namespace

class V8ProfilerAgentImpl::ProfileDescriptor {
 public:
  ProfileDescriptor(const String16& id, const String16& title)
      : m_id(id), m_title(title) {}
  String16 m_id;
  String16 m_title;
};

V8ProfilerAgentImpl::V8ProfilerAgentImpl(
    V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel,
    protocol::DictionaryValue* state)
    : m_session(session),
      m_isolate(m_session->inspector()->isolate()),
      m_state(state),
173
      m_frontend(frontendChannel) {}
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

V8ProfilerAgentImpl::~V8ProfilerAgentImpl() {
  if (m_profiler) m_profiler->Dispose();
}

void V8ProfilerAgentImpl::consoleProfile(const String16& title) {
  if (!m_enabled) return;
  String16 id = nextProfileId();
  m_startedProfiles.push_back(ProfileDescriptor(id, title));
  startProfiling(id);
  m_frontend.consoleProfileStarted(
      id, currentDebugLocation(m_session->inspector()), title);
}

void V8ProfilerAgentImpl::consoleProfileEnd(const String16& title) {
  if (!m_enabled) return;
  String16 id;
  String16 resolvedTitle;
  // Take last started profile if no title was passed.
  if (title.isEmpty()) {
    if (m_startedProfiles.empty()) return;
    id = m_startedProfiles.back().m_id;
    resolvedTitle = m_startedProfiles.back().m_title;
    m_startedProfiles.pop_back();
  } else {
    for (size_t i = 0; i < m_startedProfiles.size(); i++) {
      if (m_startedProfiles[i].m_title == title) {
        resolvedTitle = title;
        id = m_startedProfiles[i].m_id;
        m_startedProfiles.erase(m_startedProfiles.begin() + i);
        break;
      }
    }
    if (id.isEmpty()) return;
  }
  std::unique_ptr<protocol::Profiler::Profile> profile =
      stopProfiling(id, true);
  if (!profile) return;
  std::unique_ptr<protocol::Debugger::Location> location =
      currentDebugLocation(m_session->inspector());
  m_frontend.consoleProfileFinished(id, std::move(location), std::move(profile),
                                    resolvedTitle);
}

218 219
Response V8ProfilerAgentImpl::enable() {
  if (m_enabled) return Response::OK();
220 221
  m_enabled = true;
  m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
222
  return Response::OK();
223 224
}

225 226
Response V8ProfilerAgentImpl::disable() {
  if (!m_enabled) return Response::OK();
227 228 229
  for (size_t i = m_startedProfiles.size(); i > 0; --i)
    stopProfiling(m_startedProfiles[i - 1].m_id, false);
  m_startedProfiles.clear();
230
  stop(nullptr);
231 232
  stopPreciseCoverage();
  DCHECK(!m_profiler);
233 234
  m_enabled = false;
  m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
235
  return Response::OK();
236 237
}

238
Response V8ProfilerAgentImpl::setSamplingInterval(int interval) {
239
  if (m_profiler) {
240
    return Response::Error("Cannot change sampling interval when profiling.");
241
  }
242
  m_state->setInteger(ProfilerAgentState::samplingInterval, interval);
243
  return Response::OK();
244 245 246 247 248 249 250 251 252 253
}

void V8ProfilerAgentImpl::restore() {
  DCHECK(!m_enabled);
  if (!m_state->booleanProperty(ProfilerAgentState::profilerEnabled, false))
    return;
  m_enabled = true;
  DCHECK(!m_profiler);
  if (m_state->booleanProperty(ProfilerAgentState::userInitiatedProfiling,
                               false)) {
254
    start();
255
  }
256 257
  if (m_state->booleanProperty(ProfilerAgentState::preciseCoverageStarted,
                               false)) {
258 259
    bool callCount = m_state->booleanProperty(
        ProfilerAgentState::preciseCoverageCallCount, false);
260 261
    bool detailed = m_state->booleanProperty(
        ProfilerAgentState::preciseCoverageDetailed, false);
262
    startPreciseCoverage(Maybe<bool>(callCount), Maybe<bool>(detailed));
263
  }
264 265
}

266 267 268
Response V8ProfilerAgentImpl::start() {
  if (m_recordingCPUProfile) return Response::OK();
  if (!m_enabled) return Response::Error("Profiler is not enabled");
269 270 271 272
  m_recordingCPUProfile = true;
  m_frontendInitiatedProfileId = nextProfileId();
  startProfiling(m_frontendInitiatedProfileId);
  m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
273
  return Response::OK();
274 275
}

276
Response V8ProfilerAgentImpl::stop(
277
    std::unique_ptr<protocol::Profiler::Profile>* profile) {
278
  if (!m_recordingCPUProfile) {
279
    return Response::Error("No recording profiles found");
280
  }
281 282 283 284 285
  m_recordingCPUProfile = false;
  std::unique_ptr<protocol::Profiler::Profile> cpuProfile =
      stopProfiling(m_frontendInitiatedProfileId, !!profile);
  if (profile) {
    *profile = std::move(cpuProfile);
286
    if (!profile->get()) return Response::Error("Profile is not found");
287 288 289
  }
  m_frontendInitiatedProfileId = String16();
  m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
290
  return Response::OK();
291 292
}

293 294
Response V8ProfilerAgentImpl::startPreciseCoverage(Maybe<bool> callCount,
                                                   Maybe<bool> detailed) {
295
  if (!m_enabled) return Response::Error("Profiler is not enabled");
296
  bool callCountValue = callCount.fromMaybe(false);
297
  bool detailedValue = detailed.fromMaybe(false);
298
  m_state->setBoolean(ProfilerAgentState::preciseCoverageStarted, true);
299 300
  m_state->setBoolean(ProfilerAgentState::preciseCoverageCallCount,
                      callCountValue);
301 302
  m_state->setBoolean(ProfilerAgentState::preciseCoverageDetailed,
                      detailedValue);
303 304 305 306
  // BlockCount is a superset of PreciseCount. It includes block-granularity
  // coverage data if it exists (at the time of writing, that's the case for
  // each function recompiled after the BlockCount mode has been set); and
  // function-granularity coverage data otherwise.
307 308 309 310 311
  typedef v8::debug::Coverage C;
  C::Mode mode = callCountValue
                     ? (detailedValue ? C::kBlockCount : C::kPreciseCount)
                     : (detailedValue ? C::kBlockBinary : C::kPreciseBinary);
  C::SelectMode(m_isolate, mode);
312 313 314 315 316 317
  return Response::OK();
}

Response V8ProfilerAgentImpl::stopPreciseCoverage() {
  if (!m_enabled) return Response::Error("Profiler is not enabled");
  m_state->setBoolean(ProfilerAgentState::preciseCoverageStarted, false);
318
  m_state->setBoolean(ProfilerAgentState::preciseCoverageCallCount, false);
319
  m_state->setBoolean(ProfilerAgentState::preciseCoverageDetailed, false);
320
  v8::debug::Coverage::SelectMode(m_isolate, v8::debug::Coverage::kBestEffort);
321 322 323 324
  return Response::OK();
}

namespace {
325 326 327 328 329 330 331 332 333
std::unique_ptr<protocol::Profiler::CoverageRange> createCoverageRange(
    int start, int end, int count) {
  return protocol::Profiler::CoverageRange::create()
      .setStartOffset(start)
      .setEndOffset(end)
      .setCount(count)
      .build();
}

334
Response coverageToProtocol(
335
    V8InspectorImpl* inspector, const v8::debug::Coverage& coverage,
336 337 338 339
    std::unique_ptr<protocol::Array<protocol::Profiler::ScriptCoverage>>*
        out_result) {
  std::unique_ptr<protocol::Array<protocol::Profiler::ScriptCoverage>> result =
      protocol::Array<protocol::Profiler::ScriptCoverage>::create();
340
  v8::Isolate* isolate = inspector->isolate();
341 342 343 344 345 346 347 348 349 350 351
  for (size_t i = 0; i < coverage.ScriptCount(); i++) {
    v8::debug::Coverage::ScriptData script_data = coverage.GetScriptData(i);
    v8::Local<v8::debug::Script> script = script_data.GetScript();
    std::unique_ptr<protocol::Array<protocol::Profiler::FunctionCoverage>>
        functions =
            protocol::Array<protocol::Profiler::FunctionCoverage>::create();
    for (size_t j = 0; j < script_data.FunctionCount(); j++) {
      v8::debug::Coverage::FunctionData function_data =
          script_data.GetFunctionData(j);
      std::unique_ptr<protocol::Array<protocol::Profiler::CoverageRange>>
          ranges = protocol::Array<protocol::Profiler::CoverageRange>::create();
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

      // Add function range.
      ranges->addItem(createCoverageRange(function_data.StartOffset(),
                                          function_data.EndOffset(),
                                          function_data.Count()));

      // Process inner blocks.
      for (size_t k = 0; k < function_data.BlockCount(); k++) {
        v8::debug::Coverage::BlockData block_data =
            function_data.GetBlockData(k);
        ranges->addItem(createCoverageRange(block_data.StartOffset(),
                                            block_data.EndOffset(),
                                            block_data.Count()));
      }

367 368 369
      functions->addItem(
          protocol::Profiler::FunctionCoverage::create()
              .setFunctionName(toProtocolString(
370
                  isolate,
371 372
                  function_data.Name().FromMaybe(v8::Local<v8::String>())))
              .setRanges(std::move(ranges))
373
              .setIsBlockCoverage(function_data.HasBlockCoverage())
374 375 376 377
              .build());
    }
    String16 url;
    v8::Local<v8::String> name;
378
    if (script->SourceURL().ToLocal(&name) && name->Length()) {
379
      url = toProtocolString(isolate, name);
380 381
    } else if (script->Name().ToLocal(&name) && name->Length()) {
      url = resourceNameToUrl(inspector, name);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    }
    result->addItem(protocol::Profiler::ScriptCoverage::create()
                        .setScriptId(String16::fromInteger(script->Id()))
                        .setUrl(url)
                        .setFunctions(std::move(functions))
                        .build());
  }
  *out_result = std::move(result);
  return Response::OK();
}
}  // anonymous namespace

Response V8ProfilerAgentImpl::takePreciseCoverage(
    std::unique_ptr<protocol::Array<protocol::Profiler::ScriptCoverage>>*
        out_result) {
  if (!m_state->booleanProperty(ProfilerAgentState::preciseCoverageStarted,
                                false)) {
    return Response::Error("Precise coverage has not been started.");
  }
401 402
  v8::HandleScope handle_scope(m_isolate);
  v8::debug::Coverage coverage = v8::debug::Coverage::CollectPrecise(m_isolate);
403
  return coverageToProtocol(m_session->inspector(), coverage, out_result);
404 405 406 407 408
}

Response V8ProfilerAgentImpl::getBestEffortCoverage(
    std::unique_ptr<protocol::Array<protocol::Profiler::ScriptCoverage>>*
        out_result) {
409 410 411
  v8::HandleScope handle_scope(m_isolate);
  v8::debug::Coverage coverage =
      v8::debug::Coverage::CollectBestEffort(m_isolate);
412
  return coverageToProtocol(m_session->inspector(), coverage, out_result);
413 414
}

415 416
namespace {
std::unique_ptr<protocol::Array<protocol::Profiler::ScriptTypeProfile>>
417
typeProfileToProtocol(V8InspectorImpl* inspector,
418 419 420
                      const v8::debug::TypeProfile& type_profile) {
  std::unique_ptr<protocol::Array<protocol::Profiler::ScriptTypeProfile>>
      result = protocol::Array<protocol::Profiler::ScriptTypeProfile>::create();
421
  v8::Isolate* isolate = inspector->isolate();
422 423 424 425 426 427 428 429 430 431 432 433
  for (size_t i = 0; i < type_profile.ScriptCount(); i++) {
    v8::debug::TypeProfile::ScriptData script_data =
        type_profile.GetScriptData(i);
    v8::Local<v8::debug::Script> script = script_data.GetScript();
    std::unique_ptr<protocol::Array<protocol::Profiler::TypeProfileEntry>>
        entries =
            protocol::Array<protocol::Profiler::TypeProfileEntry>::create();

    for (const auto& entry : script_data.Entries()) {
      std::unique_ptr<protocol::Array<protocol::Profiler::TypeObject>> types =
          protocol::Array<protocol::Profiler::TypeObject>::create();
      for (const auto& type : entry.Types()) {
434 435 436 437 438
        types->addItem(
            protocol::Profiler::TypeObject::create()
                .setName(toProtocolString(
                    isolate, type.FromMaybe(v8::Local<v8::String>())))
                .build());
439 440 441 442 443 444 445 446
      }
      entries->addItem(protocol::Profiler::TypeProfileEntry::create()
                           .setOffset(entry.SourcePosition())
                           .setTypes(std::move(types))
                           .build());
    }
    String16 url;
    v8::Local<v8::String> name;
447
    if (script->SourceURL().ToLocal(&name) && name->Length()) {
448
      url = toProtocolString(isolate, name);
449 450
    } else if (script->Name().ToLocal(&name) && name->Length()) {
      url = resourceNameToUrl(inspector, name);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    }
    result->addItem(protocol::Profiler::ScriptTypeProfile::create()
                        .setScriptId(String16::fromInteger(script->Id()))
                        .setUrl(url)
                        .setEntries(std::move(entries))
                        .build());
  }
  return result;
}
}  // anonymous namespace

Response V8ProfilerAgentImpl::startTypeProfile() {
  m_state->setBoolean(ProfilerAgentState::typeProfileStarted, true);
  v8::debug::TypeProfile::SelectMode(m_isolate,
                                     v8::debug::TypeProfile::kCollect);
  return Response::OK();
}

Response V8ProfilerAgentImpl::stopTypeProfile() {
  m_state->setBoolean(ProfilerAgentState::typeProfileStarted, false);
  v8::debug::TypeProfile::SelectMode(m_isolate, v8::debug::TypeProfile::kNone);
  return Response::OK();
}

Response V8ProfilerAgentImpl::takeTypeProfile(
    std::unique_ptr<protocol::Array<protocol::Profiler::ScriptTypeProfile>>*
        out_result) {
  if (!m_state->booleanProperty(ProfilerAgentState::typeProfileStarted,
                                false)) {
    return Response::Error("Type profile has not been started.");
  }
  v8::HandleScope handle_scope(m_isolate);
  v8::debug::TypeProfile type_profile =
      v8::debug::TypeProfile::Collect(m_isolate);
485
  *out_result = typeProfileToProtocol(m_session->inspector(), type_profile);
486 487 488
  return Response::OK();
}

489
String16 V8ProfilerAgentImpl::nextProfileId() {
490
  return String16::fromInteger(
491
      v8::base::Relaxed_AtomicIncrement(&s_lastProfileId, 1));
492 493 494 495
}

void V8ProfilerAgentImpl::startProfiling(const String16& title) {
  v8::HandleScope handleScope(m_isolate);
496 497 498 499 500 501 502 503
  if (!m_startedProfilesCount) {
    DCHECK(!m_profiler);
    m_profiler = v8::CpuProfiler::New(m_isolate);
    int interval =
        m_state->integerProperty(ProfilerAgentState::samplingInterval, 0);
    if (interval) m_profiler->SetSamplingInterval(interval);
  }
  ++m_startedProfilesCount;
504
  m_profiler->StartProfiling(toV8String(m_isolate, title), true);
505 506 507 508 509 510
}

std::unique_ptr<protocol::Profiler::Profile> V8ProfilerAgentImpl::stopProfiling(
    const String16& title, bool serialize) {
  v8::HandleScope handleScope(m_isolate);
  v8::CpuProfile* profile =
511
      m_profiler->StopProfiling(toV8String(m_isolate, title));
512
  std::unique_ptr<protocol::Profiler::Profile> result;
513
  if (profile) {
514
    if (serialize) result = createCPUProfile(m_session->inspector(), profile);
515 516 517 518 519 520 521
    profile->Delete();
  }
  --m_startedProfilesCount;
  if (!m_startedProfilesCount) {
    m_profiler->Dispose();
    m_profiler = nullptr;
  }
522 523 524 525
  return result;
}

}  // namespace v8_inspector