v8-debugger-agent-impl.cc 80.1 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#include "src/inspector/v8-debugger-agent-impl.h"

7 8
#include <algorithm>

9
#include "../../third_party/inspector_protocol/crdtp/json.h"
10 11
#include "include/v8-context.h"
#include "include/v8-function.h"
12
#include "include/v8-inspector.h"
13
#include "include/v8-microtask-queue.h"
14
#include "src/base/safe_conversions.h"
15
#include "src/debug/debug-interface.h"
16 17
#include "src/inspector/injected-script.h"
#include "src/inspector/inspected-context.h"
18
#include "src/inspector/protocol/Debugger.h"
19
#include "src/inspector/protocol/Protocol.h"
20 21 22 23 24 25 26 27 28 29
#include "src/inspector/remote-object-id.h"
#include "src/inspector/search-util.h"
#include "src/inspector/string-util.h"
#include "src/inspector/v8-debugger-script.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-regex.h"
#include "src/inspector/v8-runtime-agent-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"
30
#include "src/inspector/v8-value-utils.h"
31

32 33 34 35 36 37
namespace v8_inspector {

using protocol::Array;
using protocol::Maybe;
using protocol::Debugger::BreakpointId;
using protocol::Debugger::CallFrame;
38
using protocol::Debugger::Scope;
39 40
using protocol::Runtime::ExceptionDetails;
using protocol::Runtime::RemoteObject;
41 42 43 44
using protocol::Runtime::ScriptId;

namespace InstrumentationEnum =
    protocol::Debugger::SetInstrumentationBreakpoint::InstrumentationEnum;
45 46 47 48 49 50

namespace DebuggerAgentState {
static const char pauseOnExceptionsState[] = "pauseOnExceptionsState";
static const char asyncCallStackDepth[] = "asyncCallStackDepth";
static const char blackboxPattern[] = "blackboxPattern";
static const char debuggerEnabled[] = "debuggerEnabled";
51
static const char skipAllPauses[] = "skipAllPauses";
52

53 54
static const char breakpointsByRegex[] = "breakpointsByRegex";
static const char breakpointsByUrl[] = "breakpointsByUrl";
55
static const char breakpointsByScriptHash[] = "breakpointsByScriptHash";
56
static const char breakpointHints[] = "breakpointHints";
57
static const char instrumentationBreakpoints[] = "instrumentationBreakpoints";
58

59
}  // namespace DebuggerAgentState
60

61 62 63 64
static const char kBacktraceObjectGroup[] = "backtrace";
static const char kDebuggerNotEnabled[] = "Debugger agent is not enabled";
static const char kDebuggerNotPaused[] =
    "Can only perform operation while paused.";
65

66 67
static const size_t kBreakpointHintMaxLength = 128;
static const intptr_t kBreakpointHintMaxSearchOffset = 80 * 10;
68 69 70
// Limit the number of breakpoints returned, as we otherwise may exceed
// the maximum length of a message in mojo (see https://crbug.com/1105172).
static const size_t kMaxNumBreakpoints = 1000;
71

72
#if V8_ENABLE_WEBASSEMBLY
73 74 75 76 77 78 79
// TODO(1099680): getScriptSource and getWasmBytecode return Wasm wire bytes
// as protocol::Binary, which is encoded as JSON string in the communication
// to the DevTools front-end and hence leads to either crashing the renderer
// that is being debugged or the renderer that's running the front-end if we
// allow arbitrarily big Wasm byte sequences here. Ideally we would find a
// different way to transfer the wire bytes (middle- to long-term), but as a
// short-term solution, we should at least not crash.
80 81 82
static constexpr size_t kWasmBytecodeMaxLength =
    (v8::String::kMaxLength / 4) * 3;
static constexpr const char kWasmBytecodeExceedsTransferLimit[] =
83
    "WebAssembly bytecode exceeds the transfer limit";
84
#endif  // V8_ENABLE_WEBASSEMBLY
85

86 87
namespace {

88 89 90
enum class BreakpointType {
  kByUrl = 1,
  kByUrlRegex,
91
  kByScriptHash,
92 93
  kByScriptId,
  kDebugCommand,
94
  kMonitorCommand,
95 96
  kBreakpointAtEntry,
  kInstrumentationBreakpoint
97 98 99 100 101
};

String16 generateBreakpointId(BreakpointType type,
                              const String16& scriptSelector, int lineNumber,
                              int columnNumber) {
102
  String16Builder builder;
103 104 105
  builder.appendNumber(static_cast<int>(type));
  builder.append(':');
  builder.appendNumber(lineNumber);
106
  builder.append(':');
107
  builder.appendNumber(columnNumber);
108
  builder.append(':');
109
  builder.append(scriptSelector);
110
  return builder.toString();
111 112
}

113 114 115 116 117 118 119 120 121
String16 generateBreakpointId(BreakpointType type,
                              v8::Local<v8::Function> function) {
  String16Builder builder;
  builder.appendNumber(static_cast<int>(type));
  builder.append(':');
  builder.appendNumber(v8::debug::GetDebuggingId(function));
  return builder.toString();
}

122 123 124 125 126 127 128 129 130
String16 generateInstrumentationBreakpointId(const String16& instrumentation) {
  String16Builder builder;
  builder.appendNumber(
      static_cast<int>(BreakpointType::kInstrumentationBreakpoint));
  builder.append(':');
  builder.append(instrumentation);
  return builder.toString();
}

131 132 133 134 135
bool parseBreakpointId(const String16& breakpointId, BreakpointType* type,
                       String16* scriptSelector = nullptr,
                       int* lineNumber = nullptr, int* columnNumber = nullptr) {
  size_t typeLineSeparator = breakpointId.find(':');
  if (typeLineSeparator == String16::kNotFound) return false;
136 137 138

  int rawType = breakpointId.substring(0, typeLineSeparator).toInteger();
  if (rawType < static_cast<int>(BreakpointType::kByUrl) ||
139
      rawType > static_cast<int>(BreakpointType::kInstrumentationBreakpoint)) {
140 141 142 143
    return false;
  }
  if (type) *type = static_cast<BreakpointType>(rawType);
  if (rawType == static_cast<int>(BreakpointType::kDebugCommand) ||
144
      rawType == static_cast<int>(BreakpointType::kMonitorCommand) ||
145 146 147
      rawType == static_cast<int>(BreakpointType::kBreakpointAtEntry) ||
      rawType == static_cast<int>(BreakpointType::kInstrumentationBreakpoint)) {
    // The script and source position are not encoded in this case.
148 149 150
    return true;
  }

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  size_t lineColumnSeparator = breakpointId.find(':', typeLineSeparator + 1);
  if (lineColumnSeparator == String16::kNotFound) return false;
  size_t columnSelectorSeparator =
      breakpointId.find(':', lineColumnSeparator + 1);
  if (columnSelectorSeparator == String16::kNotFound) return false;
  if (scriptSelector) {
    *scriptSelector = breakpointId.substring(columnSelectorSeparator + 1);
  }
  if (lineNumber) {
    *lineNumber = breakpointId
                      .substring(typeLineSeparator + 1,
                                 lineColumnSeparator - typeLineSeparator - 1)
                      .toInteger();
  }
  if (columnNumber) {
    *columnNumber =
        breakpointId
            .substring(lineColumnSeparator + 1,
                       columnSelectorSeparator - lineColumnSeparator - 1)
            .toInteger();
  }
  return true;
}

175 176
bool positionComparator(const std::pair<int, int>& a,
                        const std::pair<int, int>& b) {
177 178 179 180
  if (a.first != b.first) return a.first < b.first;
  return a.second < b.second;
}

181 182
String16 breakpointHint(const V8DebuggerScript& script, int lineNumber,
                        int columnNumber) {
183 184
  int offset;
  if (!script.offset(lineNumber, columnNumber).To(&offset)) return String16();
185
  String16 hint =
186
      script.source(offset, kBreakpointHintMaxLength).stripWhiteSpace();
187 188 189 190 191 192 193 194
  for (size_t i = 0; i < hint.length(); ++i) {
    if (hint[i] == '\r' || hint[i] == '\n' || hint[i] == ';') {
      return hint.substring(0, i);
    }
  }
  return hint;
}

195 196 197
void adjustBreakpointLocation(const V8DebuggerScript& script,
                              const String16& hint, int* lineNumber,
                              int* columnNumber) {
198 199
  if (*lineNumber < script.startLine() || *lineNumber > script.endLine())
    return;
200 201 202 203 204 205 206 207
  if (*lineNumber == script.startLine() &&
      *columnNumber < script.startColumn()) {
    return;
  }
  if (*lineNumber == script.endLine() && script.endColumn() < *columnNumber) {
    return;
  }

208
  if (hint.isEmpty()) return;
209 210
  int sourceOffset;
  if (!script.offset(*lineNumber, *columnNumber).To(&sourceOffset)) return;
211 212 213 214

  intptr_t searchRegionOffset = std::max(
      sourceOffset - kBreakpointHintMaxSearchOffset, static_cast<intptr_t>(0));
  size_t offset = sourceOffset - searchRegionOffset;
215 216
  String16 searchArea = script.source(searchRegionOffset,
                                      offset + kBreakpointHintMaxSearchOffset);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

  size_t nextMatch = searchArea.find(hint, offset);
  size_t prevMatch = searchArea.reverseFind(hint, offset);
  if (nextMatch == String16::kNotFound && prevMatch == String16::kNotFound) {
    return;
  }
  size_t bestMatch;
  if (nextMatch == String16::kNotFound) {
    bestMatch = prevMatch;
  } else if (prevMatch == String16::kNotFound) {
    bestMatch = nextMatch;
  } else {
    bestMatch = nextMatch - offset < offset - prevMatch ? nextMatch : prevMatch;
  }
  bestMatch += searchRegionOffset;
232 233
  v8::debug::Location hintPosition =
      script.location(static_cast<int>(bestMatch));
234
  if (hintPosition.IsEmpty()) return;
235 236
  *lineNumber = hintPosition.GetLineNumber();
  *columnNumber = hintPosition.GetColumnNumber();
237
}
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

String16 breakLocationType(v8::debug::BreakLocationType type) {
  switch (type) {
    case v8::debug::kCallBreakLocation:
      return protocol::Debugger::BreakLocation::TypeEnum::Call;
    case v8::debug::kReturnBreakLocation:
      return protocol::Debugger::BreakLocation::TypeEnum::Return;
    case v8::debug::kDebuggerStatementBreakLocation:
      return protocol::Debugger::BreakLocation::TypeEnum::DebuggerStatement;
    case v8::debug::kCommonBreakLocation:
      return String16();
  }
  return String16();
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
String16 scopeType(v8::debug::ScopeIterator::ScopeType type) {
  switch (type) {
    case v8::debug::ScopeIterator::ScopeTypeGlobal:
      return Scope::TypeEnum::Global;
    case v8::debug::ScopeIterator::ScopeTypeLocal:
      return Scope::TypeEnum::Local;
    case v8::debug::ScopeIterator::ScopeTypeWith:
      return Scope::TypeEnum::With;
    case v8::debug::ScopeIterator::ScopeTypeClosure:
      return Scope::TypeEnum::Closure;
    case v8::debug::ScopeIterator::ScopeTypeCatch:
      return Scope::TypeEnum::Catch;
    case v8::debug::ScopeIterator::ScopeTypeBlock:
      return Scope::TypeEnum::Block;
    case v8::debug::ScopeIterator::ScopeTypeScript:
      return Scope::TypeEnum::Script;
    case v8::debug::ScopeIterator::ScopeTypeEval:
      return Scope::TypeEnum::Eval;
    case v8::debug::ScopeIterator::ScopeTypeModule:
      return Scope::TypeEnum::Module;
273 274
    case v8::debug::ScopeIterator::ScopeTypeWasmExpressionStack:
      return Scope::TypeEnum::WasmExpressionStack;
275 276 277 278
  }
  UNREACHABLE();
}

279
Response buildScopes(v8::Isolate* isolate, v8::debug::ScopeIterator* iterator,
280 281
                     InjectedScript* injectedScript,
                     std::unique_ptr<Array<Scope>>* scopes) {
282
  *scopes = std::make_unique<Array<Scope>>();
283 284
  if (!injectedScript) return Response::Success();
  if (iterator->Done()) return Response::Success();
285 286 287

  String16 scriptId = String16::fromInteger(iterator->GetScriptId());

288 289
  for (; !iterator->Done(); iterator->Advance()) {
    std::unique_ptr<RemoteObject> object;
290 291 292
    Response result =
        injectedScript->wrapObject(iterator->GetObject(), kBacktraceObjectGroup,
                                   WrapMode::kNoPreview, &object);
293
    if (!result.IsSuccess()) return result;
294

295 296 297 298
    auto scope = Scope::create()
                     .setType(scopeType(iterator->GetType()))
                     .setObject(std::move(object))
                     .build();
299

300 301
    String16 name = toProtocolStringWithTypeCheck(
        isolate, iterator->GetFunctionDebugName());
302 303 304
    if (!name.isEmpty()) scope->setName(name);

    if (iterator->HasLocationInfo()) {
305 306 307 308 309 310
      v8::debug::Location start = iterator->GetStartLocation();
      scope->setStartLocation(protocol::Debugger::Location::create()
                                  .setScriptId(scriptId)
                                  .setLineNumber(start.GetLineNumber())
                                  .setColumnNumber(start.GetColumnNumber())
                                  .build());
311

312 313 314 315 316 317 318
      v8::debug::Location end = iterator->GetEndLocation();
      scope->setEndLocation(protocol::Debugger::Location::create()
                                .setScriptId(scriptId)
                                .setLineNumber(end.GetLineNumber())
                                .setColumnNumber(end.GetColumnNumber())
                                .build());
    }
319
    (*scopes)->emplace_back(std::move(scope));
320
  }
321
  return Response::Success();
322 323
}

324 325 326 327 328 329 330 331 332 333
protocol::DictionaryValue* getOrCreateObject(protocol::DictionaryValue* object,
                                             const String16& key) {
  protocol::DictionaryValue* value = object->getObject(key);
  if (value) return value;
  std::unique_ptr<protocol::DictionaryValue> newDictionary =
      protocol::DictionaryValue::create();
  value = newDictionary.get();
  object->setObject(key, std::move(newDictionary));
  return value;
}
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

Response isValidPosition(protocol::Debugger::ScriptPosition* position) {
  if (position->getLineNumber() < 0)
    return Response::ServerError("Position missing 'line' or 'line' < 0.");
  if (position->getColumnNumber() < 0)
    return Response::ServerError("Position missing 'column' or 'column' < 0.");
  return Response::Success();
}

Response isValidRangeOfPositions(std::vector<std::pair<int, int>>& positions) {
  for (size_t i = 1; i < positions.size(); ++i) {
    if (positions[i - 1].first < positions[i].first) continue;
    if (positions[i - 1].first == positions[i].first &&
        positions[i - 1].second < positions[i].second)
      continue;
    return Response::ServerError(
        "Input positions array is not sorted or contains duplicate values.");
  }
  return Response::Success();
}
354 355 356 357 358 359 360 361 362 363 364

bool hitBreakReasonEncodedAsOther(v8::debug::BreakReasons breakReasons) {
  // The listed break reasons are not explicitly encoded in CDP when
  // reporting the break. They are summarized as 'other'.
  v8::debug::BreakReasons otherBreakReasons(
      {v8::debug::BreakReason::kStep,
       v8::debug::BreakReason::kDebuggerStatement,
       v8::debug::BreakReason::kScheduled, v8::debug::BreakReason::kAsyncStep,
       v8::debug::BreakReason::kAlreadyPaused});
  return breakReasons.contains_any(otherBreakReasons);
}
365 366
}  // namespace

367 368 369 370 371 372 373 374 375
V8DebuggerAgentImpl::V8DebuggerAgentImpl(
    V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel,
    protocol::DictionaryValue* state)
    : m_inspector(session->inspector()),
      m_debugger(m_inspector->debugger()),
      m_session(session),
      m_enabled(false),
      m_state(state),
      m_frontend(frontendChannel),
376
      m_isolate(m_inspector->isolate()) {}
377

378
V8DebuggerAgentImpl::~V8DebuggerAgentImpl() = default;
379

380
void V8DebuggerAgentImpl::enableImpl() {
381 382 383 384
  m_enabled = true;
  m_state->setBoolean(DebuggerAgentState::debuggerEnabled, true);
  m_debugger->enable();

385 386 387 388 389
  std::vector<std::unique_ptr<V8DebuggerScript>> compiledScripts =
      m_debugger->getCompiledScripts(m_session->contextGroupId(), this);
  for (auto& script : compiledScripts) {
    didParseSource(std::move(script), true);
  }
390

391 392
  m_breakpointsActive = true;
  m_debugger->setBreakpointsActive(true);
393 394 395

  if (isPaused()) {
    didPause(0, v8::Local<v8::Value>(), std::vector<v8::debug::BreakpointId>(),
396 397
             v8::debug::kException, false,
             v8::debug::BreakReasons({v8::debug::BreakReason::kAlreadyPaused}));
398
  }
399 400
}

401 402 403 404
Response V8DebuggerAgentImpl::enable(Maybe<double> maxScriptsCacheSize,
                                     String16* outDebuggerId) {
  m_maxScriptCacheSize = v8::base::saturated_cast<size_t>(
      maxScriptsCacheSize.fromMaybe(std::numeric_limits<double>::max()));
405 406
  *outDebuggerId =
      m_debugger->debuggerIdFor(m_session->contextGroupId()).toString();
407
  if (enabled()) return Response::Success();
408

409
  if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId()))
410
    return Response::ServerError("Script execution is prohibited");
411

412
  enableImpl();
413
  return Response::Success();
414 415
}

