v8-runtime-agent-impl.cc 39.3 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 37 38 39 40
#include "include/v8-container.h"
#include "include/v8-context.h"
#include "include/v8-function.h"
#include "include/v8-inspector.h"
#include "include/v8-microtask-queue.h"
41
#include "src/debug/debug-interface.h"
42 43
#include "src/inspector/injected-script.h"
#include "src/inspector/inspected-context.h"
44
#include "src/inspector/protocol/Protocol.h"
45 46 47 48 49 50 51
#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"
52
#include "src/inspector/v8-value-utils.h"
53
#include "src/tracing/trace-event.h"
54

55 56 57 58 59
namespace v8_inspector {

namespace V8RuntimeAgentImplState {
static const char customObjectFormatterEnabled[] =
    "customObjectFormatterEnabled";
60
static const char maxCallStackSizeToCapture[] = "maxCallStackSizeToCapture";
61
static const char runtimeEnabled[] = "runtimeEnabled";
62
static const char bindings[] = "bindings";
63
static const char globalBindingsKey[] = "";
64
}  // namespace V8RuntimeAgentImplState
65 66 67 68 69

using protocol::Runtime::RemoteObject;

namespace {

70 71
template <typename ProtocolCallback>
class EvaluateCallbackWrapper : public EvaluateCallback {
72
 public:
73 74 75 76
  static std::unique_ptr<EvaluateCallback> wrap(
      std::unique_ptr<ProtocolCallback> callback) {
    return std::unique_ptr<EvaluateCallback>(
        new EvaluateCallbackWrapper(std::move(callback)));
77
  }
78 79 80 81 82
  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));
83
  }
84 85
  void sendFailure(const protocol::DispatchResponse& response) override {
    return m_callback->sendFailure(response);
86 87
  }

88 89 90
 private:
  explicit EvaluateCallbackWrapper(std::unique_ptr<ProtocolCallback> callback)
      : m_callback(std::move(callback)) {}
91

92
  std::unique_ptr<ProtocolCallback> m_callback;
93 94
};

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

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

115
void innerCallFunctionOn(
116
    V8InspectorSessionImpl* session, InjectedScript::Scope& scope,
117 118
    v8::Local<v8::Value> recv, const String16& expression,
    Maybe<protocol::Array<protocol::Runtime::CallArgument>> optionalArguments,
119
    bool silent, WrapMode wrapMode, bool userGesture, bool awaitPromise,
120
    const String16& objectGroup, bool throw_on_side_effect,
121 122 123 124 125 126 127 128
    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();
129
    argc = static_cast<int>(arguments->size());
130 131 132 133
    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(
134
          (*arguments)[i].get(), &argumentValue);
135
      if (!response.IsSuccess()) {
136 137 138 139 140 141 142 143 144 145
        callback->sendFailure(response);
        return;
      }
      argv[i] = argumentValue;
    }
  }

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

146 147 148
  // Temporarily enable allow evals for inspector.
  scope.allowCodeGenerationFromStrings();

149 150 151 152 153 154 155 156 157 158 159 160
  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();
161
  if (!response.IsSuccess()) {
162 163 164 165 166 167
    callback->sendFailure(response);
    return;
  }

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

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

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

  if (!awaitPromise || scope.tryCatch().HasCaught()) {
    wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue,
199 200
                            scope.tryCatch(), objectGroup, wrapMode,
                            callback.get());
201 202 203 204
    return;
  }

  scope.injectedScript()->addPromiseCallback(
205
      session, maybeResultValue, objectGroup, wrapMode, false /* replMode */,
206 207 208 209
      EvaluateCallbackWrapper<V8RuntimeAgentImpl::CallFunctionOnCallback>::wrap(
          std::move(callback)));
}

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

235
  return Response::Success();
236 237 238 239 240 241 242 243 244 245 246 247 248
}

}  // 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) {}

249
V8RuntimeAgentImpl::~V8RuntimeAgentImpl() = default;
250 251

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

271
  InjectedScript::ContextScope scope(m_session, contextId);
272
  response = scope.initialize();
