v8-runtime-agent-impl.cc 36.2 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) 2011 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/v8-runtime-agent-impl.h"
32

33 34
#include <inttypes.h>

35
#include "../../third_party/inspector_protocol/crdtp/json.h"
36
#include "src/debug/debug-interface.h"
37 38
#include "src/inspector/injected-script.h"
#include "src/inspector/inspected-context.h"
39
#include "src/inspector/protocol/Protocol.h"
40 41 42 43 44 45 46
#include "src/inspector/remote-object-id.h"
#include "src/inspector/v8-console-message.h"
#include "src/inspector/v8-debugger-agent-impl.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"
47
#include "src/inspector/v8-value-utils.h"
48
#include "src/tracing/trace-event.h"
49 50

#include "include/v8-inspector.h"
51 52 53 54 55 56 57

namespace v8_inspector {

namespace V8RuntimeAgentImplState {
static const char customObjectFormatterEnabled[] =
    "customObjectFormatterEnabled";
static const char runtimeEnabled[] = "runtimeEnabled";
58
static const char bindings[] = "bindings";
59
static const char globalBindingsKey[] = "";
60
}  // namespace V8RuntimeAgentImplState
61 62 63 64 65

using protocol::Runtime::RemoteObject;

namespace {

66 67
template <typename ProtocolCallback>
class EvaluateCallbackWrapper : public EvaluateCallback {
68
 public:
69 70 71 72
  static std::unique_ptr<EvaluateCallback> wrap(
      std::unique_ptr<ProtocolCallback> callback) {
    return std::unique_ptr<EvaluateCallback>(
        new EvaluateCallbackWrapper(std::move(callback)));
73
  }
74 75 76 77 78
  void sendSuccess(std::unique_ptr<protocol::Runtime::RemoteObject> result,
                   protocol::Maybe<protocol::Runtime::ExceptionDetails>
                       exceptionDetails) override {
    return m_callback->sendSuccess(std::move(result),
                                   std::move(exceptionDetails));
79
  }
80 81
  void sendFailure(const protocol::DispatchResponse& response) override {
    return m_callback->sendFailure(response);
82 83
  }

84 85 86
 private:
  explicit EvaluateCallbackWrapper(std::unique_ptr<ProtocolCallback> callback)
      : m_callback(std::move(callback)) {}
87

88
  std::unique_ptr<ProtocolCallback> m_callback;
89 90
};

91
template <typename ProtocolCallback>
92 93 94
bool wrapEvaluateResultAsync(InjectedScript* injectedScript,
                             v8::MaybeLocal<v8::Value> maybeResultValue,
                             const v8::TryCatch& tryCatch,
95 96
                             const String16& objectGroup, WrapMode wrapMode,
                             ProtocolCallback* callback) {
97 98 99
  std::unique_ptr<RemoteObject> result;
  Maybe<protocol::Runtime::ExceptionDetails> exceptionDetails;

100
  Response response = injectedScript->wrapEvaluateResult(
101 102
      maybeResultValue, tryCatch, objectGroup, wrapMode, &result,
      &exceptionDetails);
103
  if (response.IsSuccess()) {
104
    callback->sendSuccess(std::move(result), std::move(exceptionDetails));
105 106
    return true;
  }
107
  callback->sendFailure(response);
108 109 110
  return false;
}

111
void innerCallFunctionOn(
112 113
    V8InspectorSessionImpl* session,
    InjectedScript::Scope& scope,  // NOLINT(runtime/references)
114 115
    v8::Local<v8::Value> recv, const String16& expression,
    Maybe<protocol::Array<protocol::Runtime::CallArgument>> optionalArguments,
116 117
    bool silent, WrapMode wrapMode, bool userGesture, bool awaitPromise,
    const String16& objectGroup,
118 119 120 121 122 123 124 125
    std::unique_ptr<V8RuntimeAgentImpl::CallFunctionOnCallback> callback) {
  V8InspectorImpl* inspector = session->inspector();

  std::unique_ptr<v8::Local<v8::Value>[]> argv = nullptr;
  int argc = 0;
  if (optionalArguments.isJust()) {
    protocol::Array<protocol::Runtime::CallArgument>* arguments =
        optionalArguments.fromJust();
126
    argc = static_cast<int>(arguments->size());
127 128 129 130
    argv.reset(new v8::Local<v8::Value>[argc]);
    for (int i = 0; i < argc; ++i) {
      v8::Local<v8::Value> argumentValue;
      Response response = scope.injectedScript()->resolveCallArgument(
131
          (*arguments)[i].get(), &argumentValue);
132
      if (!response.IsSuccess()) {
133 134 135 136 137 138 139 140 141 142
        callback->sendFailure(response);
        return;
      }
      argv[i] = argumentValue;
    }
  }

  if (silent) scope.ignoreExceptionsAndMuteConsole();
  if (userGesture) scope.pretendUserGesture();

143 144 145
  // Temporarily enable allow evals for inspector.
  scope.allowCodeGenerationFromStrings();

146 147 148 149 150 151 152 153 154 155 156 157
  v8::MaybeLocal<v8::Value> maybeFunctionValue;
  v8::Local<v8::Script> functionScript;
  if (inspector
          ->compileScript(scope.context(), "(" + expression + ")", String16())
          .ToLocal(&functionScript)) {
    v8::MicrotasksScope microtasksScope(inspector->isolate(),
                                        v8::MicrotasksScope::kRunMicrotasks);
    maybeFunctionValue = functionScript->Run(scope.context());
  }
  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
  Response response = scope.initialize();
158
  if (!response.IsSuccess()) {
159 160 161 162 163 164
    callback->sendFailure(response);
    return;
  }

  if (scope.tryCatch().HasCaught()) {
    wrapEvaluateResultAsync(scope.injectedScript(), maybeFunctionValue,
165
                            scope.tryCatch(), objectGroup, WrapMode::kNoPreview,
166 167 168 169 170 171 172
                            callback.get());
    return;
  }

  v8::Local<v8::Value> functionValue;
  if (!maybeFunctionValue.ToLocal(&functionValue) ||
      !functionValue->IsFunction()) {
173 174
    callback->sendFailure(Response::ServerError(
        "Given expression does not evaluate to a function"));
175 176 177 178 179 180 181 182 183 184 185 186 187
    return;
  }

  v8::MaybeLocal<v8::Value> maybeResultValue;
  {
    v8::MicrotasksScope microtasksScope(inspector->isolate(),
                                        v8::MicrotasksScope::kRunMicrotasks);
    maybeResultValue = functionValue.As<v8::Function>()->Call(
        scope.context(), recv, argc, argv.get());
  }
  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
  response = scope.initialize();
188
  if (!response.IsSuccess()) {
189 190 191 192 193 194
    callback->sendFailure(response);
    return;
  }

  if (!awaitPromise || scope.tryCatch().HasCaught()) {
    wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue,
195 196
                            scope.tryCatch(), objectGroup, wrapMode,
                            callback.get());
197 198 199 200
    return;
  }