416
Response V8DebuggerAgentImpl::disable() {
417
  if (!enabled()) return Response::Success();
418

419 420
  m_state->remove(DebuggerAgentState::breakpointsByRegex);
  m_state->remove(DebuggerAgentState::breakpointsByUrl);
421
  m_state->remove(DebuggerAgentState::breakpointsByScriptHash);
422
  m_state->remove(DebuggerAgentState::breakpointHints);
423
  m_state->remove(DebuggerAgentState::instrumentationBreakpoints);
424

425
  m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState,
426
                      v8::debug::NoBreakOnException);
427 428
  m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, 0);

429 430 431 432
  if (m_breakpointsActive) {
    m_debugger->setBreakpointsActive(false);
    m_breakpointsActive = false;
  }
433
  m_blackboxedPositions.clear();
434 435
  m_blackboxPattern.reset();
  resetBlackboxedStateCache();
436
  m_skipList.clear();
437
  m_scripts.clear();
438
  m_cachedScripts.clear();
439
  m_cachedScriptSize = 0;
440 441
  for (const auto& it : m_debuggerBreakpointIdToBreakpointId) {
    v8::debug::RemoveBreakpoint(m_isolate, it.first);
442
  }
443
  m_breakpointIdToDebuggerBreakpointIds.clear();
444
  m_debuggerBreakpointIdToBreakpointId.clear();
445 446 447
  m_debugger->setAsyncCallStackDepth(this, 0);
  clearBreakDetails();
  m_skipAllPauses = false;
448
  m_state->setBoolean(DebuggerAgentState::skipAllPauses, false);
449 450 451
  m_state->remove(DebuggerAgentState::blackboxPattern);
  m_enabled = false;
  m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
452
  m_debugger->disable();
453
  return Response::Success();
454 455 456 457 458 459 460 461 462
}

void V8DebuggerAgentImpl::restore() {
  DCHECK(!m_enabled);
  if (!m_state->booleanProperty(DebuggerAgentState::debuggerEnabled, false))
    return;
  if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId()))
    return;

463
  enableImpl();
464

465
  int pauseState = v8::debug::NoBreakOnException;
466
  m_state->getInteger(DebuggerAgentState::pauseOnExceptionsState, &pauseState);
467
  setPauseOnExceptionsImpl(pauseState);
468 469 470 471 472 473 474 475 476 477 478 479

  m_skipAllPauses =
      m_state->booleanProperty(DebuggerAgentState::skipAllPauses, false);

  int asyncCallStackDepth = 0;
  m_state->getInteger(DebuggerAgentState::asyncCallStackDepth,
                      &asyncCallStackDepth);
  m_debugger->setAsyncCallStackDepth(this, asyncCallStackDepth);

  String16 blackboxPattern;
  if (m_state->getString(DebuggerAgentState::blackboxPattern,
                         &blackboxPattern)) {
480
    setBlackboxPattern(blackboxPattern);
481 482 483
  }
}

484
Response V8DebuggerAgentImpl::setBreakpointsActive(bool active) {
485 486
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (m_breakpointsActive == active) return Response::Success();
487 488
  m_breakpointsActive = active;
  m_debugger->setBreakpointsActive(active);
489 490
  if (!active && !m_breakReason.empty()) {
    clearBreakDetails();
491
    m_debugger->setPauseOnNextCall(false, m_session->contextGroupId());
492
  }
493
  return Response::Success();
494 495
}

496
Response V8DebuggerAgentImpl::setSkipAllPauses(bool skip) {
497
  m_state->setBoolean(DebuggerAgentState::skipAllPauses, skip);
498
  m_skipAllPauses = skip;
499
  return Response::Success();
500 501
}

502
static bool matches(V8InspectorImpl* inspector, const V8DebuggerScript& script,
503 504 505 506 507 508 509 510 511 512
                    BreakpointType type, const String16& selector) {
  switch (type) {
    case BreakpointType::kByUrl:
      return script.sourceURL() == selector;
    case BreakpointType::kByScriptHash:
      return script.hash() == selector;
    case BreakpointType::kByUrlRegex: {
      V8Regex regex(inspector, selector, true);
      return regex.match(script.sourceURL()) != -1;
    }
513 514 515
    case BreakpointType::kByScriptId: {
      return script.scriptId() == selector;
    }
516 517
    default:
      return false;
518 519 520
  }
}

521 522
Response V8DebuggerAgentImpl::setBreakpointByUrl(
    int lineNumber, Maybe<String16> optionalURL,
523 524 525
    Maybe<String16> optionalURLRegex, Maybe<String16> optionalScriptHash,
    Maybe<int> optionalColumnNumber, Maybe<String16> optionalCondition,
    String16* outBreakpointId,
526
    std::unique_ptr<protocol::Array<protocol::Debugger::Location>>* locations) {
527 528
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);

529
  *locations = std::make_unique<Array<protocol::Debugger::Location>>();
530

531 532 533 534
  int specified = (optionalURL.isJust() ? 1 : 0) +
                  (optionalURLRegex.isJust() ? 1 : 0) +
                  (optionalScriptHash.isJust() ? 1 : 0);
  if (specified != 1) {
535
    return Response::ServerError(
536 537
        "Either url or urlRegex or scriptHash must be specified.");
  }
