injected-script.cc 32.9 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
/*
 * Copyright (C) 2012 Google Inc. 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.
 */

31
#include "src/inspector/injected-script.h"
32

33 34
#include "src/inspector/injected-script-source.h"
#include "src/inspector/inspected-context.h"
35
#include "src/inspector/protocol/Protocol.h"
36 37 38 39 40 41 42 43
#include "src/inspector/remote-object-id.h"
#include "src/inspector/string-util.h"
#include "src/inspector/v8-console.h"
#include "src/inspector/v8-function-call.h"
#include "src/inspector/v8-injected-script-host.h"
#include "src/inspector/v8-inspector-impl.h"
#include "src/inspector/v8-inspector-session-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"
44
#include "src/inspector/v8-value-utils.h"
45 46

#include "include/v8-inspector.h"
47 48 49

namespace v8_inspector {

50 51
namespace {
static const char privateKeyName[] = "v8-inspector#injectedScript";
52
static const char kGlobalHandleLabel[] = "DevTools console";
53 54 55
static bool isResolvableNumberLike(String16 query) {
  return query == "Infinity" || query == "-Infinity" || query == "NaN";
}
56
}  // namespace
57

58 59 60 61 62 63
using protocol::Array;
using protocol::Runtime::PropertyDescriptor;
using protocol::Runtime::InternalPropertyDescriptor;
using protocol::Runtime::RemoteObject;
using protocol::Maybe;

64 65 66
class InjectedScript::ProtocolPromiseHandler {
 public:
  static bool add(V8InspectorSessionImpl* session,
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
                  v8::Local<v8::Context> context, v8::Local<v8::Value> value,
                  int executionContextId, const String16& objectGroup,
                  bool returnByValue, bool generatePreview,
                  EvaluateCallback* callback) {
    v8::Local<v8::Promise::Resolver> resolver;
    if (!v8::Promise::Resolver::New(context).ToLocal(&resolver)) {
      callback->sendFailure(Response::InternalError());
      return false;
    }
    if (!resolver->Resolve(context, value).FromMaybe(false)) {
      callback->sendFailure(Response::InternalError());
      return false;
    }

    v8::Local<v8::Promise> promise = resolver->GetPromise();
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
    V8InspectorImpl* inspector = session->inspector();
    ProtocolPromiseHandler* handler =
        new ProtocolPromiseHandler(session, executionContextId, objectGroup,
                                   returnByValue, generatePreview, callback);
    v8::Local<v8::Value> wrapper = handler->m_wrapper.Get(inspector->isolate());
    v8::Local<v8::Function> thenCallbackFunction =
        v8::Function::New(context, thenCallback, wrapper, 0,
                          v8::ConstructorBehavior::kThrow)
            .ToLocalChecked();
    if (promise->Then(context, thenCallbackFunction).IsEmpty()) {
      callback->sendFailure(Response::InternalError());
      return false;
    }
    v8::Local<v8::Function> catchCallbackFunction =
        v8::Function::New(context, catchCallback, wrapper, 0,
                          v8::ConstructorBehavior::kThrow)
            .ToLocalChecked();
    if (promise->Catch(context, catchCallbackFunction).IsEmpty()) {
      callback->sendFailure(Response::InternalError());
      return false;
    }
    return true;
  }

 private:
  static void thenCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    ProtocolPromiseHandler* handler = static_cast<ProtocolPromiseHandler*>(
        info.Data().As<v8::External>()->Value());
    DCHECK(handler);
    v8::Local<v8::Value> value =
        info.Length() > 0
            ? info[0]
            : v8::Local<v8::Value>::Cast(v8::Undefined(info.GetIsolate()));
    handler->thenCallback(value);
    delete handler;
  }