  scope.injectedScript()->addPromiseCallback(
201
      session, maybeResultValue, objectGroup, wrapMode, false /* replMode */,
202 203 204 205
      EvaluateCallbackWrapper<V8RuntimeAgentImpl::CallFunctionOnCallback>::wrap(
          std::move(callback)));
}

206
Response ensureContext(V8InspectorImpl* inspector, int contextGroupId,
207 208
                       Maybe<int> executionContextId,
                       Maybe<String16> uniqueContextId, int* contextId) {
209
  if (executionContextId.isJust()) {
210 211 212 213
    if (uniqueContextId.isJust()) {
      return Response::InvalidParams(
          "contextId and uniqueContextId are mutually exclusive");
    }
214
    *contextId = executionContextId.fromJust();
215 216 217 218 219 220 221
  } else if (uniqueContextId.isJust()) {
    V8DebuggerId uniqueId(uniqueContextId.fromJust());
    if (!uniqueId.isValid())
      return Response::InvalidParams("invalid uniqueContextId");
    int id = inspector->resolveUniqueContextId(uniqueId);
    if (!id) return Response::InvalidParams("uniqueContextId not found");
    *contextId = id;
222 223 224 225
  } else {
    v8::HandleScope handles(inspector->isolate());
    v8::Local<v8::Context> defaultContext =
        inspector->client()->ensureDefaultContextInGroup(contextGroupId);
226
    if (defaultContext.IsEmpty())
227
      return Response::ServerError("Cannot find default execution context");
228
    *contextId = InspectedContext::contextId(defaultContext);
229
  }
230

231
  return Response::Success();
232 233 234 235 236 237 238 239 240 241 242 243 244
}

}  // namespace

V8RuntimeAgentImpl::V8RuntimeAgentImpl(
    V8InspectorSessionImpl* session, protocol::FrontendChannel* FrontendChannel,
    protocol::DictionaryValue* state)
    : m_session(session),
      m_state(state),
      m_frontend(FrontendChannel),
      m_inspector(session->inspector()),
      m_enabled(false) {}

245
V8RuntimeAgentImpl::~V8RuntimeAgentImpl() = default;
246 247