273
  if (!response.IsSuccess()) {
274
    callback->sendFailure(response);
275 276 277 278 279 280
    return;
  }

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

281
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
282

283 284
  const bool replMode = maybeReplMode.fromMaybe(false);

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

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

322 323 324
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
325 326 327 328

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

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

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

422 423 424
Response V8RuntimeAgentImpl::getProperties(
    const String16& objectId, Maybe<bool> ownProperties,
    Maybe<bool> accessorPropertiesOnly, Maybe<bool> generatePreview,
425
    Maybe<bool> nonIndexedPropertiesOnly,
426 427 428 429
    std::unique_ptr<protocol::Array<protocol::Runtime::PropertyDescriptor>>*
        result,
    Maybe<protocol::Array<protocol::Runtime::InternalPropertyDescriptor>>*
        internalProperties,
430 431
    Maybe<protocol::Array<protocol::Runtime::PrivatePropertyDescriptor>>*
        privateProperties,
432 433
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
  using protocol::Runtime::InternalPropertyDescriptor;
434
  using protocol::Runtime::PrivatePropertyDescriptor;
435

436
  InjectedScript::ObjectScope scope(m_session, objectId);
437
  Response response = scope.initialize();
438
  if (!response.IsSuccess()) return response;
439 440

  scope.ignoreExceptionsAndMuteConsole();
441 442
  v8::MicrotasksScope microtasks_scope(m_inspector->isolate(),
                                       v8::MicrotasksScope::kRunMicrotasks);
443
  if (!scope.object()->IsObject())
444
    return Response::ServerError("Value with given id is not an object");
445 446

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

471
Response V8RuntimeAgentImpl::releaseObject(const String16& objectId) {
472
  InjectedScript::ObjectScope scope(m_session, objectId);
473
  Response response = scope.initialize();
474
  if (!response.IsSuccess()) return response;
475
  scope.injectedScript()->releaseObject(objectId);
476
  return Response::Success();
477 478
}

479
Response V8RuntimeAgentImpl::releaseObjectGroup(const String16& objectGroup) {
480
  m_session->releaseObjectGroup(objectGroup);
481
  return Response::Success();
482 483
}

484
Response V8RuntimeAgentImpl::runIfWaitingForDebugger() {
485
  m_inspector->client()->runIfWaitingForDebugger(m_session->contextGroupId());
486
  return Response::Success();
487 488
}

489
Response V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(bool enabled) {
490 491
  m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled,
                      enabled);
492
  if (!m_enabled) return Response::ServerError("Runtime agent is not enabled");
493
  m_session->setCustomObjectFormatterEnabled(enabled);
494
  return Response::Success();
495 496
}

497 498
Response V8RuntimeAgentImpl::setMaxCallStackSizeToCapture(int size) {
  if (size < 0) {
499 500
    return Response::ServerError(
        "maxCallStackSizeToCapture should be non-negative");
501
  }
502 503 504 505
  TRACE_EVENT_WITH_FLOW1(
      TRACE_DISABLED_BY_DEFAULT("v8.inspector"),
      "V8RuntimeAgentImpl::setMaxCallStackSizeToCapture", this,
      TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "size", size);
506 507 508
  if (!m_enabled) return Response::ServerError("Runtime agent is not enabled");
  m_state->setInteger(V8RuntimeAgentImplState::maxCallStackSizeToCapture, size);
  m_inspector->debugger()->setMaxCallStackSizeToCapture(this, size);
509
  return Response::Success();
510 511
}

512
Response V8RuntimeAgentImpl::discardConsoleEntries() {
513 514 515
  V8ConsoleMessageStorage* storage =
      m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
  storage->clear();
516
  return Response::Success();
517 518
}