  static void catchCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
    ProtocolPromiseHandler* handler = static_cast<ProtocolPromiseHandler*>(
        info.Data().As<v8::External>()->Value());
    DCHECK(handler);
    v8::Local<v8::Value> value =
        info.Length() > 0
            ? info[0]
            : v8::Local<v8::Value>::Cast(v8::Undefined(info.GetIsolate()));
    handler->catchCallback(value);
    delete handler;
  }

  ProtocolPromiseHandler(V8InspectorSessionImpl* session,
                         int executionContextId, const String16& objectGroup,
                         bool returnByValue, bool generatePreview,
                         EvaluateCallback* callback)
      : m_inspector(session->inspector()),
        m_sessionId(session->sessionId()),
        m_contextGroupId(session->contextGroupId()),
        m_executionContextId(executionContextId),
        m_objectGroup(objectGroup),
        m_returnByValue(returnByValue),
        m_generatePreview(generatePreview),
        m_callback(std::move(callback)),
        m_wrapper(m_inspector->isolate(),
                  v8::External::New(m_inspector->isolate(), this)) {
    m_wrapper.SetWeak(this, cleanup, v8::WeakCallbackType::kParameter);
  }

  static void cleanup(
      const v8::WeakCallbackInfo<ProtocolPromiseHandler>& data) {
    if (!data.GetParameter()->m_wrapper.IsEmpty()) {
      data.GetParameter()->m_wrapper.Reset();
      data.SetSecondPassCallback(cleanup);
    } else {
154
      data.GetParameter()->sendPromiseCollected();
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
      delete data.GetParameter();
    }
  }

  void thenCallback(v8::Local<v8::Value> result) {
    V8InspectorSessionImpl* session =
        m_inspector->sessionById(m_contextGroupId, m_sessionId);
    if (!session) return;
    InjectedScript::ContextScope scope(session, m_executionContextId);
    Response response = scope.initialize();
    if (!response.isSuccess()) return;
    if (m_objectGroup == "console") {
      scope.injectedScript()->setLastEvaluationResult(result);
    }
    std::unique_ptr<EvaluateCallback> callback =
        scope.injectedScript()->takeEvaluateCallback(m_callback);
    if (!callback) return;
    std::unique_ptr<protocol::Runtime::RemoteObject> wrappedValue;
    response = scope.injectedScript()->wrapObject(
        result, m_objectGroup, m_returnByValue, m_generatePreview,
        &wrappedValue);
    if (!response.isSuccess()) {
      callback->sendFailure(response);
      return;
    }
    callback->sendSuccess(std::move(wrappedValue),
                          Maybe<protocol::Runtime::ExceptionDetails>());
  }

  void catchCallback(v8::Local<v8::Value> result) {
    V8InspectorSessionImpl* session =
        m_inspector->sessionById(m_contextGroupId, m_sessionId);
    if (!session) return;
    InjectedScript::ContextScope scope(session, m_executionContextId);
    Response response = scope.initialize();
    if (!response.isSuccess()) return;
    std::unique_ptr<EvaluateCallback> callback =
        scope.injectedScript()->takeEvaluateCallback(m_callback);
    if (!callback) return;
    std::unique_ptr<protocol::Runtime::RemoteObject> wrappedValue;
    response = scope.injectedScript()->wrapObject(
        result, m_objectGroup, m_returnByValue, m_generatePreview,
        &wrappedValue);
    if (!response.isSuccess()) {
      callback->sendFailure(response);
      return;
    }
    String16 message;
    std::unique_ptr<V8StackTraceImpl> stack;
    v8::Isolate* isolate = session->inspector()->isolate();
    if (result->IsNativeError()) {
      message = " " + toProtocolString(
                          result->ToDetailString(isolate->GetCurrentContext())
                              .ToLocalChecked());
      v8::Local<v8::StackTrace> stackTrace = v8::debug::GetDetailedStackTrace(
          isolate, v8::Local<v8::Object>::Cast(result));
      if (!stackTrace.IsEmpty()) {
        stack = m_inspector->debugger()->createStackTrace(stackTrace);
      }
    }
    if (!stack) {
      stack = m_inspector->debugger()->captureStackTrace(true);
    }
    std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails =
        protocol::Runtime::ExceptionDetails::create()
            .setExceptionId(m_inspector->nextExceptionId())
            .setText("Uncaught (in promise)" + message)
            .setLineNumber(stack && !stack->isEmpty() ? stack->topLineNumber()
                                                      : 0)
            .setColumnNumber(
                stack && !stack->isEmpty() ? stack->topColumnNumber() : 0)
            .setException(wrappedValue->clone())
            .build();
    if (stack)
229 230
      exceptionDetails->setStackTrace(
          stack->buildInspectorObjectImpl(m_inspector->debugger()));
231 232 233 234 235
    if (stack && !stack->isEmpty())
      exceptionDetails->setScriptId(toString16(stack->topScriptId()));
    callback->sendSuccess(std::move(wrappedValue), std::move(exceptionDetails));
  }

236 237 238 239 240 241 242 243 244 245 246 247 248
  void sendPromiseCollected() {
    V8InspectorSessionImpl* session =
        m_inspector->sessionById(m_contextGroupId, m_sessionId);
    if (!session) return;
    InjectedScript::ContextScope scope(session, m_executionContextId);
    Response response = scope.initialize();
    if (!response.isSuccess()) return;
    std::unique_ptr<EvaluateCallback> callback =
        scope.injectedScript()->takeEvaluateCallback(m_callback);
    if (!callback) return;
    callback->sendFailure(Response::Error("Promise was collected"));
  }