void V8RuntimeAgentImpl::evaluate(
248 249 250 251
    const String16& expression, Maybe<String16> objectGroup,
    Maybe<bool> includeCommandLineAPI, Maybe<bool> silent,
    Maybe<int> executionContextId, Maybe<bool> returnByValue,
    Maybe<bool> generatePreview, Maybe<bool> userGesture,
252 253
    Maybe<bool> maybeAwaitPromise, Maybe<bool> throwOnSideEffect,
    Maybe<double> timeout, Maybe<bool> disableBreaks, Maybe<bool> maybeReplMode,
254
    Maybe<bool> allowUnsafeEvalBlockedByCSP, Maybe<String16> uniqueContextId,
255
    std::unique_ptr<EvaluateCallback> callback) {
256 257
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
               "EvaluateScript");
258 259
  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
260 261
                                    std::move(executionContextId),
                                    std::move(uniqueContextId), &contextId);
262
  if (!response.IsSuccess()) {
263
    callback->sendFailure(response);
264 265 266
    return;
  }

267
  InjectedScript::ContextScope scope(m_session, contextId);
268
  response = scope.initialize();
269
  if (!response.IsSuccess()) {
270
    callback->sendFailure(response);
271 272 273 274 275 276
    return;
  }

  if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole();
  if (userGesture.fromMaybe(false)) scope.pretendUserGesture();

277
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
278

279 280
  const bool replMode = maybeReplMode.fromMaybe(false);

281 282 283 284
  if (allowUnsafeEvalBlockedByCSP.fromMaybe(true)) {
    // Temporarily enable allow evals for inspector.
    scope.allowCodeGenerationFromStrings();
  }
285
  v8::MaybeLocal<v8::Value> maybeResultValue;
286
  {
287
    V8InspectorImpl::EvaluateScope evaluateScope(scope);
288 289
    if (timeout.isJust()) {
      response = evaluateScope.setTimeout(timeout.fromJust() / 1000.0);
290
      if (!response.IsSuccess()) {
291 292 293 294
        callback->sendFailure(response);
        return;
      }
    }
295 296
    v8::MicrotasksScope microtasksScope(m_inspector->isolate(),
                                        v8::MicrotasksScope::kRunMicrotasks);
297 298 299 300 301 302 303
    v8::debug::EvaluateGlobalMode mode =
        v8::debug::EvaluateGlobalMode::kDefault;
    if (throwOnSideEffect.fromMaybe(false)) {
      mode = v8::debug::EvaluateGlobalMode::kDisableBreaksAndThrowOnSideEffect;
    } else if (disableBreaks.fromMaybe(false)) {
      mode = v8::debug::EvaluateGlobalMode::kDisableBreaks;
    }
304 305
    const v8::Local<v8::String> source =
        toV8String(m_inspector->isolate(), expression);
306 307
    maybeResultValue = v8::debug::EvaluateGlobal(m_inspector->isolate(), source,
                                                 mode, replMode);
308
  }  // Run microtasks before returning result.
309 310 311

  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
312
  response = scope.initialize();
313
  if (!response.IsSuccess()) {
314
    callback->sendFailure(response);
315 316 317
    return;
  }

318 319 320
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
321 322 323 324

  // REPL mode always returns a promise that must be awaited.
  const bool await = replMode || maybeAwaitPromise.fromMaybe(false);
  if (!await || scope.tryCatch().HasCaught()) {
325
    wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue,
326 327
                            scope.tryCatch(), objectGroup.fromMaybe(""), mode,
                            callback.get());
328 329
    return;
  }
330
  scope.injectedScript()->addPromiseCallback(
331
      m_session, maybeResultValue, objectGroup.fromMaybe(""), mode, replMode,
332
      EvaluateCallbackWrapper<EvaluateCallback>::wrap(std::move(callback)));
333 334 335
}

void V8RuntimeAgentImpl::awaitPromise(
336 337
    const String16& promiseObjectId, Maybe<bool> returnByValue,
    Maybe<bool> generatePreview,
338
    std::unique_ptr<AwaitPromiseCallback> callback) {
339
  InjectedScript::ObjectScope scope(m_session, promiseObjectId);
340
  Response response = scope.initialize();
341
  if (!response.IsSuccess()) {
342
    callback->sendFailure(response);
343 344
    return;
  }
345 346
  if (!scope.object()->IsPromise()) {
    callback->sendFailure(
347
        Response::ServerError("Could not find promise with given id"));
348 349
    return;
  }
350 351 352
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
353
  scope.injectedScript()->addPromiseCallback(
354
      m_session, scope.object(), scope.objectGroupName(), mode,
355
      false /* replMode */,
356
      EvaluateCallbackWrapper<AwaitPromiseCallback>::wrap(std::move(callback)));
357 358 359
}