519 520 521
Response V8RuntimeAgentImpl::compileScript(
    const String16& expression, const String16& sourceURL, bool persistScript,
    Maybe<int> executionContextId, Maybe<String16>* scriptId,
522
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
523
  if (!m_enabled) return Response::ServerError("Runtime agent is not enabled");
524 525 526

  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
527 528
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
529
  if (!response.IsSuccess()) return response;
530
  InjectedScript::ContextScope scope(m_session, contextId);
531
  response = scope.initialize();
532
  if (!response.IsSuccess()) return response;
533 534

  if (!persistScript) m_inspector->debugger()->muteScriptParsedEvents();
535 536 537
  v8::Local<v8::Script> script;
  bool isOk = m_inspector->compileScript(scope.context(), expression, sourceURL)
                  .ToLocal(&script);
538
  if (!persistScript) m_inspector->debugger()->unmuteScriptParsedEvents();
539
  if (!isOk) {
540 541
    if (scope.tryCatch().HasCaught()) {
      response = scope.injectedScript()->createExceptionDetails(
542
          scope.tryCatch(), String16(), exceptionDetails);
543 544
      if (!response.IsSuccess()) return response;
      return Response::Success();
545
    } else {
546
      return Response::ServerError("Script compilation failed");
547
    }
548 549
  }

550
  if (!persistScript) return Response::Success();
551 552 553 554 555 556 557

  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;
558
  return Response::Success();
559 560 561
}

void V8RuntimeAgentImpl::runScript(
562 563 564 565
    const String16& scriptId, Maybe<int> executionContextId,
    Maybe<String16> objectGroup, Maybe<bool> silent,
    Maybe<bool> includeCommandLineAPI, Maybe<bool> returnByValue,
    Maybe<bool> generatePreview, Maybe<bool> awaitPromise,
566 567
    std::unique_ptr<RunScriptCallback> callback) {
  if (!m_enabled) {
568 569
    callback->sendFailure(
        Response::ServerError("Runtime agent is not enabled"));
570 571 572 573 574
    return;
  }

  auto it = m_compiledScripts.find(scriptId);
  if (it == m_compiledScripts.end()) {
575
    callback->sendFailure(Response::ServerError("No script with given id"));
576 577 578
    return;
  }

579 580
  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
581 582
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
583
  if (!response.IsSuccess()) {
584
    callback->sendFailure(response);
585 586 587
    return;
  }

588
  InjectedScript::ContextScope scope(m_session, contextId);
589
  response = scope.initialize();
590
  if (!response.IsSuccess()) {
591
    callback->sendFailure(response);
592 593 594 595 596 597 598 599 600
    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()) {
601
    callback->sendFailure(Response::ServerError("Script execution failed"));
602 603 604
    return;
  }

605
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
606

607 608 609 610 611 612
  v8::MaybeLocal<v8::Value> maybeResultValue;
  {
    v8::MicrotasksScope microtasksScope(m_inspector->isolate(),
                                        v8::MicrotasksScope::kRunMicrotasks);
    maybeResultValue = script->Run(scope.context());
  }
613 614 615

  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
616
  response = scope.initialize();
617
  if (!response.IsSuccess()) {
618 619 620
    callback->sendFailure(response);
    return;
  }
621

622 623 624
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
625 626
  if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) {
    wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue,
627 628
                            scope.tryCatch(), objectGroup.fromMaybe(""), mode,
                            callback.get());
629 630
    return;
  }
631
  scope.injectedScript()->addPromiseCallback(
632
      m_session, maybeResultValue.ToLocalChecked(), objectGroup.fromMaybe(""),
633
      mode, false /* replMode */,
634
      EvaluateCallbackWrapper<RunScriptCallback>::wrap(std::move(callback)));
635 636
}

637
Response V8RuntimeAgentImpl::queryObjects(
638
    const String16& prototypeObjectId, Maybe<String16> objectGroup,
639
    std::unique_ptr<protocol::Runtime::RemoteObject>* objects) {
640
  InjectedScript::ObjectScope scope(m_session, prototypeObjectId);
641
  Response response = scope.initialize();
642
  if (!response.IsSuccess()) return response;
643
  if (!scope.object()->IsObject()) {
644
    return Response::ServerError("Prototype should be instance of Object");
645 646
  }
  v8::Local<v8::Array> resultArray = m_inspector->debugger()->queryObjects(
647
      scope.context(), scope.object().As<v8::Object>());
648
  return scope.injectedScript()->wrapObject(
649 650
      resultArray, objectGroup.fromMaybe(scope.objectGroupName()),
      WrapMode::kNoPreview, objects);
651 652
}