249 250 251 252 253 254 255 256 257 258 259
  V8InspectorImpl* m_inspector;
  int m_sessionId;
  int m_contextGroupId;
  int m_executionContextId;
  String16 m_objectGroup;
  bool m_returnByValue;
  bool m_generatePreview;
  EvaluateCallback* m_callback;
  v8::Global<v8::External> m_wrapper;
};

260
std::unique_ptr<InjectedScript> InjectedScript::create(
261
    InspectedContext* inspectedContext, int sessionId) {
262 263
  v8::Isolate* isolate = inspectedContext->isolate();
  v8::HandleScope handles(isolate);
264
  v8::TryCatch tryCatch(isolate);
265 266
  v8::Local<v8::Context> context = inspectedContext->context();
  v8::Context::Scope scope(context);
267 268
  v8::MicrotasksScope microtasksScope(isolate,
                                      v8::MicrotasksScope::kDoNotRunMicrotasks);
269 270 271 272 273 274 275 276 277 278 279

  // Inject javascript into the context. The compiled script is supposed to
  // evaluate into
  // a single anonymous function(it's anonymous to avoid cluttering the global
  // object with
  // inspector's stuff) the function is called a few lines below with
  // InjectedScriptHost wrapper,
  // injected script id and explicit reference to the inspected global object.
  // The function is expected
  // to create and configure InjectedScript instance that is going to be used by
  // the inspector.
280 281
  StringView injectedScriptSource(
      reinterpret_cast<const uint8_t*>(InjectedScriptSource_js),
282 283 284 285 286
      sizeof(InjectedScriptSource_js));
  v8::Local<v8::Value> value;
  if (!inspectedContext->inspector()
           ->compileAndRunInternalScript(
               context, toV8String(isolate, injectedScriptSource))
287
           .ToLocal(&value)) {
288
    return nullptr;
289
  }
290
  DCHECK(value->IsFunction());
291 292
  v8::Local<v8::Object> scriptHostWrapper =
      V8InjectedScriptHost::create(context, inspectedContext->inspector());
293 294 295 296 297
  v8::Local<v8::Function> function = v8::Local<v8::Function>::Cast(value);
  v8::Local<v8::Object> windowGlobal = context->Global();
  v8::Local<v8::Value> info[] = {
      scriptHostWrapper, windowGlobal,
      v8::Number::New(isolate, inspectedContext->contextId())};
298 299 300 301

  int contextGroupId = inspectedContext->contextGroupId();
  int contextId = inspectedContext->contextId();
  V8InspectorImpl* inspector = inspectedContext->inspector();
302
  v8::Local<v8::Value> injectedScriptValue;
303
  if (!function->Call(context, windowGlobal, arraysize(info), info)
304 305
           .ToLocal(&injectedScriptValue))
    return nullptr;
306 307
  if (inspector->getContext(contextGroupId, contextId) != inspectedContext)
    return nullptr;
308
  if (!injectedScriptValue->IsObject()) return nullptr;
309 310

  std::unique_ptr<InjectedScript> injectedScript(new InjectedScript(
311
      inspectedContext, injectedScriptValue.As<v8::Object>(), sessionId));
312 313 314 315 316 317 318
  v8::Local<v8::Private> privateKey = v8::Private::ForApi(
      isolate, v8::String::NewFromUtf8(isolate, privateKeyName,
                                       v8::NewStringType::kInternalized)
                   .ToLocalChecked());
  scriptHostWrapper->SetPrivate(
      context, privateKey, v8::External::New(isolate, injectedScript.get()));
  return injectedScript;
319 320
}

321
InjectedScript::InjectedScript(InspectedContext* context,
322 323 324 325
                               v8::Local<v8::Object> object, int sessionId)
    : m_context(context),
      m_value(context->isolate(), object),
      m_sessionId(sessionId) {}
326

327
InjectedScript::~InjectedScript() { discardEvaluateCallbacks(); }
328