void V8RuntimeAgentImpl::callFunctionOn(
360
    const String16& expression, Maybe<String16> objectId,
361 362 363
    Maybe<protocol::Array<protocol::Runtime::CallArgument>> optionalArguments,
    Maybe<bool> silent, Maybe<bool> returnByValue, Maybe<bool> generatePreview,
    Maybe<bool> userGesture, Maybe<bool> awaitPromise,
364
    Maybe<int> executionContextId, Maybe<String16> objectGroup,
365
    std::unique_ptr<CallFunctionOnCallback> callback) {
366
  if (objectId.isJust() && executionContextId.isJust()) {
367
    callback->sendFailure(Response::ServerError(
368
        "ObjectId must not be specified together with executionContextId"));
369 370
    return;
  }
371
  if (!objectId.isJust() && !executionContextId.isJust()) {
372
    callback->sendFailure(Response::ServerError(
373
        "Either ObjectId or executionContextId must be specified"));
374 375
    return;
  }
376 377 378
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
379 380 381
  if (objectId.isJust()) {
    InjectedScript::ObjectScope scope(m_session, objectId.fromJust());
    Response response = scope.initialize();
382
    if (!response.IsSuccess()) {
383 384 385
      callback->sendFailure(response);
      return;
    }
386 387 388 389 390 391 392
    innerCallFunctionOn(m_session, scope, scope.object(), expression,
                        std::move(optionalArguments), silent.fromMaybe(false),
                        mode, userGesture.fromMaybe(false),
                        awaitPromise.fromMaybe(false),
                        objectGroup.isJust() ? objectGroup.fromMaybe(String16())
                                             : scope.objectGroupName(),
                        std::move(callback));
393 394
  } else {
    int contextId = 0;
395 396 397
    Response response = ensureContext(m_inspector, m_session->contextGroupId(),
                                      std::move(executionContextId.fromJust()),
                                      /* uniqueContextId */ {}, &contextId);
398
    if (!response.IsSuccess()) {
399 400 401 402 403
      callback->sendFailure(response);
      return;
    }
    InjectedScript::ContextScope scope(m_session, contextId);
    response = scope.initialize();
404
    if (!response.IsSuccess()) {
405 406 407
      callback->sendFailure(response);
      return;
    }
408 409 410 411 412
    innerCallFunctionOn(m_session, scope, scope.context()->Global(), expression,
                        std::move(optionalArguments), silent.fromMaybe(false),
                        mode, userGesture.fromMaybe(false),
                        awaitPromise.fromMaybe(false),
                        objectGroup.fromMaybe(""), std::move(callback));
413
  }
414 415
}

416 417 418
Response V8RuntimeAgentImpl::getProperties(
    const String16& objectId, Maybe<bool> ownProperties,
    Maybe<bool> accessorPropertiesOnly, Maybe<bool> generatePreview,
419 420 421 422
    std::unique_ptr<protocol::Array<protocol::Runtime::PropertyDescriptor>>*
        result,
    Maybe<protocol::Array<protocol::Runtime::InternalPropertyDescriptor>>*
        internalProperties,
423 424
    Maybe<protocol::Array<protocol::Runtime::PrivatePropertyDescriptor>>*
        privateProperties,
425 426
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
  using protocol::Runtime::InternalPropertyDescriptor;
427
  using protocol::Runtime::PrivatePropertyDescriptor;
428

429
  InjectedScript::ObjectScope scope(m_session, objectId);
430
  Response response = scope.initialize();
431
  if (!response.IsSuccess()) return response;
432 433

  scope.ignoreExceptionsAndMuteConsole();
434 435
  v8::MicrotasksScope microtasks_scope(m_inspector->isolate(),
                                       v8::MicrotasksScope::kRunMicrotasks);
436
  if (!scope.object()->IsObject())
437
    return Response::ServerError("Value with given id is not an object");
438 439

  v8::Local<v8::Object> object = scope.object().As<v8::Object>();
440 441
  response = scope.injectedScript()->getProperties(
      object, scope.objectGroupName(), ownProperties.fromMaybe(false),
442 443 444
      accessorPropertiesOnly.fromMaybe(false),
      generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                       : WrapMode::kNoPreview,
445
      result, exceptionDetails);
446
  if (!response.IsSuccess()) return response;
447
  if (exceptionDetails->isJust() || accessorPropertiesOnly.fromMaybe(false))
448
    return Response::Success();
449
  std::unique_ptr<protocol::Array<InternalPropertyDescriptor>>
450 451 452 453 454 455
      internalPropertiesProtocolArray;
  std::unique_ptr<protocol::Array<PrivatePropertyDescriptor>>
      privatePropertiesProtocolArray;
  response = scope.injectedScript()->getInternalAndPrivateProperties(
      object, scope.objectGroupName(), &internalPropertiesProtocolArray,
      &privatePropertiesProtocolArray);
456
  if (!response.IsSuccess()) return response;
457
  if (!internalPropertiesProtocolArray->empty())
458
    *internalProperties = std::move(internalPropertiesProtocolArray);
459
  if (!privatePropertiesProtocolArray->empty())
460
    *privateProperties = std::move(privatePropertiesProtocolArray);
461
  return Response::Success();
462 463
}