653 654 655 656 657
Response V8RuntimeAgentImpl::globalLexicalScopeNames(
    Maybe<int> executionContextId,
    std::unique_ptr<protocol::Array<String16>>* outNames) {
  int contextId = 0;
  Response response = ensureContext(m_inspector, m_session->contextGroupId(),
658 659
                                    std::move(executionContextId),
                                    /*uniqueContextId*/ {}, &contextId);
660
  if (!response.IsSuccess()) return response;
661 662 663

  InjectedScript::ContextScope scope(m_session, contextId);
  response = scope.initialize();
664
  if (!response.IsSuccess()) return response;
665 666 667

  v8::PersistentValueVector<v8::String> names(m_inspector->isolate());
  v8::debug::GlobalLexicalScopeNames(scope.context(), &names);
668
  *outNames = std::make_unique<protocol::Array<String16>>();
669
  for (size_t i = 0; i < names.Size(); ++i) {
670
    (*outNames)->emplace_back(
671
        toProtocolString(m_inspector->isolate(), names.Get(i)));
672
  }
673
  return Response::Success();
674 675
}

676 677
Response V8RuntimeAgentImpl::getIsolateId(String16* outIsolateId) {
  char buf[40];
678
  std::snprintf(buf, sizeof(buf), "%" PRIx64, m_inspector->isolateId());
679
  *outIsolateId = buf;
680
  return Response::Success();
681 682 683 684 685 686 687 688
}

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();
689
  return Response::Success();
690 691
}

692 693 694 695 696
void V8RuntimeAgentImpl::terminateExecution(
    std::unique_ptr<TerminateExecutionCallback> callback) {
  m_inspector->debugger()->terminateExecution(std::move(callback));
}

697 698 699 700 701 702 703 704 705 706
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

707
Response V8RuntimeAgentImpl::addBinding(const String16& name,
708 709
                                        Maybe<int> executionContextId,
                                        Maybe<String16> executionContextName) {
710
  if (executionContextId.isJust()) {
711 712 713 714
    if (executionContextName.isJust()) {
      return Response::InvalidParams(
          "executionContextName is mutually exclusive with executionContextId");
    }
715 716 717 718
    int contextId = executionContextId.fromJust();
    InspectedContext* context =
        m_inspector->getContext(m_session->contextGroupId(), contextId);
    if (!context) {
719
      return Response::InvalidParams(
720 721 722
          "Cannot find execution context with given executionContextId");
    }
    addBinding(context, name);
723
    return Response::Success();
724
  }
725 726 727 728 729 730 731 732 733 734

  // 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");
    }
  }
735 736 737
  // Only persist non context-specific bindings, as contextIds don't make
  // any sense when state is restored in a different process.
  protocol::DictionaryValue* bindings =
738 739 740 741 742
      getOrCreateDictionary(m_state, V8RuntimeAgentImplState::bindings);
  protocol::DictionaryValue* contextBindings =
      getOrCreateDictionary(bindings, contextKey);
  contextBindings->setBoolean(name, true);

743 744
  m_inspector->forEachContext(
      m_session->contextGroupId(),
745 746 747 748 749 750
      [&name, &executionContextName, this](InspectedContext* context) {
        if (executionContextName.isJust() &&
            executionContextName.fromJust() != context->humanReadableName())
          return;
        addBinding(context, name);
      });
751
  return Response::Success();
752 753 754 755 756 757
}

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

767 768
  String16 name = toProtocolString(isolate, info.Data().As<v8::String>());
  String16 payload = toProtocolString(isolate, info[0].As<v8::String>());
769 770 771 772 773 774 775 776 777 778

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

void V8RuntimeAgentImpl::addBinding(InspectedContext* context,
                                    const String16& name) {
779 780 781 782
  auto it = m_activeBindings.find(name);
  if (it != m_activeBindings.end() && it->second.count(context->contextId())) {
    return;
  }
783 784 785 786 787 788 789 790 791 792 793
  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);