329 330 331
Response InjectedScript::getProperties(
    v8::Local<v8::Object> object, const String16& groupName, bool ownProperties,
    bool accessorPropertiesOnly, bool generatePreview,
332 333 334
    std::unique_ptr<Array<PropertyDescriptor>>* properties,
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
  v8::HandleScope handles(m_context->isolate());
335
  v8::Local<v8::Context> context = m_context->context();
336 337 338 339 340 341 342 343 344 345 346
  V8FunctionCall function(m_context->inspector(), m_context->context(),
                          v8Value(), "getProperties");
  function.appendArgument(object);
  function.appendArgument(groupName);
  function.appendArgument(ownProperties);
  function.appendArgument(accessorPropertiesOnly);
  function.appendArgument(generatePreview);

  v8::TryCatch tryCatch(m_context->isolate());
  v8::Local<v8::Value> resultValue = function.callWithoutExceptionHandling();
  if (tryCatch.HasCaught()) {
347 348 349
    Response response = createExceptionDetails(
        tryCatch, groupName, generatePreview, exceptionDetails);
    if (!response.isSuccess()) return response;
350 351
    // FIXME: make properties optional
    *properties = Array<PropertyDescriptor>::create();
352
    return Response::OK();
353
  }
354 355 356 357 358
  if (resultValue.IsEmpty()) return Response::InternalError();
  std::unique_ptr<protocol::Value> protocolValue;
  Response response = toProtocolValue(context, resultValue, &protocolValue);
  if (!response.isSuccess()) return response;
  protocol::ErrorSupport errors;
359
  std::unique_ptr<Array<PropertyDescriptor>> result =
360
      Array<PropertyDescriptor>::fromValue(protocolValue.get(), &errors);
361 362 363
  if (errors.hasErrors()) return Response::Error(errors.errors());
  *properties = std::move(result);
  return Response::OK();
364 365 366 367
}

void InjectedScript::releaseObject(const String16& objectId) {
  std::unique_ptr<protocol::Value> parsedObjectId =
368
      protocol::StringUtil::parseJSON(objectId);
369 370 371 372 373 374
  if (!parsedObjectId) return;
  protocol::DictionaryValue* object =
      protocol::DictionaryValue::cast(parsedObjectId.get());
  if (!object) return;
  int boundId = 0;
  if (!object->getInteger("id", &boundId)) return;
375
  unbindObject(boundId);
376 377
}

378 379 380 381
Response InjectedScript::wrapObject(
    v8::Local<v8::Value> value, const String16& groupName, bool forceValueType,
    bool generatePreview,
    std::unique_ptr<protocol::Runtime::RemoteObject>* result) const {
382 383
  v8::HandleScope handles(m_context->isolate());
  v8::Local<v8::Value> wrappedObject;
384
  v8::Local<v8::Context> context = m_context->context();
385 386 387
  Response response = wrapValue(value, groupName, forceValueType,
                                generatePreview, &wrappedObject);
  if (!response.isSuccess()) return response;
388
  protocol::ErrorSupport errors;
389 390 391 392 393
  std::unique_ptr<protocol::Value> protocolValue;
  response = toProtocolValue(context, wrappedObject, &protocolValue);
  if (!response.isSuccess()) return response;

  *result =
394
      protocol::Runtime::RemoteObject::fromValue(protocolValue.get(), &errors);
395 396
  if (!result->get()) return Response::Error(errors.errors());
  return Response::OK();
397 398
}

399 400 401 402
Response InjectedScript::wrapValue(v8::Local<v8::Value> value,
                                   const String16& groupName,
                                   bool forceValueType, bool generatePreview,
                                   v8::Local<v8::Value>* result) const {
403 404 405 406 407 408 409
  V8FunctionCall function(m_context->inspector(), m_context->context(),
                          v8Value(), "wrapObject");
  function.appendArgument(value);
  function.appendArgument(groupName);
  function.appendArgument(forceValueType);
  function.appendArgument(generatePreview);
  bool hadException = false;
410 411 412
  *result = function.call(hadException);
  if (hadException || result->IsEmpty()) return Response::InternalError();
  return Response::OK();
413 414 415 416 417
}

std::unique_ptr<protocol::Runtime::RemoteObject> InjectedScript::wrapTable(
    v8::Local<v8::Value> table, v8::Local<v8::Value> columns) const {
  v8::HandleScope handles(m_context->isolate());
418 419 420
  v8::Local<v8::Context> context = m_context->context();
  V8FunctionCall function(m_context->inspector(), context, v8Value(),
                          "wrapTable");
421 422 423 424 425 426 427
  function.appendArgument(table);
  if (columns.IsEmpty())
    function.appendArgument(false);
  else
    function.appendArgument(columns);
  bool hadException = false;
  v8::Local<v8::Value> r = function.call(hadException);
428
  if (hadException || r.IsEmpty()) return nullptr;
429 430 431
  std::unique_ptr<protocol::Value> protocolValue;
  Response response = toProtocolValue(context, r, &protocolValue);
  if (!response.isSuccess()) return nullptr;
432
  protocol::ErrorSupport errors;
433 434
  return protocol::Runtime::RemoteObject::fromValue(protocolValue.get(),
                                                    &errors);
435 436
}