464
Response V8RuntimeAgentImpl::releaseObject(const String16& objectId) {
465
  InjectedScript::ObjectScope scope(m_session, objectId);
466
  Response response = scope.initialize();
467
  if (!response.IsSuccess()) return response;
468
  scope.injectedScript()->releaseObject(objectId);
469
  return Response::Success();
470 471
}

472
Response V8RuntimeAgentImpl::releaseObjectGroup(const String16& objectGroup) {
473
  m_session->releaseObjectGroup(objectGroup);
474
  return Response::Success();
475 476
}

477
Response V8RuntimeAgentImpl::runIfWaitingForDebugger() {
478
  m_inspector->client()->runIfWaitingForDebugger(m_session->contextGroupId());
479
  return Response::Success();
480 481
}

482
Response V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(bool enabled) {
483 484
  m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled,
                      enabled);
485
  if (!m_enabled) return Response::ServerError("Runtime agent is not enabled");
486
  m_session->setCustomObjectFormatterEnabled(enabled);
487
  return Response::Success();
488 489
}

490 491
Response V8RuntimeAgentImpl::setMaxCallStackSizeToCapture(int size) {
  if (size < 0) {
492 493
    return Response::ServerError(
        "maxCallStackSizeToCapture should be non-negative");
494 495
  }
  V8StackTraceImpl::maxCallStackSizeToCapture = size;
496
  return Response::Success();
497 498
}

499
Response V8RuntimeAgentImpl::discardConsoleEntries() {
500 501 502
  V8ConsoleMessageStorage* storage =
      m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
  storage->clear();
503
  return Response::Success();
504 505
}

506 507 508
Response V8RuntimeAgentImpl::compileScript(
    const String16& expression, const String16& sourceURL, bool persistScript,
    Maybe<int> executionContextId, Maybe<String16>* scriptId,
509
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
510
  if (!m_enabled) return Response::ServerError("Runtime agent is not enabled");
511 512 513

  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
514 515
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
516
  if (!response.IsSuccess()) return response;
517
  InjectedScript::ContextScope scope(m_session, contextId);
518
  response = scope.initialize();
519
  if (!response.IsSuccess()) return response;
520 521

  if (!persistScript) m_inspector->debugger()->muteScriptParsedEvents();
522 523 524
  v8::Local<v8::Script> script;
  bool isOk = m_inspector->compileScript(scope.context(), expression, sourceURL)
                  .ToLocal(&script);
525
  if (!persistScript) m_inspector->debugger()->unmuteScriptParsedEvents();
526
  if (!isOk) {
527 528
    if (scope.tryCatch().HasCaught()) {
      response = scope.injectedScript()->createExceptionDetails(
529
          scope.tryCatch(), String16(), exceptionDetails);
530 531
      if (!response.IsSuccess()) return response;
      return Response::Success();
532
    } else {
533
      return Response::ServerError("Script compilation failed");
534
    }
535 536
  }

537
  if (!persistScript) return Response::Success();
538 539 540 541 542 543 544

  String16 scriptValueId =
      String16::fromInteger(script->GetUnboundScript()->GetId());
  std::unique_ptr<v8::Global<v8::Script>> global(
      new v8::Global<v8::Script>(m_inspector->isolate(), script));
  m_compiledScripts[scriptValueId] = std::move(global);
  *scriptId = scriptValueId;
545
  return Response::Success();
546 547 548
}

void V8RuntimeAgentImpl::runScript(
549 550 551 552
    const String16& scriptId, Maybe<int> executionContextId,
    Maybe<String16> objectGroup, Maybe<bool> silent,
    Maybe<bool> includeCommandLineAPI, Maybe<bool> returnByValue,
    Maybe<bool> generatePreview, Maybe<bool> awaitPromise,
553 554
    std::unique_ptr<RunScriptCallback> callback) {
  if (!m_enabled) {
555 556
    callback->sendFailure(
        Response::ServerError("Runtime agent is not enabled"));
557 558 559 560 561
    return;
  }

  auto it = m_compiledScripts.find(scriptId);
  if (it == m_compiledScripts.end()) {
562
    callback->sendFailure(Response::ServerError("No script with given id"));
563 564 565
    return;
  }

566 567
  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
568 569
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
570
  if (!response.IsSuccess()) {
571
    callback->sendFailure(response);
572 573 574
    return;
  }

575
  InjectedScript::ContextScope scope(m_session, contextId);
576
  response = scope.initialize();
577
  if (!response.IsSuccess()) {
578
    callback->sendFailure(response);
579 580 581 582 583 584 585 586 587
    return;
  }

  if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole();

  std::unique_ptr<v8::Global<v8::Script>> scriptWrapper = std::move(it->second);
  m_compiledScripts.erase(it);
  v8::Local<v8::Script> script = scriptWrapper->Get(m_inspector->isolate());
  if (script.IsEmpty()) {
588
    callback->sendFailure(Response::ServerError("Script execution failed"));
589 590 591
    return;
  }

592
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
593

594 595 596 597 598 599
  v8::MaybeLocal<v8::Value> maybeResultValue;
  {
    v8::MicrotasksScope microtasksScope(m_inspector->isolate(),
                                        v8::MicrotasksScope::kRunMicrotasks);
    maybeResultValue = script->Run(scope.context());
  }
600 601 602

  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
603
  response = scope.initialize();
604
  if (!response.IsSuccess()) {
605 606 607
    callback->sendFailure(response);
    return;
  }
608

609 610 611
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
612 613
  if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) {
    wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue,
614 615
                            scope.tryCatch(), objectGroup.fromMaybe(""), mode,
                            callback.get());
