1 // Copyright 2016 the V8 project 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. 4 5 #include "src/profiler/tracing-cpu-profiler.h" 6 7 #include "src/profiler/cpu-profiler.h" 8 #include "src/tracing/trace-event.h" 9 #include "src/v8.h" 10 11 namespace v8 { 12 namespace internal { 13 TracingCpuProfilerImpl(Isolate * isolate)14TracingCpuProfilerImpl::TracingCpuProfilerImpl(Isolate* isolate) 15 : isolate_(isolate), profiling_enabled_(false) { 16 // Make sure tracing system notices profiler categories. 17 TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler")); 18 TRACE_EVENT_WARMUP_CATEGORY( 19 TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler.hires")); 20 V8::GetCurrentPlatform()->GetTracingController()->AddTraceStateObserver(this); 21 } 22 ~TracingCpuProfilerImpl()23TracingCpuProfilerImpl::~TracingCpuProfilerImpl() { 24 StopProfiling(); 25 V8::GetCurrentPlatform()->GetTracingController()->RemoveTraceStateObserver( 26 this); 27 } 28 OnTraceEnabled()29void TracingCpuProfilerImpl::OnTraceEnabled() { 30 bool enabled; 31 TRACE_EVENT_CATEGORY_GROUP_ENABLED( 32 TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"), &enabled); 33 if (!enabled) return; 34 profiling_enabled_ = true; 35 isolate_->RequestInterrupt( 36 [](v8::Isolate*, void* data) { 37 reinterpret_cast<TracingCpuProfilerImpl*>(data)->StartProfiling(); 38 }, 39 this); 40 } 41 OnTraceDisabled()42void TracingCpuProfilerImpl::OnTraceDisabled() { 43 base::LockGuard<base::Mutex> lock(&mutex_); 44 if (!profiling_enabled_) return; 45 profiling_enabled_ = false; 46 isolate_->RequestInterrupt( 47 [](v8::Isolate*, void* data) { 48 reinterpret_cast<TracingCpuProfilerImpl*>(data)->StopProfiling(); 49 }, 50 this); 51 } 52 StartProfiling()53void TracingCpuProfilerImpl::StartProfiling() { 54 base::LockGuard<base::Mutex> lock(&mutex_); 55 if (!profiling_enabled_ || profiler_) return; 56 bool enabled; 57 TRACE_EVENT_CATEGORY_GROUP_ENABLED( 58 TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler.hires"), &enabled); 59 int sampling_interval_us = enabled ? 100 : 1000; 60 profiler_.reset(new CpuProfiler(isolate_)); 61 profiler_->set_sampling_interval( 62 base::TimeDelta::FromMicroseconds(sampling_interval_us)); 63 profiler_->StartProfiling("", true); 64 } 65 StopProfiling()66void TracingCpuProfilerImpl::StopProfiling() { 67 base::LockGuard<base::Mutex> lock(&mutex_); 68 if (!profiler_) return; 69 profiler_->StopProfiling(""); 70 profiler_.reset(); 71 } 72 73 } // namespace internal 74 } // namespace v8 75