538 539 540
  int columnNumber = 0;
  if (optionalColumnNumber.isJust()) {
    columnNumber = optionalColumnNumber.fromJust();
541 542
    if (columnNumber < 0)
      return Response::ServerError("Incorrect column number");
543 544
  }

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
  BreakpointType type = BreakpointType::kByUrl;
  String16 selector;
  if (optionalURLRegex.isJust()) {
    selector = optionalURLRegex.fromJust();
    type = BreakpointType::kByUrlRegex;
  } else if (optionalURL.isJust()) {
    selector = optionalURL.fromJust();
    type = BreakpointType::kByUrl;
  } else if (optionalScriptHash.isJust()) {
    selector = optionalScriptHash.fromJust();
    type = BreakpointType::kByScriptHash;
  }

  String16 condition = optionalCondition.fromMaybe(String16());
  String16 breakpointId =
      generateBreakpointId(type, selector, lineNumber, columnNumber);
561
  protocol::DictionaryValue* breakpoints;
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  switch (type) {
    case BreakpointType::kByUrlRegex:
      breakpoints =
          getOrCreateObject(m_state, DebuggerAgentState::breakpointsByRegex);
      break;
    case BreakpointType::kByUrl:
      breakpoints = getOrCreateObject(
          getOrCreateObject(m_state, DebuggerAgentState::breakpointsByUrl),
          selector);
      break;
    case BreakpointType::kByScriptHash:
      breakpoints = getOrCreateObject(
          getOrCreateObject(m_state,
                            DebuggerAgentState::breakpointsByScriptHash),
          selector);
      break;
    default:
      UNREACHABLE();
580 581
  }
  if (breakpoints->get(breakpointId)) {
582 583
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
584
  }
585

586
  String16 hint;
587
  for (const auto& script : m_scripts) {
588
    if (!matches(m_inspector, *script.second, type, selector)) continue;
589 590 591 592 593 594
    if (!hint.isEmpty()) {
      adjustBreakpointLocation(*script.second, hint, &lineNumber,
                               &columnNumber);
    }
    std::unique_ptr<protocol::Debugger::Location> location = setBreakpointImpl(
        breakpointId, script.first, condition, lineNumber, columnNumber);
595
    if (location && type != BreakpointType::kByUrlRegex) {
596 597
      hint = breakpointHint(*script.second, location->getLineNumber(),
                            location->getColumnNumber(columnNumber));
598
    }
599
    if (location) (*locations)->emplace_back(std::move(location));
600
  }
601 602 603 604 605 606
  breakpoints->setString(breakpointId, condition);
  if (!hint.isEmpty()) {
    protocol::DictionaryValue* breakpointHints =
        getOrCreateObject(m_state, DebuggerAgentState::breakpointHints);
    breakpointHints->setString(breakpointId, hint);
  }
607
  *outBreakpointId = breakpointId;
608
  return Response::Success();
609 610
}

611
Response V8DebuggerAgentImpl::setBreakpoint(
612
    std::unique_ptr<protocol::Debugger::Location> location,
613
    Maybe<String16> optionalCondition, String16* outBreakpointId,
614
    std::unique_ptr<protocol::Debugger::Location>* actualLocation) {
615 616 617
  String16 breakpointId = generateBreakpointId(
      BreakpointType::kByScriptId, location->getScriptId(),
      location->getLineNumber(), location->getColumnNumber(0));
618 619
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);

620 621
  if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) !=
      m_breakpointIdToDebuggerBreakpointIds.end()) {
622 623
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
624
  }
625 626 627 628
  *actualLocation = setBreakpointImpl(breakpointId, location->getScriptId(),
                                      optionalCondition.fromMaybe(String16()),
                                      location->getLineNumber(),
                                      location->getColumnNumber(0));
629 630
  if (!*actualLocation)
    return Response::ServerError("Could not resolve breakpoint");
631
  *outBreakpointId = breakpointId;
632
  return Response::Success();
633 634
}

635 636 637
Response V8DebuggerAgentImpl::setBreakpointOnFunctionCall(
    const String16& functionObjectId, Maybe<String16> optionalCondition,
    String16* outBreakpointId) {
638 639
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);

640 641
  InjectedScript::ObjectScope scope(m_session, functionObjectId);
  Response response = scope.initialize();
642
  if (!response.IsSuccess()) return response;
643
  if (!scope.object()->IsFunction()) {
644
    return Response::ServerError("Could not find function with given id");
645 646 647 648 649 650 651
  }
  v8::Local<v8::Function> function =
      v8::Local<v8::Function>::Cast(scope.object());
  String16 breakpointId =
      generateBreakpointId(BreakpointType::kBreakpointAtEntry, function);
  if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) !=
      m_breakpointIdToDebuggerBreakpointIds.end()) {
652 653
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
654 655 656 657 658
  }
  v8::Local<v8::String> condition =
      toV8String(m_isolate, optionalCondition.fromMaybe(String16()));
  setBreakpointImpl(breakpointId, function, condition);
  *outBreakpointId = breakpointId;
659
  return Response::Success();
660 661
}

662 663
Response V8DebuggerAgentImpl::setInstrumentationBreakpoint(
    const String16& instrumentation, String16* outBreakpointId) {
664
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
665 666 667 668
  String16 breakpointId = generateInstrumentationBreakpointId(instrumentation);
  protocol::DictionaryValue* breakpoints = getOrCreateObject(
      m_state, DebuggerAgentState::instrumentationBreakpoints);
  if (breakpoints->get(breakpointId)) {
669 670
    return Response::ServerError(
        "Instrumentation breakpoint is already enabled.");
671 672 673
  }
  breakpoints->setBoolean(breakpointId, true);
  *outBreakpointId = breakpointId;
674
  return Response::Success();
675 676
}

677
Response V8DebuggerAgentImpl::removeBreakpoint(const String16& breakpointId) {
678
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
679 680 681
  BreakpointType type;
  String16 selector;
  if (!parseBreakpointId(breakpointId, &type, &selector)) {
682
    return Response::Success();
683 684
  }
  protocol::DictionaryValue* breakpoints = nullptr;
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
  switch (type) {
    case BreakpointType::kByUrl: {
      protocol::DictionaryValue* breakpointsByUrl =
          m_state->getObject(DebuggerAgentState::breakpointsByUrl);
      if (breakpointsByUrl) {
        breakpoints = breakpointsByUrl->getObject(selector);
      }
    } break;
    case BreakpointType::kByScriptHash: {
      protocol::DictionaryValue* breakpointsByScriptHash =
          m_state->getObject(DebuggerAgentState::breakpointsByScriptHash);
      if (breakpointsByScriptHash) {
        breakpoints = breakpointsByScriptHash->getObject(selector);
      }
    } break;
    case BreakpointType::kByUrlRegex:
      breakpoints = m_state->getObject(DebuggerAgentState::breakpointsByRegex);
      break;
703 704 705 706
    case BreakpointType::kInstrumentationBreakpoint:
      breakpoints =
          m_state->getObject(DebuggerAgentState::instrumentationBreakpoints);
      break;
707 708
    default:
      break;
709 710 711 712 713
  }
  if (breakpoints) breakpoints->remove(breakpointId);
  protocol::DictionaryValue* breakpointHints =
      m_state->getObject(DebuggerAgentState::breakpointHints);
  if (breakpointHints) breakpointHints->remove(breakpointId);
714 715 716 717 718 719

  // Get a list of scripts to remove breakpoints.
  // TODO(duongn): we can do better here if from breakpoint id we can tell it is
  // not Wasm breakpoint.
  std::vector<V8DebuggerScript*> scripts;
  for (const auto& scriptIter : m_scripts) {
720 721 722 723 724
    const bool scriptSelectorMatch =
        matches(m_inspector, *scriptIter.second, type, selector);
    const bool isInstrumentation =
        type == BreakpointType::kInstrumentationBreakpoint;
    if (!scriptSelectorMatch && !isInstrumentation) continue;
725
    V8DebuggerScript* script = scriptIter.second.get();
726 727 728
    if (script->getLanguage() == V8DebuggerScript::Language::WebAssembly) {
      scripts.push_back(script);
    }
729 730 731
  }
  removeBreakpointImpl(breakpointId, scripts);

732
  return Response::Success();
733 734
}

735 736 737
void V8DebuggerAgentImpl::removeBreakpointImpl(
    const String16& breakpointId,
    const std::vector<V8DebuggerScript*>& scripts) {
738 739 740 741 742
  DCHECK(enabled());
  BreakpointIdToDebuggerBreakpointIdsMap::iterator
      debuggerBreakpointIdsIterator =
          m_breakpointIdToDebuggerBreakpointIds.find(breakpointId);
  if (debuggerBreakpointIdsIterator ==
743
      m_breakpointIdToDebuggerBreakpointIds.end()) {
744
    return;
745 746
  }
  for (const auto& id : debuggerBreakpointIdsIterator->second) {
747
#if V8_ENABLE_WEBASSEMBLY
748 749 750
    for (auto& script : scripts) {
      script->removeWasmBreakpoint(id);
    }
751
#endif  // V8_ENABLE_WEBASSEMBLY
752
    v8::debug::RemoveBreakpoint(m_isolate, id);
753
    m_debuggerBreakpointIdToBreakpointId.erase(id);
754 755 756 757
  }
  m_breakpointIdToDebuggerBreakpointIds.erase(breakpointId);
}

758 759
Response V8DebuggerAgentImpl::getPossibleBreakpoints(
    std::unique_ptr<protocol::Debugger::Location> start,
760
    Maybe<protocol::Debugger::Location> end, Maybe<bool> restrictToFunction,
761 762
    std::unique_ptr<protocol::Array<protocol::Debugger::BreakLocation>>*
        locations) {
763 764 765
  String16 scriptId = start->getScriptId();

  if (start->getLineNumber() < 0 || start->getColumnNumber(0) < 0)
766
    return Response::ServerError(
767 768
        "start.lineNumber and start.columnNumber should be >= 0");

769 770 771
  v8::debug::Location v8Start(start->getLineNumber(),
                              start->getColumnNumber(0));
  v8::debug::Location v8End;
772 773
  if (end.isJust()) {
    if (end.fromJust()->getScriptId() != scriptId)
774 775
      return Response::ServerError(
          "Locations should contain the same scriptId");
776 777 778
    int line = end.fromJust()->getLineNumber();
    int column = end.fromJust()->getColumnNumber(0);
    if (line < 0 || column < 0)
779
      return Response::ServerError(
780
          "end.lineNumber and end.columnNumber should be >= 0");
781
    v8End = v8::debug::Location(line, column);
782 783
  }
  auto it = m_scripts.find(scriptId);
784
  if (it == m_scripts.end()) return Response::ServerError("Script not found");
785
  std::vector<v8::debug::BreakLocation> v8Locations;
786 787
  {
    v8::HandleScope handleScope(m_isolate);
788 789 790
    int contextId = it->second->executionContextId();
    InspectedContext* inspected = m_inspector->getContext(contextId);
    if (!inspected) {
791
      return Response::ServerError("Cannot retrive script context");
792 793
    }
    v8::Context::Scope contextScope(inspected->context());
794 795
    v8::MicrotasksScope microtasks(m_isolate,
                                   v8::MicrotasksScope::kDoNotRunMicrotasks);
796 797 798
    v8::TryCatch tryCatch(m_isolate);
    it->second->getPossibleBreakpoints(
        v8Start, v8End, restrictToFunction.fromMaybe(false), &v8Locations);
799
  }
800

801 802
  *locations =
      std::make_unique<protocol::Array<protocol::Debugger::BreakLocation>>();
803 804 805 806 807 808

  // TODO(1106269): Return an error instead of capping the number of
  // breakpoints.
  const size_t numBreakpointsToSend =
      std::min(v8Locations.size(), kMaxNumBreakpoints);
  for (size_t i = 0; i < numBreakpointsToSend; ++i) {
809 810 811 812 813 814 815 816 817
    std::unique_ptr<protocol::Debugger::BreakLocation> breakLocation =
        protocol::Debugger::BreakLocation::create()
            .setScriptId(scriptId)
            .setLineNumber(v8Locations[i].GetLineNumber())
            .setColumnNumber(v8Locations[i].GetColumnNumber())
            .build();
    if (v8Locations[i].type() != v8::debug::kCommonBreakLocation) {
      breakLocation->setType(breakLocationType(v8Locations[i].type()));
    }
818
    (*locations)->emplace_back(std::move(breakLocation));
819
  }
820
  return Response::Success();
821 822
}