616 617
    return;
  }
618
  scope.injectedScript()->addPromiseCallback(
619
      m_session, maybeResultValue.ToLocalChecked(), objectGroup.fromMaybe(""),
620
      mode, false /* replMode */,
621
      EvaluateCallbackWrapper<RunScriptCallback>::wrap(std::move(callback)));
622 623
}

624
Response V8RuntimeAgentImpl::queryObjects(
625
    const String16& prototypeObjectId, Maybe<String16> objectGroup,
626
    std::unique_ptr<protocol::Runtime::RemoteObject>* objects) {
627
  InjectedScript::ObjectScope scope(m_session, prototypeObjectId);
628
  Response response = scope.initialize();
629
  if (!response.IsSuccess()) return response;
630
  if (!scope.object()->IsObject()) {
631
    return Response::ServerError("Prototype should be instance of Object");
632 633
  }
  v8::Local<v8::Array> resultArray = m_inspector->debugger()->queryObjects(
634
      scope.context(), scope.object().As<v8::Object>());
635
  return scope.injectedScript()->wrapObject(
636 637
      resultArray, objectGroup.fromMaybe(scope.objectGroupName()),
      WrapMode::kNoPreview, objects);
638 639
}

640 641 642 643 644
Response V8RuntimeAgentImpl::globalLexicalScopeNames(
    Maybe<int> executionContextId,
    std::unique_ptr<protocol::Array<String16>>* outNames) {
  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
645 646
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
647
  if (!response.IsSuccess()) return response;
648 649 650

  InjectedScript::ContextScope scope(m_session, contextId);
  response = scope.initialize();
651
  if (!response.IsSuccess()) return response;
652 653 654

  v8::PersistentValueVector<v8::String> names(m_inspector->isolate());
  v8::debug::GlobalLexicalScopeNames(scope.context(), &names);
655
  *outNames = std::make_unique<protocol::Array<String16>>();
656
  for (size_t i = 0; i < names.Size(); ++i) {
657
    (*outNames)->emplace_back(
658
        toProtocolString(m_inspector->isolate(), names.Get(i)));
659
  }
660
  return Response::Success();
661 662
}

663 664
Response V8RuntimeAgentImpl::getIsolateId(String16* outIsolateId) {
  char buf[40];
665
  std::snprintf(buf, sizeof(buf), "%" PRIx64, m_inspector->isolateId());
666
  *outIsolateId = buf;
667
  return Response::Success();
668 669 670 671 672 673 674 675
}

Response V8RuntimeAgentImpl::getHeapUsage(double* out_usedSize,
                                          double* out_totalSize) {
  v8::HeapStatistics stats;
  m_inspector->isolate()->GetHeapStatistics(&stats);
  *out_usedSize = stats.used_heap_size();
  *out_totalSize = stats.total_heap_size();
676
  return Response::Success();
677 678
}

679 680 681 682 683
void V8RuntimeAgentImpl::terminateExecution(
    std::unique_ptr<TerminateExecutionCallback> callback) {
  m_inspector->debugger()->terminateExecution(std::move(callback));
}

684 685 686 687 688 689 690 691 692 693
namespace {
protocol::DictionaryValue* getOrCreateDictionary(
    protocol::DictionaryValue* dict, const String16& key) {
  if (protocol::DictionaryValue* bindings = dict->getObject(key))
    return bindings;
  dict->setObject(key, protocol::DictionaryValue::create());
  return dict->getObject(key);
}
}  // namespace