437 438
void InjectedScript::addPromiseCallback(
    V8InspectorSessionImpl* session, v8::MaybeLocal<v8::Value> value,
439
    const String16& objectGroup, bool returnByValue, bool generatePreview,
440 441 442 443 444 445 446
    std::unique_ptr<EvaluateCallback> callback) {
  if (value.IsEmpty()) {
    callback->sendFailure(Response::InternalError());
    return;
  }
  v8::MicrotasksScope microtasksScope(m_context->isolate(),
                                      v8::MicrotasksScope::kRunMicrotasks);
447 448 449 450
  if (ProtocolPromiseHandler::add(
          session, m_context->context(), value.ToLocalChecked(),
          m_context->contextId(), objectGroup, returnByValue, generatePreview,
          callback.get())) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    m_evaluateCallbacks.insert(callback.release());
  }
}

void InjectedScript::discardEvaluateCallbacks() {
  for (auto& callback : m_evaluateCallbacks) {
    callback->sendFailure(Response::Error("Execution context was destroyed."));
    delete callback;
  }
  m_evaluateCallbacks.clear();
}

std::unique_ptr<EvaluateCallback> InjectedScript::takeEvaluateCallback(
    EvaluateCallback* callback) {
  auto it = m_evaluateCallbacks.find(callback);
  if (it == m_evaluateCallbacks.end()) return nullptr;
  std::unique_ptr<EvaluateCallback> value(*it);
  m_evaluateCallbacks.erase(it);
  return value;
}

472 473
Response InjectedScript::findObject(const RemoteObjectId& objectId,
                                    v8::Local<v8::Value>* outObject) const {
474 475
  auto it = m_idToWrappedObject.find(objectId.id());
  if (it == m_idToWrappedObject.end())
476
    return Response::Error("Could not find object with given id");
477
  *outObject = it->second.Get(m_context->isolate());
478
  return Response::OK();
479 480 481
}

String16 InjectedScript::objectGroupName(const RemoteObjectId& objectId) const {
482 483 484
  if (objectId.id() <= 0) return String16();
  auto it = m_idToObjectGroupName.find(objectId.id());
  return it != m_idToObjectGroupName.end() ? it->second : String16();
485 486 487 488
}

void InjectedScript::releaseObjectGroup(const String16& objectGroup) {
  if (objectGroup == "console") m_lastEvaluationResult.Reset();
489 490 491 492 493
  if (objectGroup.isEmpty()) return;
  auto it = m_nameToObjectGroup.find(objectGroup);
  if (it == m_nameToObjectGroup.end()) return;
  for (int id : it->second) unbindObject(id);
  m_nameToObjectGroup.erase(it);
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
}

void InjectedScript::setCustomObjectFormatterEnabled(bool enabled) {
  v8::HandleScope handles(m_context->isolate());
  V8FunctionCall function(m_context->inspector(), m_context->context(),
                          v8Value(), "setCustomObjectFormatterEnabled");
  function.appendArgument(enabled);
  bool hadException = false;
  function.call(hadException);
  DCHECK(!hadException);
}

v8::Local<v8::Value> InjectedScript::v8Value() const {
  return m_value.Get(m_context->isolate());
}

v8::Local<v8::Value> InjectedScript::lastEvaluationResult() const {
  if (m_lastEvaluationResult.IsEmpty())
    return v8::Undefined(m_context->isolate());
  return m_lastEvaluationResult.Get(m_context->isolate());
}

516 517
void InjectedScript::setLastEvaluationResult(v8::Local<v8::Value> result) {
  m_lastEvaluationResult.Reset(m_context->isolate(), result);
518
  m_lastEvaluationResult.AnnotateStrongRetainer(kGlobalHandleLabel);
519 520
}