823
Response V8DebuggerAgentImpl::continueToLocation(
824 825
    std::unique_ptr<protocol::Debugger::Location> location,
    Maybe<String16> targetCallFrames) {
826 827
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
828 829
  ScriptsMap::iterator it = m_scripts.find(location->getScriptId());
  if (it == m_scripts.end()) {
830
    return Response::ServerError("Cannot continue to specified location");
831 832 833 834 835
  }
  V8DebuggerScript* script = it->second.get();
  int contextId = script->executionContextId();
  InspectedContext* inspected = m_inspector->getContext(contextId);
  if (!inspected)
836
    return Response::ServerError("Cannot continue to specified location");
837
  v8::HandleScope handleScope(m_isolate);
838
  v8::Context::Scope contextScope(inspected->context());
839
  return m_debugger->continueToLocation(
840
      m_session->contextGroupId(), script, std::move(location),
841 842
      targetCallFrames.fromMaybe(
          protocol::Debugger::ContinueToLocation::TargetCallFramesEnum::Any));
843 844
}

845 846 847 848 849
Response V8DebuggerAgentImpl::getStackTrace(
    std::unique_ptr<protocol::Runtime::StackTraceId> inStackTraceId,
    std::unique_ptr<protocol::Runtime::StackTrace>* outStackTrace) {
  bool isOk = false;
  int64_t id = inStackTraceId->getId().toInteger64(&isOk);
850
  if (!isOk) return Response::ServerError("Invalid stack trace id");
851

852
  internal::V8DebuggerId debuggerId;
853
  if (inStackTraceId->hasDebuggerId()) {
854 855
    debuggerId =
        internal::V8DebuggerId(inStackTraceId->getDebuggerId(String16()));
856 857 858
  } else {
    debuggerId = m_debugger->debuggerIdFor(m_session->contextGroupId());
  }
859 860
  if (!debuggerId.isValid())
    return Response::ServerError("Invalid stack trace id");
861 862 863

  V8StackTraceId v8StackTraceId(id, debuggerId.pair());
  if (v8StackTraceId.IsInvalid())
864
    return Response::ServerError("Invalid stack trace id");
865 866 867
  auto stack =
      m_debugger->stackTraceFor(m_session->contextGroupId(), v8StackTraceId);
  if (!stack) {
868
    return Response::ServerError("Stack trace with given id is not found");
869
  }
870 871
  *outStackTrace = stack->buildInspectorObject(
      m_debugger, m_debugger->maxAsyncCallChainDepth());
872
  return Response::Success();
873 874
}

875 876 877 878
bool V8DebuggerAgentImpl::isFunctionBlackboxed(const String16& scriptId,
                                               const v8::debug::Location& start,
                                               const v8::debug::Location& end) {
  ScriptsMap::iterator it = m_scripts.find(scriptId);
879 880 881 882 883 884 885 886 887 888
  if (it == m_scripts.end()) {
    // Unknown scripts are blackboxed.
    return true;
  }
  if (m_blackboxPattern) {
    const String16& scriptSourceURL = it->second->sourceURL();
    if (!scriptSourceURL.isEmpty() &&
        m_blackboxPattern->match(scriptSourceURL) != -1)
      return true;
  }
889
  auto itBlackboxedPositions = m_blackboxedPositions.find(scriptId);
890 891 892 893
  if (itBlackboxedPositions == m_blackboxedPositions.end()) return false;

  const std::vector<std::pair<int, int>>& ranges =
      itBlackboxedPositions->second;
894
  auto itStartRange = std::lower_bound(
895
      ranges.begin(), ranges.end(),
896 897 898 899 900 901
      std::make_pair(start.GetLineNumber(), start.GetColumnNumber()),
      positionComparator);
  auto itEndRange = std::lower_bound(
      itStartRange, ranges.end(),
      std::make_pair(end.GetLineNumber(), end.GetColumnNumber()),
      positionComparator);
902 903 904
  // Ranges array contains positions in script where blackbox state is changed.
  // [(0,0) ... ranges[0]) isn't blackboxed, [ranges[0] ... ranges[1]) is
  // blackboxed...
905 906
  return itStartRange == itEndRange &&
         std::distance(ranges.begin(), itStartRange) % 2;
907 908
}

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
bool V8DebuggerAgentImpl::shouldBeSkipped(const String16& scriptId, int line,
                                          int column) {
  if (m_skipList.empty()) return false;

  auto it = m_skipList.find(scriptId);
  if (it == m_skipList.end()) return false;

  const std::vector<std::pair<int, int>>& ranges = it->second;
  DCHECK(!ranges.empty());
  const std::pair<int, int> location = std::make_pair(line, column);
  auto itLowerBound = std::lower_bound(ranges.begin(), ranges.end(), location,
                                       positionComparator);

  bool shouldSkip = false;
  if (itLowerBound != ranges.end()) {
    // Skip lists are defined as pairs of locations that specify the
    // start and the end of ranges to skip: [ranges[0], ranges[1], ..], where
    // locations in [ranges[0], ranges[1]) should be skipped, i.e.
    // [(lineStart, columnStart), (lineEnd, columnEnd)).
    const bool isSameAsLowerBound = location == *itLowerBound;
    const bool isUnevenIndex = (itLowerBound - ranges.begin()) % 2;
    shouldSkip = isSameAsLowerBound ^ isUnevenIndex;
  }

  return shouldSkip;
}

936 937 938 939
bool V8DebuggerAgentImpl::acceptsPause(bool isOOMBreak) const {
  return enabled() && (isOOMBreak || !m_skipAllPauses);
}

940
std::unique_ptr<protocol::Debugger::Location>
941 942 943 944
V8DebuggerAgentImpl::setBreakpointImpl(const String16& breakpointId,
                                       const String16& scriptId,
                                       const String16& condition,
                                       int lineNumber, int columnNumber) {
945
  v8::HandleScope handles(m_isolate);
946
  DCHECK(enabled());
947 948

  ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
949
  if (scriptIterator == m_scripts.end()) return nullptr;
950
  V8DebuggerScript* script = scriptIterator->second.get();
951

952
  v8::debug::BreakpointId debuggerBreakpointId;
953
  v8::debug::Location location(lineNumber, columnNumber);
954 955 956 957 958 959
  int contextId = script->executionContextId();
  InspectedContext* inspected = m_inspector->getContext(contextId);
  if (!inspected) return nullptr;

  {
    v8::Context::Scope contextScope(inspected->context());
960
    if (!script->setBreakpoint(condition, &location, &debuggerBreakpointId)) {
961 962 963
      return nullptr;
    }
  }
964

965
  m_debuggerBreakpointIdToBreakpointId[debuggerBreakpointId] = breakpointId;
966 967
  m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(
      debuggerBreakpointId);
968 969 970 971 972 973

  return protocol::Debugger::Location::create()
      .setScriptId(scriptId)
      .setLineNumber(location.GetLineNumber())
      .setColumnNumber(location.GetColumnNumber())
      .build();
974 975
}

976 977 978 979 980 981 982 983 984 985 986 987 988
void V8DebuggerAgentImpl::setBreakpointImpl(const String16& breakpointId,
                                            v8::Local<v8::Function> function,
                                            v8::Local<v8::String> condition) {
  v8::debug::BreakpointId debuggerBreakpointId;
  if (!v8::debug::SetFunctionBreakpoint(function, condition,
                                        &debuggerBreakpointId)) {
    return;
  }
  m_debuggerBreakpointIdToBreakpointId[debuggerBreakpointId] = breakpointId;
  m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(
      debuggerBreakpointId);
}

989 990 991
Response V8DebuggerAgentImpl::searchInContent(
    const String16& scriptId, const String16& query,
    Maybe<bool> optionalCaseSensitive, Maybe<bool> optionalIsRegex,
992 993 994
    std::unique_ptr<Array<protocol::Debugger::SearchMatch>>* results) {
  v8::HandleScope handles(m_isolate);
  ScriptsMap::iterator it = m_scripts.find(scriptId);
995
  if (it == m_scripts.end())
996
    return Response::ServerError("No script for id: " + scriptId.utf8());
997

998 999 1000 1001
  *results = std::make_unique<protocol::Array<protocol::Debugger::SearchMatch>>(
      searchInTextByLinesImpl(m_session, it->second->source(0), query,
                              optionalCaseSensitive.fromMaybe(false),
                              optionalIsRegex.fromMaybe(false)));
1002
  return Response::Success();
1003 1004
}

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
namespace {
const char* buildStatus(v8::debug::LiveEditResult::Status status) {
  switch (status) {
    case v8::debug::LiveEditResult::OK:
      return protocol::Debugger::SetScriptSource::StatusEnum::Ok;
    case v8::debug::LiveEditResult::COMPILE_ERROR:
      return protocol::Debugger::SetScriptSource::StatusEnum::CompileError;
    case v8::debug::LiveEditResult::BLOCKED_BY_ACTIVE_FUNCTION:
      return protocol::Debugger::SetScriptSource::StatusEnum::
          BlockedByActiveFunction;
    case v8::debug::LiveEditResult::BLOCKED_BY_RUNNING_GENERATOR:
      return protocol::Debugger::SetScriptSource::StatusEnum::
          BlockedByActiveGenerator;
  }
}
}  // namespace

1022 1023
Response V8DebuggerAgentImpl::setScriptSource(
    const String16& scriptId, const String16& newContent, Maybe<bool> dryRun,
1024
    Maybe<bool> allowTopFrameEditing,
1025
    Maybe<protocol::Array<protocol::Debugger::CallFrame>>* newCallFrames,
1026 1027
    Maybe<bool>* stackChanged,
    Maybe<protocol::Runtime::StackTrace>* asyncStackTrace,
1028
    Maybe<protocol::Runtime::StackTraceId>* asyncStackTraceId, String16* status,
1029
    Maybe<protocol::Runtime::ExceptionDetails>* optOutCompileError) {
1030
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1031

1032 1033
  ScriptsMap::iterator it = m_scripts.find(scriptId);
  if (it == m_scripts.end()) {
1034
    return Response::ServerError("No script with given id found");
1035
  }
1036
  int contextId = it->second->executionContextId();
1037
  InspectedContext* inspected = m_inspector->getContext(contextId);
1038 1039 1040 1041 1042 1043
  if (!inspected) {
    return Response::InternalError();
  }
  v8::HandleScope handleScope(m_isolate);
  v8::Local<v8::Context> context = inspected->context();
  v8::Context::Scope contextScope(context);
1044
  const bool allowTopFrameLiveEditing = allowTopFrameEditing.fromMaybe(false);
1045 1046

  v8::debug::LiveEditResult result;
1047 1048
  it->second->setSource(newContent, dryRun.fromMaybe(false),
                        allowTopFrameLiveEditing, &result);
1049 1050
  *status = buildStatus(result.status);
  if (result.status == v8::debug::LiveEditResult::COMPILE_ERROR) {
1051 1052 1053
    *optOutCompileError =
        protocol::Runtime::ExceptionDetails::create()
            .setExceptionId(m_inspector->nextExceptionId())
1054
            .setText(toProtocolString(m_isolate, result.message))
1055 1056 1057 1058 1059
            .setLineNumber(result.line_number != -1 ? result.line_number - 1
                                                    : 0)
            .setColumnNumber(result.column_number != -1 ? result.column_number
                                                        : 0)
            .build();
1060
    return Response::Success();
1061
  }
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

  if (result.restart_top_frame_required) {
    CHECK(allowTopFrameLiveEditing);
    // Nothing could have happened to the JS stack since the live edit so
    // restarting the top frame is guaranteed to be successful.
    CHECK(m_debugger->restartFrame(m_session->contextGroupId(),
                                   /* callFrameOrdinal */ 0));
    m_session->releaseObjectGroup(kBacktraceObjectGroup);
  }

1072
  return Response::Success();
1073 1074
}