794 795 796 797 798 799
    if (it == m_activeBindings.end()) {
      m_activeBindings.emplace(name,
                               std::unordered_set<int>(context->contextId()));
    } else {
      m_activeBindings.at(name).insert(context->contextId());
    }
800 801 802 803 804 805
  }
}

Response V8RuntimeAgentImpl::removeBinding(const String16& name) {
  protocol::DictionaryValue* bindings =
      m_state->getObject(V8RuntimeAgentImplState::bindings);
806 807
  if (bindings) bindings->remove(name);
  m_activeBindings.erase(name);
808
  return Response::Success();
809 810
}

811 812 813 814 815 816 817 818 819
Response V8RuntimeAgentImpl::getExceptionDetails(
    const String16& errorObjectId,
    Maybe<protocol::Runtime::ExceptionDetails>* out_exceptionDetails) {
  InjectedScript::ObjectScope scope(m_session, errorObjectId);
  Response response = scope.initialize();
  if (!response.IsSuccess()) return response;

  const v8::Local<v8::Value> error = scope.object();
  if (!error->IsNativeError())
820
    return Response::ServerError("errorObjectId is not a JS error object");
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

  const v8::Local<v8::Message> message =
      v8::debug::CreateMessageFromException(m_inspector->isolate(), error);

  response = scope.injectedScript()->createExceptionDetails(
      message, error, scope.objectGroupName(), out_exceptionDetails);
  if (!response.IsSuccess()) return response;

  CHECK(out_exceptionDetails->isJust());

  // When an exception object is present, `createExceptionDetails` assumes
  // the exception is uncaught and will overwrite the text field to "Uncaught".
  // Lets use the normal message text instead.
  out_exceptionDetails->fromJust()->setText(
      toProtocolString(m_inspector->isolate(), message->Get()));
836 837 838 839 840 841 842

  // Check if the exception has any metadata on the inspector and also attach
  // it.
  std::unique_ptr<protocol::DictionaryValue> data =
      m_inspector->getAssociatedExceptionDataForProtocol(error);
  if (data)
    out_exceptionDetails->fromJust()->setExceptionMetaData(std::move(data));
843 844 845
  return Response::Success();
}

846 847 848
void V8RuntimeAgentImpl::bindingCalled(const String16& name,
                                       const String16& payload,
                                       int executionContextId) {
849
  if (!m_activeBindings.count(name)) return;
850
  m_frontend.bindingCalled(name, payload, executionContextId);
851
  m_frontend.flush();
852 853 854
}

void V8RuntimeAgentImpl::addBindings(InspectedContext* context) {
855
  const String16 contextName = context->humanReadableName();
856 857 858 859
  if (!m_enabled) return;
  protocol::DictionaryValue* bindings =
      m_state->getObject(V8RuntimeAgentImplState::bindings);
  if (!bindings) return;
860 861 862 863 864 865 866 867 868 869 870 871
  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);
  }
872 873
}

874 875 876 877
void V8RuntimeAgentImpl::restore() {
  if (!m_state->booleanProperty(V8RuntimeAgentImplState::runtimeEnabled, false))
    return;
  m_frontend.executionContextsCleared();
878
  enable();
879 880 881
  if (m_state->booleanProperty(
          V8RuntimeAgentImplState::customObjectFormatterEnabled, false))
    m_session->setCustomObjectFormatterEnabled(true);
882

883 884 885 886 887
  int size;
  if (m_state->getInteger(V8RuntimeAgentImplState::maxCallStackSizeToCapture,
                          &size))
    m_inspector->debugger()->setMaxCallStackSizeToCapture(this, size);

888 889 890
  m_inspector->forEachContext(
      m_session->contextGroupId(),
      [this](InspectedContext* context) { addBindings(context); });
891 892
}

893
Response V8RuntimeAgentImpl::enable() {
894
  if (m_enabled) return Response::Success();
895 896 897
  TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("v8.inspector"),
                         "V8RuntimeAgentImpl::enable", this,
                         TRACE_EVENT_FLAG_FLOW_OUT);