521 522 523
Response InjectedScript::resolveCallArgument(
    protocol::Runtime::CallArgument* callArgument,
    v8::Local<v8::Value>* result) {
524
  if (callArgument->hasObjectId()) {
525 526 527 528 529 530
    std::unique_ptr<RemoteObjectId> remoteObjectId;
    Response response =
        RemoteObjectId::parse(callArgument->getObjectId(""), &remoteObjectId);
    if (!response.isSuccess()) return response;
    if (remoteObjectId->contextId() != m_context->contextId())
      return Response::Error(
531
          "Argument should belong to the same JavaScript world as target "
532 533
          "object");
    return findObject(*remoteObjectId, result);
534 535
  }
  if (callArgument->hasValue() || callArgument->hasUnserializableValue()) {
536 537 538 539 540 541 542 543 544 545 546
    String16 value;
    if (callArgument->hasValue()) {
      value = "(" + callArgument->getValue(nullptr)->serialize() + ")";
    } else {
      String16 unserializableValue = callArgument->getUnserializableValue("");
      // Protect against potential identifier resolution for NaN and Infinity.
      if (isResolvableNumberLike(unserializableValue))
        value = "Number(\"" + unserializableValue + "\")";
      else
        value = unserializableValue;
    }
547 548 549
    if (!m_context->inspector()
             ->compileAndRunInternalScript(
                 m_context->context(), toV8String(m_context->isolate(), value))
550 551
             .ToLocal(result)) {
      return Response::Error("Couldn't parse value object in call argument");
552
    }
553
    return Response::OK();
554
  }
555 556
  *result = v8::Undefined(m_context->isolate());
  return Response::OK();
557 558
}

559 560 561 562
Response InjectedScript::createExceptionDetails(
    const v8::TryCatch& tryCatch, const String16& objectGroup,
    bool generatePreview, Maybe<protocol::Runtime::ExceptionDetails>* result) {
  if (!tryCatch.HasCaught()) return Response::InternalError();
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  v8::Local<v8::Message> message = tryCatch.Message();
  v8::Local<v8::Value> exception = tryCatch.Exception();
  String16 messageText =
      message.IsEmpty() ? String16() : toProtocolString(message->Get());
  std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails =
      protocol::Runtime::ExceptionDetails::create()
          .setExceptionId(m_context->inspector()->nextExceptionId())
          .setText(exception.IsEmpty() ? messageText : String16("Uncaught"))
          .setLineNumber(
              message.IsEmpty()
                  ? 0
                  : message->GetLineNumber(m_context->context()).FromMaybe(1) -
                        1)
          .setColumnNumber(
              message.IsEmpty()
                  ? 0
                  : message->GetStartColumn(m_context->context()).FromMaybe(0))
          .build();
  if (!message.IsEmpty()) {
582 583
    exceptionDetails->setScriptId(String16::fromInteger(
        static_cast<int>(message->GetScriptOrigin().ScriptID()->Value())));
584 585
    v8::Local<v8::StackTrace> stackTrace = message->GetStackTrace();
    if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
586 587 588 589 590
      exceptionDetails->setStackTrace(
          m_context->inspector()
              ->debugger()
              ->createStackTrace(stackTrace)
              ->buildInspectorObjectImpl(m_context->inspector()->debugger()));
591 592
  }
  if (!exception.IsEmpty()) {
593 594 595 596 597
    std::unique_ptr<protocol::Runtime::RemoteObject> wrapped;
    Response response =
        wrapObject(exception, objectGroup, false /* forceValueType */,
                   generatePreview && !exception->IsNativeError(), &wrapped);
    if (!response.isSuccess()) return response;
598 599
    exceptionDetails->setException(std::move(wrapped));
  }
600 601
  *result = std::move(exceptionDetails);
  return Response::OK();
602 603
}

604 605 606
Response InjectedScript::wrapEvaluateResult(
    v8::MaybeLocal<v8::Value> maybeResultValue, const v8::TryCatch& tryCatch,
    const String16& objectGroup, bool returnByValue, bool generatePreview,
607 608 609 610
    std::unique_ptr<protocol::Runtime::RemoteObject>* result,
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
  v8::Local<v8::Value> resultValue;
  if (!tryCatch.HasCaught()) {
611 612 613 614 615
    if (!maybeResultValue.ToLocal(&resultValue))
      return Response::InternalError();
    Response response = wrapObject(resultValue, objectGroup, returnByValue,
                                   generatePreview, result);
    if (!response.isSuccess()) return response;
616
    if (objectGroup == "console") {
617
      m_lastEvaluationResult.Reset(m_context->isolate(), resultValue);
618 619
      m_lastEvaluationResult.AnnotateStrongRetainer(kGlobalHandleLabel);
    }
620
  } else {
621 622 623
    if (tryCatch.HasTerminated() || !tryCatch.CanContinue()) {
      return Response::Error("Execution was terminated");
    }
624
    v8::Local<v8::Value> exception = tryCatch.Exception();
625 626 627 628
    Response response =
        wrapObject(exception, objectGroup, false,
                   generatePreview && !exception->IsNativeError(), result);
    if (!response.isSuccess()) return response;
629 630
    // We send exception in result for compatibility reasons, even though it's
    // accessible through exceptionDetails.exception.
631 632 633
    response = createExceptionDetails(tryCatch, objectGroup, generatePreview,
                                      exceptionDetails);
    if (!response.isSuccess()) return response;
634
  }
635
  return Response::OK();
636 637 638
}