1075
Response V8DebuggerAgentImpl::restartFrame(
1076
    const String16& callFrameId, Maybe<String16> mode,
1077
    std::unique_ptr<Array<CallFrame>>* newCallFrames,
1078 1079
    Maybe<protocol::Runtime::StackTrace>* asyncStackTrace,
    Maybe<protocol::Runtime::StackTraceId>* asyncStackTraceId) {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
  if (!mode.isJust()) {
    return Response::ServerError(
        "Restarting frame without 'mode' not supported");
  }
  CHECK_EQ(mode.fromJust(),
           protocol::Debugger::RestartFrame::ModeEnum::StepInto);

  InjectedScript::CallFrameScope scope(m_session, callFrameId);
  Response response = scope.initialize();
  if (!response.IsSuccess()) return response;
  int callFrameOrdinal = static_cast<int>(scope.frameOrdinal());

  if (!m_debugger->restartFrame(m_session->contextGroupId(),
                                callFrameOrdinal)) {
    return Response::ServerError("Restarting frame failed");
  }
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
  *newCallFrames = std::make_unique<Array<CallFrame>>();
  return Response::Success();
1100 1101
}

1102 1103 1104
Response V8DebuggerAgentImpl::getScriptSource(
    const String16& scriptId, String16* scriptSource,
    Maybe<protocol::Binary>* bytecode) {
1105
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1106
  ScriptsMap::iterator it = m_scripts.find(scriptId);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  if (it == m_scripts.end()) {
    auto cachedScriptIt =
        std::find_if(m_cachedScripts.begin(), m_cachedScripts.end(),
                     [&scriptId](const CachedScript& cachedScript) {
                       return cachedScript.scriptId == scriptId;
                     });
    if (cachedScriptIt != m_cachedScripts.end()) {
      *scriptSource = cachedScriptIt->source;
      *bytecode = protocol::Binary::fromSpan(cachedScriptIt->bytecode.data(),
                                             cachedScriptIt->bytecode.size());
      return Response::Success();
    }
1119
    return Response::ServerError("No script for id: " + scriptId.utf8());
1120
  }
1121
  *scriptSource = it->second->source(0);
1122
#if V8_ENABLE_WEBASSEMBLY
1123 1124
  v8::MemorySpan<const uint8_t> span;
  if (it->second->wasmBytecode().To(&span)) {
1125 1126 1127
    if (span.size() > kWasmBytecodeMaxLength) {
      return Response::ServerError(kWasmBytecodeExceedsTransferLimit);
    }
1128 1129
    *bytecode = protocol::Binary::fromSpan(span.data(), span.size());
  }
1130
#endif  // V8_ENABLE_WEBASSEMBLY
1131
  return Response::Success();
1132 1133
}

1134 1135
Response V8DebuggerAgentImpl::getWasmBytecode(const String16& scriptId,
                                              protocol::Binary* bytecode) {
1136
#if V8_ENABLE_WEBASSEMBLY
1137
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1138 1139
  ScriptsMap::iterator it = m_scripts.find(scriptId);
  if (it == m_scripts.end())
1140
    return Response::ServerError("No script for id: " + scriptId.utf8());
1141 1142
  v8::MemorySpan<const uint8_t> span;
  if (!it->second->wasmBytecode().To(&span))
1143 1144
    return Response::ServerError("Script with id " + scriptId.utf8() +
                                 " is not WebAssembly");
1145 1146 1147
  if (span.size() > kWasmBytecodeMaxLength) {
    return Response::ServerError(kWasmBytecodeExceedsTransferLimit);
  }
1148
  *bytecode = protocol::Binary::fromSpan(span.data(), span.size());
1149
  return Response::Success();
1150 1151 1152
#else
  return Response::ServerError("WebAssembly is disabled");
#endif  // V8_ENABLE_WEBASSEMBLY
1153 1154
}

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
void V8DebuggerAgentImpl::pushBreakDetails(
    const String16& breakReason,
    std::unique_ptr<protocol::DictionaryValue> breakAuxData) {
  m_breakReason.push_back(std::make_pair(breakReason, std::move(breakAuxData)));
}

void V8DebuggerAgentImpl::popBreakDetails() {
  if (m_breakReason.empty()) return;
  m_breakReason.pop_back();
}

void V8DebuggerAgentImpl::clearBreakDetails() {
  std::vector<BreakReason> emptyBreakReason;
  m_breakReason.swap(emptyBreakReason);
}

1171 1172 1173
void V8DebuggerAgentImpl::schedulePauseOnNextStatement(
    const String16& breakReason,
    std::unique_ptr<protocol::DictionaryValue> data) {
1174
  if (isPaused() || !acceptsPause(false) || !m_breakpointsActive) return;
1175
  if (m_breakReason.empty()) {
1176
    m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
1177
  }
1178
  pushBreakDetails(breakReason, std::move(data));
1179 1180 1181
}

void V8DebuggerAgentImpl::cancelPauseOnNextStatement() {
1182
  if (isPaused() || !acceptsPause(false) || !m_breakpointsActive) return;
1183
  if (m_breakReason.size() == 1) {
1184
    m_debugger->setPauseOnNextCall(false, m_session->contextGroupId());
1185 1186
  }
  popBreakDetails();
1187 1188
}

1189
Response V8DebuggerAgentImpl::pause() {
1190 1191
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (isPaused()) return Response::Success();
1192

1193 1194 1195
  if (m_debugger->canBreakProgram()) {
    m_debugger->interruptAndBreak(m_session->contextGroupId());
  } else {
1196
    pushBreakDetails(protocol::Debugger::Paused::ReasonEnum::Other, nullptr);
1197
    m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
1198
  }
1199

1200
  return Response::Success();
1201 1202
}

1203
Response V8DebuggerAgentImpl::resume(Maybe<bool> terminateOnResume) {
1204
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1205
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1206 1207
  m_debugger->continueProgram(m_session->contextGroupId(),
                              terminateOnResume.fromMaybe(false));
1208
  return Response::Success();
1209 1210
}

1211 1212
Response V8DebuggerAgentImpl::stepOver(
    Maybe<protocol::Array<protocol::Debugger::LocationRange>> inSkipList) {
1213
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1214 1215 1216 1217 1218 1219 1220 1221

  if (inSkipList.isJust()) {
    const Response res = processSkipList(inSkipList.fromJust());
    if (res.IsError()) return res;
  } else {
    m_skipList.clear();
  }

1222
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1223
  m_debugger->stepOverStatement(m_session->contextGroupId());
1224
  return Response::Success();
1225 1226
}

1227 1228 1229
Response V8DebuggerAgentImpl::stepInto(
    Maybe<bool> inBreakOnAsyncCall,
    Maybe<protocol::Array<protocol::Debugger::LocationRange>> inSkipList) {
1230
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1231 1232 1233 1234 1235 1236 1237 1238

  if (inSkipList.isJust()) {
    const Response res = processSkipList(inSkipList.fromJust());
    if (res.IsError()) return res;
  } else {
    m_skipList.clear();
  }

1239
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1240 1241
  m_debugger->stepIntoStatement(m_session->contextGroupId(),
                                inBreakOnAsyncCall.fromMaybe(false));
1242
  return Response::Success();
1243 1244
}

1245
Response V8DebuggerAgentImpl::stepOut() {
1246
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1247
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1248
  m_debugger->stepOutOfFunction(m_session->contextGroupId());
1249
  return Response::Success();
1250 1251
}

1252 1253
Response V8DebuggerAgentImpl::pauseOnAsyncCall(
    std::unique_ptr<protocol::Runtime::StackTraceId> inParentStackTraceId) {
1254
  // Deprecated, just return OK.
1255
  return Response::Success();
1256 1257
}

1258 1259
Response V8DebuggerAgentImpl::setPauseOnExceptions(
    const String16& stringPauseState) {
1260
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1261
  v8::debug::ExceptionBreakState pauseState;
1262
  if (stringPauseState == "none") {
1263
    pauseState = v8::debug::NoBreakOnException;
1264
  } else if (stringPauseState == "all") {
1265
    pauseState = v8::debug::BreakOnAnyException;
1266
  } else if (stringPauseState == "uncaught") {
1267
    pauseState = v8::debug::BreakOnUncaughtException;
1268
  } else {
1269 1270
    return Response::ServerError("Unknown pause on exceptions mode: " +
                                 stringPauseState.utf8());
1271
  }
1272
  setPauseOnExceptionsImpl(pauseState);
1273
  return Response::Success();
1274 1275
}

1276
void V8DebuggerAgentImpl::setPauseOnExceptionsImpl(int pauseState) {
1277 1278
  // TODO(dgozman): this changes the global state and forces all context groups
  // to pause. We should make this flag be per-context-group.
1279
  m_debugger->setPauseOnExceptionsState(
1280
      static_cast<v8::debug::ExceptionBreakState>(pauseState));
1281
  m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, pauseState);
1282 1283
}

1284 1285 1286 1287
Response V8DebuggerAgentImpl::evaluateOnCallFrame(
    const String16& callFrameId, const String16& expression,
    Maybe<String16> objectGroup, Maybe<bool> includeCommandLineAPI,
    Maybe<bool> silent, Maybe<bool> returnByValue, Maybe<bool> generatePreview,
1288 1289
    Maybe<bool> throwOnSideEffect, Maybe<double> timeout,
    std::unique_ptr<RemoteObject>* result,
1290
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
1291
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1292
  InjectedScript::CallFrameScope scope(m_session, callFrameId);
1293
  Response response = scope.initialize();
1294
  if (!response.IsSuccess()) return response;
1295
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
1296 1297
  if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole();

1298 1299 1300
  int frameOrdinal = static_cast<int>(scope.frameOrdinal());
  auto it = v8::debug::StackTraceIterator::Create(m_isolate, frameOrdinal);
  if (it->Done()) {
1301
    return Response::ServerError("Could not find call frame with given id");
1302
  }
1303 1304 1305

  v8::MaybeLocal<v8::Value> maybeResultValue;
  {
1306
    V8InspectorImpl::EvaluateScope evaluateScope(scope);
1307 1308
    if (timeout.isJust()) {
      response = evaluateScope.setTimeout(timeout.fromJust() / 1000.0);
1309
      if (!response.IsSuccess()) return response;
1310 1311 1312 1313
    }
    maybeResultValue = it->Evaluate(toV8String(m_isolate, expression),
                                    throwOnSideEffect.fromMaybe(false));
  }
1314 1315
  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
1316
  response = scope.initialize();
1317
  if (!response.IsSuccess()) return response;
1318 1319 1320
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
1321
  return scope.injectedScript()->wrapEvaluateResult(
1322
      maybeResultValue, scope.tryCatch(), objectGroup.fromMaybe(""), mode,
1323
      throwOnSideEffect.fromMaybe(false), result, exceptionDetails);
1324 1325
}

