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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 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 485 486 487 488 489 490
|
// Copyright 2016 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 "core/inspector/ThreadDebugger.h"
#include "bindings/core/v8/SourceLocation.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMException.h"
#include "bindings/core/v8/V8DOMTokenList.h"
#include "bindings/core/v8/V8Event.h"
#include "bindings/core/v8/V8EventListener.h"
#include "bindings/core/v8/V8EventListenerHelper.h"
#include "bindings/core/v8/V8EventListenerInfo.h"
#include "bindings/core/v8/V8HTMLAllCollection.h"
#include "bindings/core/v8/V8HTMLCollection.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8NodeList.h"
#include "bindings/core/v8/V8ScriptRunner.h"
#include "core/dom/DocumentUserGestureToken.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InspectorDOMDebuggerAgent.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/inspector/V8InspectorString.h"
#include "platform/ScriptForbiddenScope.h"
#include "wtf/CurrentTime.h"
#include "wtf/PtrUtil.h"
#include <memory>
namespace blink {
ThreadDebugger::ThreadDebugger(v8::Isolate* isolate)
: m_isolate(isolate),
m_v8Inspector(v8_inspector::V8Inspector::create(isolate, this)),
m_v8TracingCpuProfiler(v8::TracingCpuProfiler::Create(isolate)) {}
ThreadDebugger::~ThreadDebugger() {}
// static
ThreadDebugger* ThreadDebugger::from(v8::Isolate* isolate) {
if (!isolate)
return nullptr;
V8PerIsolateData* data = V8PerIsolateData::from(isolate);
return data ? data->threadDebugger() : nullptr;
}
// static
MessageLevel ThreadDebugger::consoleAPITypeToMessageLevel(
v8_inspector::V8ConsoleAPIType type) {
switch (type) {
case v8_inspector::V8ConsoleAPIType::kDebug:
return DebugMessageLevel;
case v8_inspector::V8ConsoleAPIType::kLog:
return LogMessageLevel;
case v8_inspector::V8ConsoleAPIType::kInfo:
return InfoMessageLevel;
case v8_inspector::V8ConsoleAPIType::kWarning:
return WarningMessageLevel;
case v8_inspector::V8ConsoleAPIType::kError:
return ErrorMessageLevel;
default:
return LogMessageLevel;
}
}
void ThreadDebugger::willExecuteScript(v8::Isolate* isolate, int scriptId) {
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->v8Inspector()->willExecuteScript(isolate->GetCurrentContext(),
scriptId);
}
void ThreadDebugger::didExecuteScript(v8::Isolate* isolate) {
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->v8Inspector()->didExecuteScript(isolate->GetCurrentContext());
}
void ThreadDebugger::idleStarted(v8::Isolate* isolate) {
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->v8Inspector()->idleStarted();
}
void ThreadDebugger::idleFinished(v8::Isolate* isolate) {
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->v8Inspector()->idleFinished();
}
void ThreadDebugger::asyncTaskScheduled(const String& operationName,
void* task,
bool recurring) {
m_v8Inspector->asyncTaskScheduled(toV8InspectorStringView(operationName),
task, recurring);
}
void ThreadDebugger::asyncTaskCanceled(void* task) {
m_v8Inspector->asyncTaskCanceled(task);
}
void ThreadDebugger::allAsyncTasksCanceled() {
m_v8Inspector->allAsyncTasksCanceled();
}
void ThreadDebugger::asyncTaskStarted(void* task) {
m_v8Inspector->asyncTaskStarted(task);
}
void ThreadDebugger::asyncTaskFinished(void* task) {
m_v8Inspector->asyncTaskFinished(task);
}
unsigned ThreadDebugger::promiseRejected(
v8::Local<v8::Context> context,
const String& errorMessage,
v8::Local<v8::Value> exception,
std::unique_ptr<SourceLocation> location) {
const String defaultMessage = "Uncaught (in promise)";
String message = errorMessage;
if (message.isEmpty())
message = defaultMessage;
else if (message.startsWith("Uncaught "))
message = message.substring(0, 8) + " (in promise)" + message.substring(8);
reportConsoleMessage(toExecutionContext(context), JSMessageSource,
ErrorMessageLevel, message, location.get());
String url = location->url();
return v8Inspector()->exceptionThrown(
context, toV8InspectorStringView(defaultMessage), exception,
toV8InspectorStringView(message), toV8InspectorStringView(url),
location->lineNumber(), location->columnNumber(),
location->takeStackTrace(), location->scriptId());
}
void ThreadDebugger::promiseRejectionRevoked(v8::Local<v8::Context> context,
unsigned promiseRejectionId) {
const String message = "Handler added to rejected promise";
v8Inspector()->exceptionRevoked(context, promiseRejectionId,
toV8InspectorStringView(message));
}
void ThreadDebugger::beginUserGesture() {
m_userGestureIndicator = WTF::wrapUnique(
new UserGestureIndicator(DocumentUserGestureToken::create(nullptr)));
}
void ThreadDebugger::endUserGesture() {
m_userGestureIndicator.reset();
}
std::unique_ptr<v8_inspector::StringBuffer> ThreadDebugger::valueSubtype(
v8::Local<v8::Value> value) {
static const char kNode[] = "node";
static const char kArray[] = "array";
static const char kError[] = "error";
if (V8Node::hasInstance(value, m_isolate))
return toV8InspectorStringBuffer(kNode);
if (V8NodeList::hasInstance(value, m_isolate) ||
V8DOMTokenList::hasInstance(value, m_isolate) ||
V8HTMLCollection::hasInstance(value, m_isolate) ||
V8HTMLAllCollection::hasInstance(value, m_isolate)) {
return toV8InspectorStringBuffer(kArray);
}
if (V8DOMException::hasInstance(value, m_isolate))
return toV8InspectorStringBuffer(kError);
return nullptr;
}
bool ThreadDebugger::formatAccessorsAsProperties(v8::Local<v8::Value> value) {
return V8DOMWrapper::isWrapper(m_isolate, value);
}
double ThreadDebugger::currentTimeMS() {
return WTF::currentTimeMS();
}
bool ThreadDebugger::isInspectableHeapObject(v8::Local<v8::Object> object) {
if (object->InternalFieldCount() < v8DefaultWrapperInternalFieldCount)
return true;
v8::Local<v8::Value> wrapper =
object->GetInternalField(v8DOMWrapperObjectIndex);
// Skip wrapper boilerplates which are like regular wrappers but don't have
// native object.
if (!wrapper.IsEmpty() && wrapper->IsUndefined())
return false;
return true;
}
static void returnDataCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(info.Data());
}
static v8::Maybe<bool> createDataProperty(v8::Local<v8::Context> context,
v8::Local<v8::Object> object,
v8::Local<v8::Name> key,
v8::Local<v8::Value> value) {
v8::TryCatch tryCatch(context->GetIsolate());
v8::Isolate::DisallowJavascriptExecutionScope throwJs(
context->GetIsolate(),
v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
return object->CreateDataProperty(context, key, value);
}
static void createFunctionPropertyWithData(v8::Local<v8::Context> context,
v8::Local<v8::Object> object,
const char* name,
v8::FunctionCallback callback,
v8::Local<v8::Value> data,
const char* description) {
v8::Local<v8::String> funcName = v8String(context->GetIsolate(), name);
v8::Local<v8::Function> func;
if (!v8::Function::New(context, callback, data, 0,
v8::ConstructorBehavior::kThrow)
.ToLocal(&func))
return;
func->SetName(funcName);
v8::Local<v8::String> returnValue =
v8String(context->GetIsolate(), description);
v8::Local<v8::Function> toStringFunction;
if (v8::Function::New(context, returnDataCallback, returnValue, 0,
v8::ConstructorBehavior::kThrow)
.ToLocal(&toStringFunction))
createDataProperty(context, func,
v8String(context->GetIsolate(), "toString"),
toStringFunction);
createDataProperty(context, object, funcName, func);
}
v8::Maybe<bool> ThreadDebugger::createDataPropertyInArray(
v8::Local<v8::Context> context,
v8::Local<v8::Array> array,
int index,
v8::Local<v8::Value> value) {
v8::TryCatch tryCatch(context->GetIsolate());
v8::Isolate::DisallowJavascriptExecutionScope throwJs(
context->GetIsolate(),
v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
return array->CreateDataProperty(context, index, value);
}
void ThreadDebugger::createFunctionProperty(v8::Local<v8::Context> context,
v8::Local<v8::Object> object,
const char* name,
v8::FunctionCallback callback,
const char* description) {
createFunctionPropertyWithData(context, object, name, callback,
v8::External::New(context->GetIsolate(), this),
description);
}
void ThreadDebugger::installAdditionalCommandLineAPI(
v8::Local<v8::Context> context,
v8::Local<v8::Object> object) {
createFunctionProperty(
context, object, "getEventListeners",
ThreadDebugger::getEventListenersCallback,
"function getEventListeners(node) { [Command Line API] }");
v8::Local<v8::Value> functionValue;
bool success =
V8ScriptRunner::compileAndRunInternalScript(
v8String(m_isolate, "(function(e) { console.log(e.type, e); })"),
m_isolate)
.ToLocal(&functionValue) &&
functionValue->IsFunction();
DCHECK(success);
createFunctionPropertyWithData(
context, object, "monitorEvents", ThreadDebugger::monitorEventsCallback,
functionValue,
"function monitorEvents(object, [types]) { [Command Line API] }");
createFunctionPropertyWithData(
context, object, "unmonitorEvents",
ThreadDebugger::unmonitorEventsCallback, functionValue,
"function unmonitorEvents(object, [types]) { [Command Line API] }");
}
static Vector<String> normalizeEventTypes(
const v8::FunctionCallbackInfo<v8::Value>& info) {
Vector<String> types;
if (info.Length() > 1 && info[1]->IsString())
types.push_back(toCoreString(info[1].As<v8::String>()));
if (info.Length() > 1 && info[1]->IsArray()) {
v8::Local<v8::Array> typesArray = v8::Local<v8::Array>::Cast(info[1]);
for (size_t i = 0; i < typesArray->Length(); ++i) {
v8::Local<v8::Value> typeValue;
if (!typesArray->Get(info.GetIsolate()->GetCurrentContext(), i)
.ToLocal(&typeValue) ||
!typeValue->IsString())
continue;
types.push_back(toCoreString(v8::Local<v8::String>::Cast(typeValue)));
}
}
if (info.Length() == 1)
types.appendVector(
Vector<String>({"mouse", "key", "touch",
"pointer", "control", "load",
"unload", "abort", "error",
"select", "input", "change",
"submit", "reset", "focus",
"blur", "resize", "scroll",
"search", "devicemotion", "deviceorientation"}));
Vector<String> outputTypes;
for (size_t i = 0; i < types.size(); ++i) {
if (types[i] == "mouse")
outputTypes.appendVector(
Vector<String>({"auxclick", "click", "dblclick", "mousedown",
"mouseeenter", "mouseleave", "mousemove", "mouseout",
"mouseover", "mouseup", "mouseleave", "mousewheel"}));
else if (types[i] == "key")
outputTypes.appendVector(
Vector<String>({"keydown", "keyup", "keypress", "textInput"}));
else if (types[i] == "touch")
outputTypes.appendVector(Vector<String>(
{"touchstart", "touchmove", "touchend", "touchcancel"}));
else if (types[i] == "pointer")
outputTypes.appendVector(Vector<String>(
{"pointerover", "pointerout", "pointerenter", "pointerleave",
"pointerdown", "pointerup", "pointermove", "pointercancel",
"gotpointercapture", "lostpointercapture"}));
else if (types[i] == "control")
outputTypes.appendVector(
Vector<String>({"resize", "scroll", "zoom", "focus", "blur", "select",
"input", "change", "submit", "reset"}));
else
outputTypes.push_back(types[i]);
}
return outputTypes;
}
static EventTarget* firstArgumentAsEventTarget(
const v8::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1)
return nullptr;
if (EventTarget* target =
V8EventTarget::toImplWithTypeCheck(info.GetIsolate(), info[0]))
return target;
return toDOMWindow(info.GetIsolate(), info[0]);
}
void ThreadDebugger::setMonitorEventsCallback(
const v8::FunctionCallbackInfo<v8::Value>& info,
bool enabled) {
EventTarget* eventTarget = firstArgumentAsEventTarget(info);
if (!eventTarget)
return;
Vector<String> types = normalizeEventTypes(info);
EventListener* eventListener = V8EventListenerHelper::getEventListener(
ScriptState::current(info.GetIsolate()),
v8::Local<v8::Function>::Cast(info.Data()), false,
enabled ? ListenerFindOrCreate : ListenerFindOnly);
if (!eventListener)
return;
for (size_t i = 0; i < types.size(); ++i) {
if (enabled)
eventTarget->addEventListener(AtomicString(types[i]), eventListener,
false);
else
eventTarget->removeEventListener(AtomicString(types[i]), eventListener,
false);
}
}
// static
void ThreadDebugger::monitorEventsCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
setMonitorEventsCallback(info, true);
}
// static
void ThreadDebugger::unmonitorEventsCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
setMonitorEventsCallback(info, false);
}
// static
void ThreadDebugger::getEventListenersCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1)
return;
ThreadDebugger* debugger = static_cast<ThreadDebugger*>(
v8::Local<v8::External>::Cast(info.Data())->Value());
DCHECK(debugger);
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
int groupId = debugger->contextGroupId(toExecutionContext(context));
V8EventListenerInfoList listenerInfo;
// eventListeners call can produce message on ErrorEvent during lazy event
// listener compilation.
if (groupId)
debugger->muteMetrics(groupId);
InspectorDOMDebuggerAgent::eventListenersInfoForTarget(isolate, info[0],
listenerInfo);
if (groupId)
debugger->unmuteMetrics(groupId);
v8::Local<v8::Object> result = v8::Object::New(isolate);
AtomicString currentEventType;
v8::Local<v8::Array> listeners;
size_t outputIndex = 0;
for (auto& info : listenerInfo) {
if (currentEventType != info.eventType) {
currentEventType = info.eventType;
listeners = v8::Array::New(isolate);
outputIndex = 0;
createDataProperty(context, result, v8String(isolate, currentEventType),
listeners);
}
v8::Local<v8::Object> listenerObject = v8::Object::New(isolate);
createDataProperty(context, listenerObject, v8String(isolate, "listener"),
info.handler);
createDataProperty(context, listenerObject, v8String(isolate, "useCapture"),
v8::Boolean::New(isolate, info.useCapture));
createDataProperty(context, listenerObject, v8String(isolate, "passive"),
v8::Boolean::New(isolate, info.passive));
createDataProperty(context, listenerObject, v8String(isolate, "once"),
v8::Boolean::New(isolate, info.once));
createDataProperty(context, listenerObject, v8String(isolate, "type"),
v8String(isolate, currentEventType));
v8::Local<v8::Function> removeFunction;
if (info.removeFunction.ToLocal(&removeFunction))
createDataProperty(context, listenerObject, v8String(isolate, "remove"),
removeFunction);
createDataPropertyInArray(context, listeners, outputIndex++,
listenerObject);
}
info.GetReturnValue().Set(result);
}
void ThreadDebugger::consoleTime(const v8_inspector::StringView& title) {
// TODO(dgozman): we can save on a copy here if trace macro would take a
// pointer with length.
TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console",
toCoreString(title).utf8().data(), this);
}
void ThreadDebugger::consoleTimeEnd(const v8_inspector::StringView& title) {
// TODO(dgozman): we can save on a copy here if trace macro would take a
// pointer with length.
TRACE_EVENT_COPY_ASYNC_END0("blink.console",
toCoreString(title).utf8().data(), this);
}
void ThreadDebugger::consoleTimeStamp(const v8_inspector::StringView& title) {
v8::Isolate* isolate = m_isolate;
// TODO(dgozman): we can save on a copy here if TracedValue would take a
// StringView.
TRACE_EVENT_INSTANT1(
"devtools.timeline", "TimeStamp", TRACE_EVENT_SCOPE_THREAD, "data",
InspectorTimeStampEvent::data(currentExecutionContext(isolate),
toCoreString(title)));
}
void ThreadDebugger::startRepeatingTimer(
double interval,
V8InspectorClient::TimerCallback callback,
void* data) {
m_timerData.push_back(data);
m_timerCallbacks.push_back(callback);
std::unique_ptr<Timer<ThreadDebugger>> timer = WTF::wrapUnique(
new Timer<ThreadDebugger>(this, &ThreadDebugger::onTimer));
Timer<ThreadDebugger>* timerPtr = timer.get();
m_timers.push_back(std::move(timer));
timerPtr->startRepeating(interval, BLINK_FROM_HERE);
}
void ThreadDebugger::cancelTimer(void* data) {
for (size_t index = 0; index < m_timerData.size(); ++index) {
if (m_timerData[index] == data) {
m_timers[index]->stop();
m_timerCallbacks.remove(index);
m_timers.remove(index);
m_timerData.remove(index);
return;
}
}
}
void ThreadDebugger::onTimer(TimerBase* timer) {
for (size_t index = 0; index < m_timers.size(); ++index) {
if (m_timers[index].get() == timer) {
m_timerCallbacks[index](m_timerData[index]);
return;
}
}
}
} // namespace blink
|