v8::Local<v8::Object> InjectedScript::commandLineAPI() {
639 640 641 642
  if (m_commandLineAPI.IsEmpty()) {
    m_commandLineAPI.Reset(
        m_context->isolate(),
        m_context->inspector()->console()->createCommandLineAPI(
643
            m_context->context(), m_sessionId));
644
    m_commandLineAPI.AnnotateStrongRetainer(kGlobalHandleLabel);
645
  }
646 647 648
  return m_commandLineAPI.Get(m_context->isolate());
}

649 650
InjectedScript::Scope::Scope(V8InspectorSessionImpl* session)
    : m_inspector(session->inspector()),
651
      m_injectedScript(nullptr),
652 653
      m_handleScope(m_inspector->isolate()),
      m_tryCatch(m_inspector->isolate()),
654
      m_ignoreExceptionsAndMuteConsole(false),
655
      m_previousPauseOnExceptionsState(v8::debug::NoBreakOnException),
656
      m_userGesture(false),
657
      m_allowEval(false),
658 659
      m_contextGroupId(session->contextGroupId()),
      m_sessionId(session->sessionId()) {}
660

661
Response InjectedScript::Scope::initialize() {
662
  cleanup();
663 664
  V8InspectorSessionImpl* session =
      m_inspector->sessionById(m_contextGroupId, m_sessionId);
665 666 667
  if (!session) return Response::InternalError();
  Response response = findInjectedScript(session);
  if (!response.isSuccess()) return response;
668 669
  m_context = m_injectedScript->context()->context();
  m_context->Enter();
670
  if (m_allowEval) m_context->AllowCodeGenerationFromStrings(true);
671
  return Response::OK();
672 673
}

674
void InjectedScript::Scope::installCommandLineAPI() {
675 676 677 678 679 680 681 682 683 684 685 686
  DCHECK(m_injectedScript && !m_context.IsEmpty() &&
         !m_commandLineAPIScope.get());
  m_commandLineAPIScope.reset(new V8Console::CommandLineAPIScope(
      m_context, m_injectedScript->commandLineAPI(), m_context->Global()));
}

void InjectedScript::Scope::ignoreExceptionsAndMuteConsole() {
  DCHECK(!m_ignoreExceptionsAndMuteConsole);
  m_ignoreExceptionsAndMuteConsole = true;
  m_inspector->client()->muteMetrics(m_contextGroupId);
  m_inspector->muteExceptions(m_contextGroupId);
  m_previousPauseOnExceptionsState =
687
      setPauseOnExceptionsState(v8::debug::NoBreakOnException);
688 689
}

690 691
v8::debug::ExceptionBreakState InjectedScript::Scope::setPauseOnExceptionsState(
    v8::debug::ExceptionBreakState newState) {
692
  if (!m_inspector->debugger()->enabled()) return newState;
693
  v8::debug::ExceptionBreakState presentState =
694 695 696 697 698 699 700 701 702 703 704 705
      m_inspector->debugger()->getPauseOnExceptionsState();
  if (presentState != newState)
    m_inspector->debugger()->setPauseOnExceptionsState(newState);
  return presentState;
}

void InjectedScript::Scope::pretendUserGesture() {
  DCHECK(!m_userGesture);
  m_userGesture = true;
  m_inspector->client()->beginUserGesture();
}

706 707 708 709 710 711 712
void InjectedScript::Scope::allowCodeGenerationFromStrings() {
  DCHECK(!m_allowEval);
  if (m_context->IsCodeGenerationFromStringsAllowed()) return;
  m_allowEval = true;
  m_context->AllowCodeGenerationFromStrings(true);
}

713 714 715
void InjectedScript::Scope::cleanup() {
  m_commandLineAPIScope.reset();
  if (!m_context.IsEmpty()) {
716
    if (m_allowEval) m_context->AllowCodeGenerationFromStrings(false);
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    m_context->Exit();
    m_context.Clear();
  }
}