1326 1327
Response V8DebuggerAgentImpl::setVariableValue(
    int scopeNumber, const String16& variableName,
1328 1329
    std::unique_ptr<protocol::Runtime::CallArgument> newValueArgument,
    const String16& callFrameId) {
1330 1331
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1332
  InjectedScript::CallFrameScope scope(m_session, callFrameId);
1333
  Response response = scope.initialize();
1334
  if (!response.IsSuccess()) return response;
1335
  v8::Local<v8::Value> newValue;
1336 1337
  response = scope.injectedScript()->resolveCallArgument(newValueArgument.get(),
                                                         &newValue);
1338
  if (!response.IsSuccess()) return response;
1339

1340 1341 1342
  int frameOrdinal = static_cast<int>(scope.frameOrdinal());
  auto it = v8::debug::StackTraceIterator::Create(m_isolate, frameOrdinal);
  if (it->Done()) {
1343
    return Response::ServerError("Could not find call frame with given id");
1344 1345 1346 1347 1348 1349 1350
  }
  auto scopeIterator = it->GetScopeIterator();
  while (!scopeIterator->Done() && scopeNumber > 0) {
    --scopeNumber;
    scopeIterator->Advance();
  }
  if (scopeNumber != 0) {
1351
    return Response::ServerError("Could not find scope with given number");
1352
  }
1353

1354 1355 1356
  if (!scopeIterator->SetVariableValue(toV8String(m_isolate, variableName),
                                       newValue) ||
      scope.tryCatch().HasCaught()) {
1357
    return Response::InternalError();
1358
  }
1359
  return Response::Success();
1360 1361
}

1362 1363
Response V8DebuggerAgentImpl::setReturnValue(
    std::unique_ptr<protocol::Runtime::CallArgument> protocolNewValue) {
1364 1365
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1366
  v8::HandleScope handleScope(m_isolate);
1367 1368
  auto iterator = v8::debug::StackTraceIterator::Create(m_isolate);
  if (iterator->Done()) {
1369
    return Response::ServerError("Could not find top call frame");
1370 1371
  }
  if (iterator->GetReturnValue().IsEmpty()) {
1372
    return Response::ServerError(
1373 1374 1375 1376
        "Could not update return value at non-return position");
  }
  InjectedScript::ContextScope scope(m_session, iterator->GetContextId());
  Response response = scope.initialize();
1377
  if (!response.IsSuccess()) return response;
1378 1379 1380
  v8::Local<v8::Value> newValue;
  response = scope.injectedScript()->resolveCallArgument(protocolNewValue.get(),
                                                         &newValue);
1381
  if (!response.IsSuccess()) return response;
1382
  v8::debug::SetReturnValue(m_isolate, newValue);
1383
  return Response::Success();
1384 1385
}

1386
Response V8DebuggerAgentImpl::setAsyncCallStackDepth(int depth) {
1387
  if (!enabled() && !m_session->runtimeAgent()->enabled()) {
1388
    return Response::ServerError(kDebuggerNotEnabled);
1389
  }
1390 1391
  m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, depth);
  m_debugger->setAsyncCallStackDepth(this, depth);
1392
  return Response::Success();
1393 1394
}

1395
Response V8DebuggerAgentImpl::setBlackboxPatterns(
1396
    std::unique_ptr<protocol::Array<String16>> patterns) {
1397
  if (patterns->empty()) {
1398
    m_blackboxPattern = nullptr;
1399
    resetBlackboxedStateCache();
1400
    m_state->remove(DebuggerAgentState::blackboxPattern);
1401
    return Response::Success();
1402 1403 1404 1405
  }

  String16Builder patternBuilder;
  patternBuilder.append('(');
1406 1407
  for (size_t i = 0; i < patterns->size() - 1; ++i) {
    patternBuilder.append((*patterns)[i]);
1408 1409
    patternBuilder.append("|");
  }
1410
  patternBuilder.append(patterns->back());
1411 1412
  patternBuilder.append(')');
  String16 pattern = patternBuilder.toString();
1413
  Response response = setBlackboxPattern(pattern);
1414
  if (!response.IsSuccess()) return response;
1415
  resetBlackboxedStateCache();
1416
  m_state->setString(DebuggerAgentState::blackboxPattern, pattern);
1417
  return Response::Success();
1418 1419
}

1420
Response V8DebuggerAgentImpl::setBlackboxPattern(const String16& pattern) {
1421 1422
  std::unique_ptr<V8Regex> regex(new V8Regex(
      m_inspector, pattern, true /** caseSensitive */, false /** multiline */));
1423
  if (!regex->isValid())
1424 1425
    return Response::ServerError("Pattern parser error: " +
                                 regex->errorMessage().utf8());
1426
  m_blackboxPattern = std::move(regex);
1427
  return Response::Success();
1428 1429
}

1430 1431 1432 1433 1434 1435
void V8DebuggerAgentImpl::resetBlackboxedStateCache() {
  for (const auto& it : m_scripts) {
    it.second->resetBlackboxedStateCache();
  }
}

1436 1437
Response V8DebuggerAgentImpl::setBlackboxedRanges(
    const String16& scriptId,
1438 1439
    std::unique_ptr<protocol::Array<protocol::Debugger::ScriptPosition>>
        inPositions) {
1440 1441
  auto it = m_scripts.find(scriptId);
  if (it == m_scripts.end())
1442
    return Response::ServerError("No script with passed id.");
1443

1444
  if (inPositions->empty()) {
1445
    m_blackboxedPositions.erase(scriptId);
1446
    it->second->resetBlackboxedStateCache();
1447
    return Response::Success();
1448 1449 1450
  }

  std::vector<std::pair<int, int>> positions;
1451 1452 1453
  positions.reserve(inPositions->size());
  for (const std::unique_ptr<protocol::Debugger::ScriptPosition>& position :
       *inPositions) {
1454 1455 1456
    Response res = isValidPosition(position.get());
    if (res.IsError()) return res;

1457 1458 1459
    positions.push_back(
        std::make_pair(position->getLineNumber(), position->getColumnNumber()));
  }
1460 1461
  Response res = isValidRangeOfPositions(positions);
  if (res.IsError()) return res;
1462 1463

  m_blackboxedPositions[scriptId] = positions;
1464
  it->second->resetBlackboxedStateCache();
1465
  return Response::Success();
1466 1467
}

1468 1469
Response V8DebuggerAgentImpl::currentCallFrames(
    std::unique_ptr<Array<CallFrame>>* result) {
1470
  if (!isPaused()) {
1471
    *result = std::make_unique<Array<CallFrame>>();
1472
    return Response::Success();
1473
  }
1474
  v8::HandleScope handles(m_isolate);
1475
  *result = std::make_unique<Array<CallFrame>>();
1476 1477 1478 1479
  auto iterator = v8::debug::StackTraceIterator::Create(m_isolate);
  int frameOrdinal = 0;
  for (; !iterator->Done(); iterator->Advance(), frameOrdinal++) {
    int contextId = iterator->GetContextId();
1480 1481
    InjectedScript* injectedScript = nullptr;
    if (contextId) m_session->findInjectedScript(contextId, injectedScript);
1482 1483
    String16 callFrameId = RemoteCallFrameId::serialize(
        m_inspector->isolateId(), contextId, frameOrdinal);
1484 1485 1486 1487 1488

    v8::debug::Location loc = iterator->GetSourceLocation();

    std::unique_ptr<Array<Scope>> scopes;
    auto scopeIterator = iterator->GetScopeIterator();
1489 1490
    Response res =
        buildScopes(m_isolate, scopeIterator.get(), injectedScript, &scopes);
1491
    if (!res.IsSuccess()) return res;
1492

1493
    std::unique_ptr<RemoteObject> protocolReceiver;
1494
    if (injectedScript) {
1495 1496
      v8::Local<v8::Value> receiver;
      if (iterator->GetReceiver().ToLocal(&receiver)) {
1497 1498 1499
        res =
            injectedScript->wrapObject(receiver, kBacktraceObjectGroup,
                                       WrapMode::kNoPreview, &protocolReceiver);
1500
        if (!res.IsSuccess()) return res;
1501 1502 1503 1504 1505 1506
      }
    }
    if (!protocolReceiver) {
      protocolReceiver = RemoteObject::create()
                             .setType(RemoteObject::TypeEnum::Undefined)
                             .build();
1507 1508
    }

1509 1510 1511 1512 1513 1514 1515 1516 1517
    v8::Local<v8::debug::Script> script = iterator->GetScript();
    DCHECK(!script.IsEmpty());
    std::unique_ptr<protocol::Debugger::Location> location =
        protocol::Debugger::Location::create()
            .setScriptId(String16::fromInteger(script->Id()))
            .setLineNumber(loc.GetLineNumber())
            .setColumnNumber(loc.GetColumnNumber())
            .build();

1518 1519 1520 1521 1522
    auto frame = CallFrame::create()
                     .setCallFrameId(callFrameId)
                     .setFunctionName(toProtocolString(
                         m_isolate, iterator->GetFunctionDebugName()))
                     .setLocation(std::move(location))
1523
                     .setUrl(String16())
1524 1525
                     .setScopeChain(std::move(scopes))
                     .setThis(std::move(protocolReceiver))
1526
                     .setCanBeRestarted(iterator->CanBeRestarted())
1527
                     .build();
1528 1529 1530 1531 1532 1533 1534 1535 1536

    v8::Local<v8::Function> func = iterator->GetFunction();
    if (!func.IsEmpty()) {
      frame->setFunctionLocation(
          protocol::Debugger::Location::create()
              .setScriptId(String16::fromInteger(func->ScriptId()))
              .setLineNumber(func->GetScriptLineNumber())
              .setColumnNumber(func->GetScriptColumnNumber())
              .build());
1537 1538
    }

1539 1540 1541 1542
    v8::Local<v8::Value> returnValue = iterator->GetReturnValue();
    if (!returnValue.IsEmpty() && injectedScript) {
      std::unique_ptr<RemoteObject> value;
      res = injectedScript->wrapObject(returnValue, kBacktraceObjectGroup,
1543
                                       WrapMode::kNoPreview, &value);
1544
      if (!res.IsSuccess()) return res;
1545
      frame->setReturnValue(std::move(value));
1546
    }
1547
    (*result)->emplace_back(std::move(frame));
1548
  }
1549
  return Response::Success();
1550 1551
}

1552 1553 1554 1555 1556 1557
std::unique_ptr<protocol::Runtime::StackTrace>
V8DebuggerAgentImpl::currentAsyncStackTrace() {
  std::shared_ptr<AsyncStackTrace> asyncParent =
      m_debugger->currentAsyncParent();
  if (!asyncParent) return nullptr;
  return asyncParent->buildInspectorObject(
1558
      m_debugger, m_debugger->maxAsyncCallChainDepth() - 1);
1559 1560
}

1561 1562 1563 1564 1565 1566
std::unique_ptr<protocol::Runtime::StackTraceId>
V8DebuggerAgentImpl::currentExternalStackTrace() {
  V8StackTraceId externalParent = m_debugger->currentExternalParent();
  if (externalParent.IsInvalid()) return nullptr;
  return protocol::Runtime::StackTraceId::create()
      .setId(stackTraceIdToString(externalParent.id))
1567 1568
      .setDebuggerId(
          internal::V8DebuggerId(externalParent.debugger_id).toString())
1569 1570 1571
      .build();
}

1572
bool V8DebuggerAgentImpl::isPaused() const {
1573
  return m_debugger->isPausedInContextGroup(m_session->contextGroupId());
1574
}
1575

1576 1577 1578 1579 1580 1581 1582 1583 1584
static String16 getScriptLanguage(const V8DebuggerScript& script) {
  switch (script.getLanguage()) {
    case V8DebuggerScript::Language::WebAssembly:
      return protocol::Debugger::ScriptLanguageEnum::WebAssembly;
    case V8DebuggerScript::Language::JavaScript:
      return protocol::Debugger::ScriptLanguageEnum::JavaScript;
  }
}