694
Response V8RuntimeAgentImpl::addBinding(const String16& name,
695 696
                                        Maybe<int> executionContextId,
                                        Maybe<String16> executionContextName) {
697
  if (m_activeBindings.count(name)) return Response::Success();
698
  if (executionContextId.isJust()) {
699 700 701 702
    if (executionContextName.isJust()) {
      return Response::InvalidParams(
          "executionContextName is mutually exclusive with executionContextId");
    }
703 704 705 706
    int contextId = executionContextId.fromJust();
    InspectedContext* context =
        m_inspector->getContext(m_session->contextGroupId(), contextId);
    if (!context) {
707
      return Response::InvalidParams(
708 709 710
          "Cannot find execution context with given executionContextId");
    }
    addBinding(context, name);
711
    return Response::Success();
712
  }
713 714 715 716 717 718 719 720 721 722

  // If it's a globally exposed binding, i.e. no context name specified, use
  // a special value for the context name.
  String16 contextKey = V8RuntimeAgentImplState::globalBindingsKey;
  if (executionContextName.isJust()) {
    contextKey = executionContextName.fromJust();
    if (contextKey == V8RuntimeAgentImplState::globalBindingsKey) {
      return Response::InvalidParams("Invalid executionContextName");
    }
  }
723 724 725
  // Only persist non context-specific bindings, as contextIds don't make
  // any sense when state is restored in a different process.
  protocol::DictionaryValue* bindings =
726 727 728 729 730
      getOrCreateDictionary(m_state, V8RuntimeAgentImplState::bindings);
  protocol::DictionaryValue* contextBindings =
      getOrCreateDictionary(bindings, contextKey);
  contextBindings->setBoolean(name, true);

731 732
  m_inspector->forEachContext(
      m_session->contextGroupId(),
733 734 735 736 737 738
      [&name, &executionContextName, this](InspectedContext* context) {
        if (executionContextName.isJust() &&
            executionContextName.fromJust() != context->humanReadableName())
          return;
        addBinding(context, name);
      });
739
  return Response::Success();
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
}

void V8RuntimeAgentImpl::bindingCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();
  if (info.Length() != 1 || !info[0]->IsString()) {
    info.GetIsolate()->ThrowException(toV8String(
        isolate, "Invalid arguments: should be exactly one string."));
    return;
  }
  V8InspectorImpl* inspector =
      static_cast<V8InspectorImpl*>(v8::debug::GetInspector(isolate));
  int contextId = InspectedContext::contextId(isolate->GetCurrentContext());
  int contextGroupId = inspector->contextGroupId(contextId);

755 756
  String16 name = toProtocolString(isolate, info.Data().As<v8::String>());
  String16 payload = toProtocolString(isolate, info[0].As<v8::String>());
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

  inspector->forEachSession(
      contextGroupId,
      [&name, &payload, &contextId](V8InspectorSessionImpl* session) {
        session->runtimeAgent()->bindingCalled(name, payload, contextId);
      });
}

void V8RuntimeAgentImpl::addBinding(InspectedContext* context,
                                    const String16& name) {
  v8::HandleScope handles(m_inspector->isolate());
  v8::Local<v8::Context> localContext = context->context();
  v8::Local<v8::Object> global = localContext->Global();
  v8::Local<v8::String> v8Name = toV8String(m_inspector->isolate(), name);
  v8::Local<v8::Value> functionValue;
  v8::MicrotasksScope microtasks(m_inspector->isolate(),
                                 v8::MicrotasksScope::kDoNotRunMicrotasks);
  if (v8::Function::New(localContext, bindingCallback, v8Name)
          .ToLocal(&functionValue)) {
    v8::Maybe<bool> success = global->Set(localContext, v8Name, functionValue);
    USE(success);
778
    m_activeBindings.insert(name);
779 780 781 782 783 784
  }
}

Response V8RuntimeAgentImpl::removeBinding(const String16& name) {
  protocol::DictionaryValue* bindings =
      m_state->getObject(V8RuntimeAgentImplState::bindings);
785 786
  if (bindings) bindings->remove(name);
  m_activeBindings.erase(name);
787
  return Response::Success();
788 789 790 791 792
}

void V8RuntimeAgentImpl::bindingCalled(const String16& name,
                                       const String16& payload,
                                       int executionContextId) {
793
  if (!m_activeBindings.count(name)) return;
794 795 796 797
  m_frontend.bindingCalled(name, payload, executionContextId);
}

void V8RuntimeAgentImpl::addBindings(InspectedContext* context) {
798
  const String16 contextName = context->humanReadableName();
799 800 801 802
  if (!m_enabled) return;
  protocol::DictionaryValue* bindings =
      m_state->getObject(V8RuntimeAgentImplState::bindings);
  if (!bindings) return;
803 804 805 806 807 808 809 810 811 812 813 814
  protocol::DictionaryValue* globalBindings =
      bindings->getObject(V8RuntimeAgentImplState::globalBindingsKey);
  if (globalBindings) {
    for (size_t i = 0; i < globalBindings->size(); ++i)
      addBinding(context, globalBindings->at(i).first);
  }
  protocol::DictionaryValue* contextBindings =
      contextName.isEmpty() ? nullptr : bindings->getObject(contextName);
  if (contextBindings) {
    for (size_t i = 0; i < contextBindings->size(); ++i)
      addBinding(context, contextBindings->at(i).first);
  }
815 816
}