InjectedScript::Scope::~Scope() {
  if (m_ignoreExceptionsAndMuteConsole) {
    setPauseOnExceptionsState(m_previousPauseOnExceptionsState);
    m_inspector->client()->unmuteMetrics(m_contextGroupId);
    m_inspector->unmuteExceptions(m_contextGroupId);
  }
  if (m_userGesture) m_inspector->client()->endUserGesture();
  cleanup();
}

732
InjectedScript::ContextScope::ContextScope(V8InspectorSessionImpl* session,
733
                                           int executionContextId)
734
    : InjectedScript::Scope(session),
735 736 737 738
      m_executionContextId(executionContextId) {}

InjectedScript::ContextScope::~ContextScope() {}

739
Response InjectedScript::ContextScope::findInjectedScript(
740
    V8InspectorSessionImpl* session) {
741
  return session->findInjectedScript(m_executionContextId, m_injectedScript);
742 743
}

744
InjectedScript::ObjectScope::ObjectScope(V8InspectorSessionImpl* session,
745
                                         const String16& remoteObjectId)
746
    : InjectedScript::Scope(session), m_remoteObjectId(remoteObjectId) {}
747 748 749

InjectedScript::ObjectScope::~ObjectScope() {}

750
Response InjectedScript::ObjectScope::findInjectedScript(
751
    V8InspectorSessionImpl* session) {
752 753 754 755 756 757
  std::unique_ptr<RemoteObjectId> remoteId;
  Response response = RemoteObjectId::parse(m_remoteObjectId, &remoteId);
  if (!response.isSuccess()) return response;
  InjectedScript* injectedScript = nullptr;
  response = session->findInjectedScript(remoteId.get(), injectedScript);
  if (!response.isSuccess()) return response;
758
  m_objectGroupName = injectedScript->objectGroupName(*remoteId);
759 760
  response = injectedScript->findObject(*remoteId, &m_object);
  if (!response.isSuccess()) return response;
761
  m_injectedScript = injectedScript;
762
  return Response::OK();
763 764
}

765
InjectedScript::CallFrameScope::CallFrameScope(V8InspectorSessionImpl* session,
766
                                               const String16& remoteObjectId)
767
    : InjectedScript::Scope(session), m_remoteCallFrameId(remoteObjectId) {}
768 769 770

InjectedScript::CallFrameScope::~CallFrameScope() {}

771
Response InjectedScript::CallFrameScope::findInjectedScript(
772
    V8InspectorSessionImpl* session) {
773 774 775
  std::unique_ptr<RemoteCallFrameId> remoteId;
  Response response = RemoteCallFrameId::parse(m_remoteCallFrameId, &remoteId);
  if (!response.isSuccess()) return response;
776
  m_frameOrdinal = static_cast<size_t>(remoteId->frameOrdinal());
777
  return session->findInjectedScript(remoteId.get(), m_injectedScript);
778 779
}

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
InjectedScript* InjectedScript::fromInjectedScriptHost(
    v8::Isolate* isolate, v8::Local<v8::Object> injectedScriptObject) {
  v8::HandleScope handleScope(isolate);
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  v8::Local<v8::Private> privateKey = v8::Private::ForApi(
      isolate, v8::String::NewFromUtf8(isolate, privateKeyName,
                                       v8::NewStringType::kInternalized)
                   .ToLocalChecked());
  v8::Local<v8::Value> value =
      injectedScriptObject->GetPrivate(context, privateKey).ToLocalChecked();
  DCHECK(value->IsExternal());
  v8::Local<v8::External> external = value.As<v8::External>();
  return static_cast<InjectedScript*>(external->Value());
}

int InjectedScript::bindObject(v8::Local<v8::Value> value,
                               const String16& groupName) {
  if (m_lastBoundObjectId <= 0) m_lastBoundObjectId = 1;
  int id = m_lastBoundObjectId++;
  m_idToWrappedObject[id].Reset(m_context->isolate(), value);
800
  m_idToWrappedObject[id].AnnotateStrongRetainer(kGlobalHandleLabel);
801 802 803 804 805 806 807 808 809 810 811 812 813

  if (!groupName.isEmpty() && id > 0) {
    m_idToObjectGroupName[id] = groupName;
    m_nameToObjectGroup[groupName].push_back(id);
  }
  return id;
}

void InjectedScript::unbindObject(int id) {
  m_idToWrappedObject.erase(id);
  m_idToObjectGroupName.erase(id);
}

814
}  // namespace v8_inspector