1585
#if V8_ENABLE_WEBASSEMBLY
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
static const char* getDebugSymbolTypeName(
    v8::debug::WasmScript::DebugSymbolsType type) {
  switch (type) {
    case v8::debug::WasmScript::DebugSymbolsType::None:
      return v8_inspector::protocol::Debugger::DebugSymbols::TypeEnum::None;
    case v8::debug::WasmScript::DebugSymbolsType::SourceMap:
      return v8_inspector::protocol::Debugger::DebugSymbols::TypeEnum::
          SourceMap;
    case v8::debug::WasmScript::DebugSymbolsType::EmbeddedDWARF:
      return v8_inspector::protocol::Debugger::DebugSymbols::TypeEnum::
          EmbeddedDWARF;
    case v8::debug::WasmScript::DebugSymbolsType::ExternalDWARF:
      return v8_inspector::protocol::Debugger::DebugSymbols::TypeEnum::
          ExternalDWARF;
  }
}

static std::unique_ptr<protocol::Debugger::DebugSymbols> getDebugSymbols(
    const V8DebuggerScript& script) {
  v8::debug::WasmScript::DebugSymbolsType type;
  if (!script.getDebugSymbolsType().To(&type)) return {};

  std::unique_ptr<protocol::Debugger::DebugSymbols> debugSymbols =
      v8_inspector::protocol::Debugger::DebugSymbols::create()
          .setType(getDebugSymbolTypeName(type))
          .build();
  String16 externalUrl;
  if (script.getExternalDebugSymbolsURL().To(&externalUrl)) {
    debugSymbols->setExternalURL(externalUrl);
  }
  return debugSymbols;
}
1618
#endif  // V8_ENABLE_WEBASSEMBLY
1619

1620 1621 1622
void V8DebuggerAgentImpl::didParseSource(
    std::unique_ptr<V8DebuggerScript> script, bool success) {
  v8::HandleScope handles(m_isolate);
1623 1624 1625 1626 1627
  if (!success) {
    String16 scriptSource = script->source(0);
    script->setSourceURL(findSourceURL(scriptSource, false));
    script->setSourceMappingURL(findSourceMapURL(scriptSource, false));
  }
1628

1629 1630 1631 1632
  int contextId = script->executionContextId();
  int contextGroupId = m_inspector->contextGroupId(contextId);
  InspectedContext* inspected =
      m_inspector->getContext(contextGroupId, contextId);
1633
  std::unique_ptr<protocol::DictionaryValue> executionContextAuxData;
1634 1635 1636
  if (inspected) {
    // Script reused between different groups/sessions can have a stale
    // execution context id.
1637 1638 1639 1640
    const String16& aux = inspected->auxData();
    std::vector<uint8_t> cbor;
    v8_crdtp::json::ConvertJSONToCBOR(
        v8_crdtp::span<uint16_t>(aux.characters16(), aux.length()), &cbor);
1641
    executionContextAuxData = protocol::DictionaryValue::cast(
1642
        protocol::Value::parseBinary(cbor.data(), cbor.size()));
1643
  }
1644
  bool isLiveEdit = script->isLiveEdit();
1645
  bool hasSourceURLComment = script->hasSourceURLComment();
1646
  bool isModule = script->isModule();
1647 1648
  String16 scriptId = script->scriptId();
  String16 scriptURL = script->sourceURL();
1649
  String16 embedderName = script->embedderName();
1650
  String16 scriptLanguage = getScriptLanguage(*script);
1651
  Maybe<int> codeOffset;
1652 1653
  std::unique_ptr<protocol::Debugger::DebugSymbols> debugSymbols;
#if V8_ENABLE_WEBASSEMBLY
1654 1655
  if (script->getLanguage() == V8DebuggerScript::Language::WebAssembly)
    codeOffset = script->codeOffset();
1656 1657
  debugSymbols = getDebugSymbols(*script);
#endif  // V8_ENABLE_WEBASSEMBLY
1658

1659
  m_scripts[scriptId] = std::move(script);
1660 1661 1662
  // Release the strong reference to get notified when debugger is the only
  // one that holds the script. Has to be done after script added to m_scripts.
  m_scripts[scriptId]->MakeWeak();
1663 1664 1665 1666

  ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
  DCHECK(scriptIterator != m_scripts.end());
  V8DebuggerScript* scriptRef = scriptIterator->second.get();
1667 1668 1669 1670 1671
  // V8 could create functions for parsed scripts before reporting and asks
  // inspector about blackboxed state, we should reset state each time when we
  // make any change that change isFunctionBlackboxed output - adding parsed
  // script is changing.
  scriptRef->resetBlackboxedStateCache();
1672 1673

  Maybe<String16> sourceMapURLParam = scriptRef->sourceMappingURL();
1674
  Maybe<protocol::DictionaryValue> executionContextAuxDataParam(
1675 1676
      std::move(executionContextAuxData));
  const bool* isLiveEditParam = isLiveEdit ? &isLiveEdit : nullptr;
1677 1678
  const bool* hasSourceURLParam =
      hasSourceURLComment ? &hasSourceURLComment : nullptr;
1679
  const bool* isModuleParam = isModule ? &isModule : nullptr;
1680
  std::unique_ptr<V8StackTraceImpl> stack =
1681
      V8StackTraceImpl::capture(m_inspector->debugger(), 1);
1682
  std::unique_ptr<protocol::Runtime::StackTrace> stackTrace =
1683 1684 1685
      stack && !stack->isEmpty()
          ? stack->buildInspectorObjectImpl(m_debugger, 0)
          : nullptr;
1686 1687

  if (!success) {
1688
    m_frontend.scriptFailedToParse(
1689
        scriptId, scriptURL, scriptRef->startLine(), scriptRef->startColumn(),
1690
        scriptRef->endLine(), scriptRef->endColumn(), contextId,
1691
        scriptRef->hash(), std::move(executionContextAuxDataParam),
1692
        std::move(sourceMapURLParam), hasSourceURLParam, isModuleParam,
1693
        scriptRef->length(), std::move(stackTrace), std::move(codeOffset),
1694
        std::move(scriptLanguage), embedderName);
1695
    return;
1696
  }
1697

1698 1699 1700 1701 1702 1703 1704 1705
  m_frontend.scriptParsed(
      scriptId, scriptURL, scriptRef->startLine(), scriptRef->startColumn(),
      scriptRef->endLine(), scriptRef->endColumn(), contextId,
      scriptRef->hash(), std::move(executionContextAuxDataParam),
      isLiveEditParam, std::move(sourceMapURLParam), hasSourceURLParam,
      isModuleParam, scriptRef->length(), std::move(stackTrace),
      std::move(codeOffset), std::move(scriptLanguage), std::move(debugSymbols),
      embedderName);
1706

1707
  std::vector<protocol::DictionaryValue*> potentialBreakpoints;
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  if (!scriptURL.isEmpty()) {
    protocol::DictionaryValue* breakpointsByUrl =
        m_state->getObject(DebuggerAgentState::breakpointsByUrl);
    if (breakpointsByUrl) {
      potentialBreakpoints.push_back(breakpointsByUrl->getObject(scriptURL));
    }
    potentialBreakpoints.push_back(
        m_state->getObject(DebuggerAgentState::breakpointsByRegex));
  }
  protocol::DictionaryValue* breakpointsByScriptHash =
      m_state->getObject(DebuggerAgentState::breakpointsByScriptHash);
  if (breakpointsByScriptHash) {
    potentialBreakpoints.push_back(
        breakpointsByScriptHash->getObject(scriptRef->hash()));
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
  }
  protocol::DictionaryValue* breakpointHints =
      m_state->getObject(DebuggerAgentState::breakpointHints);
  for (auto breakpoints : potentialBreakpoints) {
    if (!breakpoints) continue;
    for (size_t i = 0; i < breakpoints->size(); ++i) {
      auto breakpointWithCondition = breakpoints->at(i);
      String16 breakpointId = breakpointWithCondition.first;

      BreakpointType type;
      String16 selector;
      int lineNumber = 0;
      int columnNumber = 0;
      parseBreakpointId(breakpointId, &type, &selector, &lineNumber,
                        &columnNumber);

1738
      if (!matches(m_inspector, *scriptRef, type, selector)) continue;
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
      String16 condition;
      breakpointWithCondition.second->asString(&condition);
      String16 hint;
      bool hasHint =
          breakpointHints && breakpointHints->getString(breakpointId, &hint);
      if (hasHint) {
        adjustBreakpointLocation(*scriptRef, hint, &lineNumber, &columnNumber);
      }
      std::unique_ptr<protocol::Debugger::Location> location =
          setBreakpointImpl(breakpointId, scriptId, condition, lineNumber,
                            columnNumber);
      if (location)
        m_frontend.breakpointResolved(breakpointId, std::move(location));
1752
    }
1753
  }
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
  setScriptInstrumentationBreakpointIfNeeded(scriptRef);
}

void V8DebuggerAgentImpl::setScriptInstrumentationBreakpointIfNeeded(
    V8DebuggerScript* scriptRef) {
  protocol::DictionaryValue* breakpoints =
      m_state->getObject(DebuggerAgentState::instrumentationBreakpoints);
  if (!breakpoints) return;
  bool isBlackboxed = isFunctionBlackboxed(
      scriptRef->scriptId(), v8::debug::Location(0, 0),
      v8::debug::Location(scriptRef->endLine(), scriptRef->endColumn()));
  if (isBlackboxed) return;

  String16 sourceMapURL = scriptRef->sourceMappingURL();
  String16 breakpointId = generateInstrumentationBreakpointId(
      InstrumentationEnum::BeforeScriptExecution);
  if (!breakpoints->get(breakpointId)) {
    if (sourceMapURL.isEmpty()) return;
    breakpointId = generateInstrumentationBreakpointId(
        InstrumentationEnum::BeforeScriptWithSourceMapExecution);
    if (!breakpoints->get(breakpointId)) return;
  }
  v8::debug::BreakpointId debuggerBreakpointId;
1777
  if (!scriptRef->setInstrumentationBreakpoint(&debuggerBreakpointId)) return;
1778 1779 1780 1781

  m_debuggerBreakpointIdToBreakpointId[debuggerBreakpointId] = breakpointId;
  m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(
      debuggerBreakpointId);
1782 1783
}

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
void V8DebuggerAgentImpl::didPauseOnInstrumentation(
    v8::debug::BreakpointId instrumentationId) {
  String16 breakReason = protocol::Debugger::Paused::ReasonEnum::Other;
  std::unique_ptr<protocol::DictionaryValue> breakAuxData;

  std::unique_ptr<Array<CallFrame>> protocolCallFrames;
  Response response = currentCallFrames(&protocolCallFrames);
  if (!response.IsSuccess())
    protocolCallFrames = std::make_unique<Array<CallFrame>>();

  if (m_debuggerBreakpointIdToBreakpointId.find(instrumentationId) !=
      m_debuggerBreakpointIdToBreakpointId.end()) {
    DCHECK_GT(protocolCallFrames->size(), 0);
    if (protocolCallFrames->size() > 0) {
      breakReason = protocol::Debugger::Paused::ReasonEnum::Instrumentation;
      const String16 scriptId =
          protocolCallFrames->at(0)->getLocation()->getScriptId();
      DCHECK_NE(m_scripts.find(scriptId), m_scripts.end());
      const auto& script = m_scripts[scriptId];

      breakAuxData = protocol::DictionaryValue::create();
      breakAuxData->setString("scriptId", script->scriptId());
      breakAuxData->setString("url", script->sourceURL());
      if (!script->sourceMappingURL().isEmpty()) {
        breakAuxData->setString("sourceMapURL", (script->sourceMappingURL()));
      }
    }
  }

  m_frontend.paused(std::move(protocolCallFrames), breakReason,
                    std::move(breakAuxData),
                    std::make_unique<Array<String16>>(),
                    currentAsyncStackTrace(), currentExternalStackTrace());
}