898 899 900 901
  m_inspector->client()->beginEnsureAllContextsInGroup(
      m_session->contextGroupId());
  m_enabled = true;
  m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, true);
902 903
  m_inspector->debugger()->setMaxCallStackSizeToCapture(
      this, V8StackTraceImpl::kDefaultMaxCallStackSizeToCapture);
904 905 906
  m_session->reportAllContexts(this);
  V8ConsoleMessageStorage* storage =
      m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
907
  for (const auto& message : storage->messages()) {
908
    if (!reportMessage(message.get(), false)) break;
909
  }
910
  return Response::Success();
911 912
}

913
Response V8RuntimeAgentImpl::disable() {
914
  if (!m_enabled) return Response::Success();
915 916 917
  TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("v8.inspector"),
                         "V8RuntimeAgentImpl::disable", this,
                         TRACE_EVENT_FLAG_FLOW_IN);
918 919
  m_enabled = false;
  m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, false);
920
  m_state->remove(V8RuntimeAgentImplState::bindings);
921
  m_inspector->debugger()->setMaxCallStackSizeToCapture(this, -1);
922
  m_session->setCustomObjectFormatterEnabled(false);
923 924 925
  reset();
  m_inspector->client()->endEnsureAllContextsInGroup(
      m_session->contextGroupId());
926 927 928
  if (m_session->debuggerAgent() && !m_session->debuggerAgent()->enabled()) {
    m_session->debuggerAgent()->setAsyncCallStackDepth(0);
  }
929
  return Response::Success();
930 931 932 933 934
}

void V8RuntimeAgentImpl::reset() {
  m_compiledScripts.clear();
  if (m_enabled) {
935 936 937 938 939
    int sessionId = m_session->sessionId();
    m_inspector->forEachContext(m_session->contextGroupId(),
                                [&sessionId](InspectedContext* context) {
                                  context->setReported(sessionId, false);
                                });
940 941 942 943 944 945 946
    m_frontend.executionContextsCleared();
  }
}

void V8RuntimeAgentImpl::reportExecutionContextCreated(
    InspectedContext* context) {
  if (!m_enabled) return;
947
  context->setReported(m_session->sessionId(), true);
948 949 950 951 952
  std::unique_ptr<protocol::Runtime::ExecutionContextDescription> description =
      protocol::Runtime::ExecutionContextDescription::create()
          .setId(context->contextId())
          .setName(context->humanReadableName())
          .setOrigin(context->origin())
953
          .setUniqueId(context->uniqueId().toString())
954
          .build();
955 956 957 958 959
  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);
960
    description->setAuxData(protocol::DictionaryValue::cast(
961 962
        protocol::Value::parseBinary(cbor.data(), cbor.size())));
  }
963 964 965 966 967
  m_frontend.executionContextCreated(std::move(description));
}

void V8RuntimeAgentImpl::reportExecutionContextDestroyed(
    InspectedContext* context) {
968 969
  if (m_enabled && context->isReported(m_session->sessionId())) {
    context->setReported(m_session->sessionId(), false);
970 971 972 973 974 975
    m_frontend.executionContextDestroyed(context->contextId());
  }
}

void V8RuntimeAgentImpl::inspect(
    std::unique_ptr<protocol::Runtime::RemoteObject> objectToInspect,
976
    std::unique_ptr<protocol::DictionaryValue> hints, int executionContextId) {
977
  if (m_enabled)
978 979
    m_frontend.inspectRequested(std::move(objectToInspect), std::move(hints),
                                executionContextId);
980 981 982 983 984 985
}

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

986
bool V8RuntimeAgentImpl::reportMessage(V8ConsoleMessage* message,
987 988 989
                                       bool generatePreview) {
  message->reportToFrontend(&m_frontend, m_session, generatePreview);
  m_frontend.flush();
990
  return m_inspector->hasConsoleMessageStorage(m_session->contextGroupId());
991 992
}
}  // namespace v8_inspector