817 818 819 820
void V8RuntimeAgentImpl::restore() {
  if (!m_state->booleanProperty(V8RuntimeAgentImplState::runtimeEnabled, false))
    return;
  m_frontend.executionContextsCleared();
821
  enable();
822 823 824
  if (m_state->booleanProperty(
          V8RuntimeAgentImplState::customObjectFormatterEnabled, false))
    m_session->setCustomObjectFormatterEnabled(true);
825 826 827 828

  m_inspector->forEachContext(
      m_session->contextGroupId(),
      [this](InspectedContext* context) { addBindings(context); });
829 830
}

831
Response V8RuntimeAgentImpl::enable() {
832
  if (m_enabled) return Response::Success();
833 834 835 836 837 838 839 840
  m_inspector->client()->beginEnsureAllContextsInGroup(
      m_session->contextGroupId());
  m_enabled = true;
  m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, true);
  m_inspector->enableStackCapturingIfNeeded();
  m_session->reportAllContexts(this);
  V8ConsoleMessageStorage* storage =
      m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
841
  for (const auto& message : storage->messages()) {
842
    if (!reportMessage(message.get(), false)) break;
843
  }
844
  return Response::Success();
845 846
}

847
Response V8RuntimeAgentImpl::disable() {
848
  if (!m_enabled) return Response::Success();
849 850
  m_enabled = false;
  m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, false);
851
  m_state->remove(V8RuntimeAgentImplState::bindings);
852
  m_inspector->disableStackCapturingIfNeeded();
853
  m_session->setCustomObjectFormatterEnabled(false);
854 855 856
  reset();
  m_inspector->client()->endEnsureAllContextsInGroup(
      m_session->contextGroupId());
857 858 859
  if (m_session->debuggerAgent() && !m_session->debuggerAgent()->enabled()) {
    m_session->debuggerAgent()->setAsyncCallStackDepth(0);
  }
860
  return Response::Success();
861 862 863 864 865
}

void V8RuntimeAgentImpl::reset() {
  m_compiledScripts.clear();
  if (m_enabled) {
866 867 868 869 870
    int sessionId = m_session->sessionId();
    m_inspector->forEachContext(m_session->contextGroupId(),
                                [&sessionId](InspectedContext* context) {
                                  context->setReported(sessionId, false);
                                });
871 872 873 874 875 876 877
    m_frontend.executionContextsCleared();
  }
}

void V8RuntimeAgentImpl::reportExecutionContextCreated(
    InspectedContext* context) {
  if (!m_enabled) return;
878
  context->setReported(m_session->sessionId(), true);
879 880 881 882 883
  std::unique_ptr<protocol::Runtime::ExecutionContextDescription> description =
      protocol::Runtime::ExecutionContextDescription::create()
          .setId(context->contextId())
          .setName(context->humanReadableName())
          .setOrigin(context->origin())
884
          .setUniqueId(context->uniqueId().toString())
885
          .build();
886 887 888 889 890
  const String16& aux = context->auxData();
  if (!aux.isEmpty()) {
    std::vector<uint8_t> cbor;
    v8_crdtp::json::ConvertJSONToCBOR(
        v8_crdtp::span<uint16_t>(aux.characters16(), aux.length()), &cbor);
891
    description->setAuxData(protocol::DictionaryValue::cast(
892 893
        protocol::Value::parseBinary(cbor.data(), cbor.size())));
  }
894 895 896 897 898
  m_frontend.executionContextCreated(std::move(description));
}

void V8RuntimeAgentImpl::reportExecutionContextDestroyed(
    InspectedContext* context) {
899 900
  if (m_enabled && context->isReported(m_session->sessionId())) {
    context->setReported(m_session->sessionId(), false);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    m_frontend.executionContextDestroyed(context->contextId());
  }
}

void V8RuntimeAgentImpl::inspect(
    std::unique_ptr<protocol::Runtime::RemoteObject> objectToInspect,
    std::unique_ptr<protocol::DictionaryValue> hints) {
  if (m_enabled)
    m_frontend.inspectRequested(std::move(objectToInspect), std::move(hints));
}

void V8RuntimeAgentImpl::messageAdded(V8ConsoleMessage* message) {
  if (m_enabled) reportMessage(message, true);
}

916
bool V8RuntimeAgentImpl::reportMessage(V8ConsoleMessage* message,
917 918 919
                                       bool generatePreview) {
  message->reportToFrontend(&m_frontend, m_session, generatePreview);
  m_frontend.flush();
920
  return m_inspector->hasConsoleMessageStorage(m_session->contextGroupId());
921 922
}
}  // namespace v8_inspector