1819 1820 1821
void V8DebuggerAgentImpl::didPause(
    int contextId, v8::Local<v8::Value> exception,
    const std::vector<v8::debug::BreakpointId>& hitBreakpoints,
1822 1823
    v8::debug::ExceptionType exceptionType, bool isUncaught,
    v8::debug::BreakReasons breakReasons) {
1824 1825
  v8::HandleScope handles(m_isolate);

1826 1827
  std::vector<BreakReason> hitReasons;

1828
  if (breakReasons.contains(v8::debug::BreakReason::kOOM)) {
1829 1830
    hitReasons.push_back(
        std::make_pair(protocol::Debugger::Paused::ReasonEnum::OOM, nullptr));
1831
  } else if (breakReasons.contains(v8::debug::BreakReason::kAssert)) {
1832 1833
    hitReasons.push_back(std::make_pair(
        protocol::Debugger::Paused::ReasonEnum::Assert, nullptr));
1834
  } else if (breakReasons.contains(v8::debug::BreakReason::kException)) {
1835
    InjectedScript* injectedScript = nullptr;
1836
    m_session->findInjectedScript(contextId, injectedScript);
1837
    if (injectedScript) {
1838
      String16 breakReason =
1839
          exceptionType == v8::debug::kPromiseRejection
1840 1841
              ? protocol::Debugger::Paused::ReasonEnum::PromiseRejection
              : protocol::Debugger::Paused::ReasonEnum::Exception;
1842
      std::unique_ptr<protocol::Runtime::RemoteObject> obj;
1843 1844
      injectedScript->wrapObject(exception, kBacktraceObjectGroup,
                                 WrapMode::kNoPreview, &obj);
1845
      std::unique_ptr<protocol::DictionaryValue> breakAuxData;
1846
      if (obj) {
1847 1848 1849 1850
        std::vector<uint8_t> serialized;
        obj->AppendSerialized(&serialized);
        breakAuxData = protocol::DictionaryValue::cast(
            protocol::Value::parseBinary(serialized.data(), serialized.size()));
1851
        breakAuxData->setBoolean("uncaught", isUncaught);
1852
      }
1853 1854
      hitReasons.push_back(
          std::make_pair(breakReason, std::move(breakAuxData)));
1855 1856 1857
    }
  }

1858
  auto hitBreakpointIds = std::make_unique<Array<String16>>();
1859
  bool hitRegularBreakpoint = false;
1860
  for (const auto& id : hitBreakpoints) {
1861 1862 1863
    auto breakpointIterator = m_debuggerBreakpointIdToBreakpointId.find(id);
    if (breakpointIterator == m_debuggerBreakpointIdToBreakpointId.end()) {
      continue;
1864
    }
1865
    const String16& breakpointId = breakpointIterator->second;
1866
    hitBreakpointIds->emplace_back(breakpointId);
1867 1868
    BreakpointType type;
    parseBreakpointId(breakpointId, &type);
1869 1870 1871 1872 1873 1874
    if (type == BreakpointType::kDebugCommand) {
      hitReasons.push_back(std::make_pair(
          protocol::Debugger::Paused::ReasonEnum::DebugCommand, nullptr));
    } else {
      hitRegularBreakpoint = true;
    }
1875 1876
  }

1877 1878 1879 1880 1881
  for (size_t i = 0; i < m_breakReason.size(); ++i) {
    hitReasons.push_back(std::move(m_breakReason[i]));
  }
  clearBreakDetails();

1882 1883 1884
  // Make sure that we only include (other: nullptr) once.
  const BreakReason otherHitReason =
      std::make_pair(protocol::Debugger::Paused::ReasonEnum::Other, nullptr);
1885
  const bool otherBreakReasons =
1886
      hitRegularBreakpoint || hitBreakReasonEncodedAsOther(breakReasons);
1887 1888
  if (otherBreakReasons && std::find(hitReasons.begin(), hitReasons.end(),
                                     otherHitReason) == hitReasons.end()) {
1889 1890 1891 1892
    hitReasons.push_back(
        std::make_pair(protocol::Debugger::Paused::ReasonEnum::Other, nullptr));
  }

1893 1894 1895 1896 1897
  // We should always know why we pause: either the pause relates to this agent
  // (`hitReason` is non empty), or it relates to another agent (hit a
  // breakpoint there, or a triggered pause was scheduled by other agent).
  DCHECK(hitReasons.size() > 0 || !hitBreakpoints.empty() ||
         breakReasons.contains(v8::debug::BreakReason::kAgent));
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
  String16 breakReason = protocol::Debugger::Paused::ReasonEnum::Other;
  std::unique_ptr<protocol::DictionaryValue> breakAuxData;
  if (hitReasons.size() == 1) {
    breakReason = hitReasons[0].first;
    breakAuxData = std::move(hitReasons[0].second);
  } else if (hitReasons.size() > 1) {
    breakReason = protocol::Debugger::Paused::ReasonEnum::Ambiguous;
    std::unique_ptr<protocol::ListValue> reasons =
        protocol::ListValue::create();
    for (size_t i = 0; i < hitReasons.size(); ++i) {
      std::unique_ptr<protocol::DictionaryValue> reason =
          protocol::DictionaryValue::create();
      reason->setString("reason", hitReasons[i].first);
      if (hitReasons[i].second)
        reason->setObject("auxData", std::move(hitReasons[i].second));
      reasons->pushValue(std::move(reason));
    }
    breakAuxData = protocol::DictionaryValue::create();
    breakAuxData->setArray("reasons", std::move(reasons));
  }

1919 1920
  std::unique_ptr<Array<CallFrame>> protocolCallFrames;
  Response response = currentCallFrames(&protocolCallFrames);
1921
  if (!response.IsSuccess())
1922
    protocolCallFrames = std::make_unique<Array<CallFrame>>();
1923

1924 1925
  m_frontend.paused(std::move(protocolCallFrames), breakReason,
                    std::move(breakAuxData), std::move(hitBreakpointIds),
1926
                    currentAsyncStackTrace(), currentExternalStackTrace());
1927 1928 1929 1930
}

void V8DebuggerAgentImpl::didContinue() {
  m_frontend.resumed();
1931
  m_frontend.flush();
1932 1933 1934 1935 1936
}

void V8DebuggerAgentImpl::breakProgram(
    const String16& breakReason,
    std::unique_ptr<protocol::DictionaryValue> data) {
1937
  if (!enabled() || m_skipAllPauses || !m_debugger->canBreakProgram()) return;
1938 1939 1940
  std::vector<BreakReason> currentScheduledReason;
  currentScheduledReason.swap(m_breakReason);
  pushBreakDetails(breakReason, std::move(data));
1941 1942 1943 1944 1945 1946 1947 1948 1949

  int contextGroupId = m_session->contextGroupId();
  int sessionId = m_session->sessionId();
  V8InspectorImpl* inspector = m_inspector;
  m_debugger->breakProgram(contextGroupId);
  // Check that session and |this| are still around.
  if (!inspector->sessionById(contextGroupId, sessionId)) return;
  if (!enabled()) return;

1950 1951
  popBreakDetails();
  m_breakReason.swap(currentScheduledReason);
1952
  if (!m_breakReason.empty()) {
1953
    m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
1954
  }
1955 1956
}

1957 1958 1959
void V8DebuggerAgentImpl::setBreakpointFor(v8::Local<v8::Function> function,
                                           v8::Local<v8::String> condition,
                                           BreakpointSource source) {
1960 1961 1962
  String16 breakpointId = generateBreakpointId(
      source == DebugCommandBreakpointSource ? BreakpointType::kDebugCommand
                                             : BreakpointType::kMonitorCommand,
1963
      function);
1964 1965 1966 1967
  if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) !=
      m_breakpointIdToDebuggerBreakpointIds.end()) {
    return;
  }
1968
  setBreakpointImpl(breakpointId, function, condition);
1969 1970
}

1971 1972
void V8DebuggerAgentImpl::removeBreakpointFor(v8::Local<v8::Function> function,
                                              BreakpointSource source) {
1973 1974 1975
  String16 breakpointId = generateBreakpointId(
      source == DebugCommandBreakpointSource ? BreakpointType::kDebugCommand
                                             : BreakpointType::kMonitorCommand,
1976
      function);
1977 1978
  std::vector<V8DebuggerScript*> scripts;
  removeBreakpointImpl(breakpointId, scripts);
1979 1980 1981 1982 1983
}

void V8DebuggerAgentImpl::reset() {
  if (!enabled()) return;
  m_blackboxedPositions.clear();
1984
  resetBlackboxedStateCache();
1985
  m_skipList.clear();
1986
  m_scripts.clear();
1987
  m_cachedScripts.clear();
1988
  m_cachedScriptSize = 0;
1989
  m_debugger->allAsyncTasksCanceled();
1990 1991
}

1992 1993
void V8DebuggerAgentImpl::ScriptCollected(const V8DebuggerScript* script) {
  DCHECK_NE(m_scripts.find(script->scriptId()), m_scripts.end());
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
  std::vector<uint8_t> bytecode;
#if V8_ENABLE_WEBASSEMBLY
  v8::MemorySpan<const uint8_t> span;
  if (script->wasmBytecode().To(&span)) {
    bytecode.reserve(span.size());
    bytecode.insert(bytecode.begin(), span.data(), span.data() + span.size());
  }
#endif
  CachedScript cachedScript{script->scriptId(), script->source(0),
                            std::move(bytecode)};
  m_cachedScriptSize += cachedScript.size();
  m_cachedScripts.push_back(std::move(cachedScript));
  m_scripts.erase(script->scriptId());
2007 2008

  while (m_cachedScriptSize > m_maxScriptCacheSize) {
2009 2010 2011 2012
    const CachedScript& cachedScript = m_cachedScripts.front();
    DCHECK_GE(m_cachedScriptSize, cachedScript.size());
    m_cachedScriptSize -= cachedScript.size();
    m_cachedScripts.pop_front();
2013 2014 2015
  }
}

2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
Response V8DebuggerAgentImpl::processSkipList(
    protocol::Array<protocol::Debugger::LocationRange>* skipList) {
  std::unordered_map<String16, std::vector<std::pair<int, int>>> skipListInit;
  for (std::unique_ptr<protocol::Debugger::LocationRange>& range : *skipList) {
    protocol::Debugger::ScriptPosition* start = range->getStart();
    protocol::Debugger::ScriptPosition* end = range->getEnd();
    String16 scriptId = range->getScriptId();

    auto it = m_scripts.find(scriptId);
    if (it == m_scripts.end())
      return Response::ServerError("No script with passed id.");

    Response res = isValidPosition(start);
    if (res.IsError()) return res;

    res = isValidPosition(end);
    if (res.IsError()) return res;

    skipListInit[scriptId].emplace_back(start->getLineNumber(),
                                        start->getColumnNumber());
    skipListInit[scriptId].emplace_back(end->getLineNumber(),
                                        end->getColumnNumber());
  }

  // Verify that the skipList is sorted, and that all ranges
  // are properly defined (start comes before end).
  for (auto skipListPair : skipListInit) {
    Response res = isValidRangeOfPositions(skipListPair.second);
    if (res.IsError()) return res;
  }

  m_skipList = std::move(skipListInit);
  return Response::Success();
}
2050
}  // namespace v8_inspector