v8-debugger-agent-impl.cc 75.3 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
#include "include/v8-inspector.h"
11
#include "src/base/safe_conversions.h"
12
#include "src/debug/debug-interface.h"
13 14
#include "src/inspector/injected-script.h"
#include "src/inspector/inspected-context.h"
15
#include "src/inspector/protocol/Debugger.h"
16
#include "src/inspector/protocol/Protocol.h"
17 18 19 20 21 22 23 24 25 26
#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"
27
#include "src/inspector/v8-value-utils.h"
28

29 30 31 32 33 34
namespace v8_inspector {

using protocol::Array;
using protocol::Maybe;
using protocol::Debugger::BreakpointId;
using protocol::Debugger::CallFrame;
35
using protocol::Debugger::Scope;
36 37
using protocol::Runtime::ExceptionDetails;
using protocol::Runtime::RemoteObject;
38 39 40 41
using protocol::Runtime::ScriptId;

namespace InstrumentationEnum =
    protocol::Debugger::SetInstrumentationBreakpoint::InstrumentationEnum;
42 43 44 45 46 47

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

50 51
static const char breakpointsByRegex[] = "breakpointsByRegex";
static const char breakpointsByUrl[] = "breakpointsByUrl";
52
static const char breakpointsByScriptHash[] = "breakpointsByScriptHash";
53
static const char breakpointHints[] = "breakpointHints";
54
static const char instrumentationBreakpoints[] = "instrumentationBreakpoints";
55

56
}  // namespace DebuggerAgentState
57

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

63 64
static const size_t kBreakpointHintMaxLength = 128;
static const intptr_t kBreakpointHintMaxSearchOffset = 80 * 10;
65 66 67
// 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;
68

69 70 71 72 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.
static const size_t kWasmBytecodeMaxLength = (v8::String::kMaxLength / 4) * 3;
static const char kWasmBytecodeExceedsTransferLimit[] =
    "WebAssembly bytecode exceeds the transfer limit";

80 81
namespace {

82 83 84
enum class BreakpointType {
  kByUrl = 1,
  kByUrlRegex,
85
  kByScriptHash,
86 87
  kByScriptId,
  kDebugCommand,
88
  kMonitorCommand,
89 90
  kBreakpointAtEntry,
  kInstrumentationBreakpoint
91 92 93 94 95
};

String16 generateBreakpointId(BreakpointType type,
                              const String16& scriptSelector, int lineNumber,
                              int columnNumber) {
96
  String16Builder builder;
97 98 99
  builder.appendNumber(static_cast<int>(type));
  builder.append(':');
  builder.appendNumber(lineNumber);
100
  builder.append(':');
101
  builder.appendNumber(columnNumber);
102
  builder.append(':');
103
  builder.append(scriptSelector);
104
  return builder.toString();
105 106
}

107 108 109 110 111 112 113 114 115
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();
}

116 117 118 119 120 121 122 123 124
String16 generateInstrumentationBreakpointId(const String16& instrumentation) {
  String16Builder builder;
  builder.appendNumber(
      static_cast<int>(BreakpointType::kInstrumentationBreakpoint));
  builder.append(':');
  builder.append(instrumentation);
  return builder.toString();
}

125 126 127 128 129
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;
130 131 132

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

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  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;
}

169 170
bool positionComparator(const std::pair<int, int>& a,
                        const std::pair<int, int>& b) {
171 172 173 174
  if (a.first != b.first) return a.first < b.first;
  return a.second < b.second;
}

175 176 177
String16 breakpointHint(const V8DebuggerScript& script, int lineNumber,
                        int columnNumber) {
  int offset = script.offset(lineNumber, columnNumber);
178 179
  if (offset == V8DebuggerScript::kNoOffset) return String16();
  String16 hint =
180
      script.source(offset, kBreakpointHintMaxLength).stripWhiteSpace();
181 182 183 184 185 186 187 188
  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;
}

189 190 191
void adjustBreakpointLocation(const V8DebuggerScript& script,
                              const String16& hint, int* lineNumber,
                              int* columnNumber) {
192 193
  if (*lineNumber < script.startLine() || *lineNumber > script.endLine())
    return;
194
  if (hint.isEmpty()) return;
195
  intptr_t sourceOffset = script.offset(*lineNumber, *columnNumber);
196 197 198 199 200
  if (sourceOffset == V8DebuggerScript::kNoOffset) return;

  intptr_t searchRegionOffset = std::max(
      sourceOffset - kBreakpointHintMaxSearchOffset, static_cast<intptr_t>(0));
  size_t offset = sourceOffset - searchRegionOffset;
201 202
  String16 searchArea = script.source(searchRegionOffset,
                                      offset + kBreakpointHintMaxSearchOffset);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

  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;
218 219
  v8::debug::Location hintPosition =
      script.location(static_cast<int>(bestMatch));
220
  if (hintPosition.IsEmpty()) return;
221 222
  *lineNumber = hintPosition.GetLineNumber();
  *columnNumber = hintPosition.GetColumnNumber();
223
}
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

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();
}

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
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;
259 260
    case v8::debug::ScopeIterator::ScopeTypeWasmExpressionStack:
      return Scope::TypeEnum::WasmExpressionStack;
261 262 263 264 265
  }
  UNREACHABLE();
  return String16();
}

266
Response buildScopes(v8::Isolate* isolate, v8::debug::ScopeIterator* iterator,
267 268
                     InjectedScript* injectedScript,
                     std::unique_ptr<Array<Scope>>* scopes) {
269
  *scopes = std::make_unique<Array<Scope>>();
270 271
  if (!injectedScript) return Response::Success();
  if (iterator->Done()) return Response::Success();
272 273 274

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

275 276
  for (; !iterator->Done(); iterator->Advance()) {
    std::unique_ptr<RemoteObject> object;
277 278 279
    Response result =
        injectedScript->wrapObject(iterator->GetObject(), kBacktraceObjectGroup,
                                   WrapMode::kNoPreview, &object);
280
    if (!result.IsSuccess()) return result;
281

282 283 284 285
    auto scope = Scope::create()
                     .setType(scopeType(iterator->GetType()))
                     .setObject(std::move(object))
                     .build();
286

287 288
    String16 name = toProtocolStringWithTypeCheck(
        isolate, iterator->GetFunctionDebugName());
289 290 291
    if (!name.isEmpty()) scope->setName(name);

    if (iterator->HasLocationInfo()) {
292 293 294 295 296 297
      v8::debug::Location start = iterator->GetStartLocation();
      scope->setStartLocation(protocol::Debugger::Location::create()
                                  .setScriptId(scriptId)
                                  .setLineNumber(start.GetLineNumber())
                                  .setColumnNumber(start.GetColumnNumber())
                                  .build());
298

299 300 301 302 303 304 305
      v8::debug::Location end = iterator->GetEndLocation();
      scope->setEndLocation(protocol::Debugger::Location::create()
                                .setScriptId(scriptId)
                                .setLineNumber(end.GetLineNumber())
                                .setColumnNumber(end.GetColumnNumber())
                                .build());
    }
306
    (*scopes)->emplace_back(std::move(scope));
307
  }
308
  return Response::Success();
309 310
}

311 312 313 314 315 316 317 318 319 320
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;
}
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

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();
}
341 342
}  // namespace

343 344 345 346 347 348 349 350 351
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),
352
      m_isolate(m_inspector->isolate()) {}
353

354
V8DebuggerAgentImpl::~V8DebuggerAgentImpl() = default;
355

356
void V8DebuggerAgentImpl::enableImpl() {
357 358 359 360
  m_enabled = true;
  m_state->setBoolean(DebuggerAgentState::debuggerEnabled, true);
  m_debugger->enable();

361 362 363 364 365
  std::vector<std::unique_ptr<V8DebuggerScript>> compiledScripts =
      m_debugger->getCompiledScripts(m_session->contextGroupId(), this);
  for (auto& script : compiledScripts) {
    didParseSource(std::move(script), true);
  }
366

367 368
  m_breakpointsActive = true;
  m_debugger->setBreakpointsActive(true);
369 370 371

  if (isPaused()) {
    didPause(0, v8::Local<v8::Value>(), std::vector<v8::debug::BreakpointId>(),
372
             v8::debug::kException, false, false, false);
373
  }
374 375
}

376 377 378 379
Response V8DebuggerAgentImpl::enable(Maybe<double> maxScriptsCacheSize,
                                     String16* outDebuggerId) {
  m_maxScriptCacheSize = v8::base::saturated_cast<size_t>(
      maxScriptsCacheSize.fromMaybe(std::numeric_limits<double>::max()));
380 381
  *outDebuggerId =
      m_debugger->debuggerIdFor(m_session->contextGroupId()).toString();
382
  if (enabled()) return Response::Success();
383

384
  if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId()))
385
    return Response::ServerError("Script execution is prohibited");
386

387
  enableImpl();
388
  return Response::Success();
389 390
}

391
Response V8DebuggerAgentImpl::disable() {
392
  if (!enabled()) return Response::Success();
393

394 395
  m_state->remove(DebuggerAgentState::breakpointsByRegex);
  m_state->remove(DebuggerAgentState::breakpointsByUrl);
396
  m_state->remove(DebuggerAgentState::breakpointsByScriptHash);
397
  m_state->remove(DebuggerAgentState::breakpointHints);
398
  m_state->remove(DebuggerAgentState::instrumentationBreakpoints);
399

400
  m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState,
401
                      v8::debug::NoBreakOnException);
402 403
  m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, 0);

404 405 406 407
  if (m_breakpointsActive) {
    m_debugger->setBreakpointsActive(false);
    m_breakpointsActive = false;
  }
408
  m_blackboxedPositions.clear();
409 410
  m_blackboxPattern.reset();
  resetBlackboxedStateCache();
411
  m_skipList.clear();
412
  m_scripts.clear();
413 414
  m_cachedScriptIds.clear();
  m_cachedScriptSize = 0;
415 416
  for (const auto& it : m_debuggerBreakpointIdToBreakpointId) {
    v8::debug::RemoveBreakpoint(m_isolate, it.first);
417
  }
418
  m_breakpointIdToDebuggerBreakpointIds.clear();
419
  m_debuggerBreakpointIdToBreakpointId.clear();
420 421 422
  m_debugger->setAsyncCallStackDepth(this, 0);
  clearBreakDetails();
  m_skipAllPauses = false;
423
  m_state->setBoolean(DebuggerAgentState::skipAllPauses, false);
424 425 426
  m_state->remove(DebuggerAgentState::blackboxPattern);
  m_enabled = false;
  m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
427
  m_debugger->disable();
428
  return Response::Success();
429 430 431 432 433 434 435 436 437
}

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

438
  enableImpl();
439

440
  int pauseState = v8::debug::NoBreakOnException;
441
  m_state->getInteger(DebuggerAgentState::pauseOnExceptionsState, &pauseState);
442
  setPauseOnExceptionsImpl(pauseState);
443 444 445 446 447 448 449 450 451 452 453 454

  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)) {
455
    setBlackboxPattern(blackboxPattern);
456 457 458
  }
}

459
Response V8DebuggerAgentImpl::setBreakpointsActive(bool active) {
460 461
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (m_breakpointsActive == active) return Response::Success();
462 463
  m_breakpointsActive = active;
  m_debugger->setBreakpointsActive(active);
464 465
  if (!active && !m_breakReason.empty()) {
    clearBreakDetails();
466
    m_debugger->setPauseOnNextCall(false, m_session->contextGroupId());
467
  }
468
  return Response::Success();
469 470
}

471
Response V8DebuggerAgentImpl::setSkipAllPauses(bool skip) {
472
  m_state->setBoolean(DebuggerAgentState::skipAllPauses, skip);
473
  m_skipAllPauses = skip;
474
  return Response::Success();
475 476
}

477
static bool matches(V8InspectorImpl* inspector, const V8DebuggerScript& script,
478 479 480 481 482 483 484 485 486 487
                    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;
    }
488 489 490
    case BreakpointType::kByScriptId: {
      return script.scriptId() == selector;
    }
491 492
    default:
      return false;
493 494 495
  }
}

496 497
Response V8DebuggerAgentImpl::setBreakpointByUrl(
    int lineNumber, Maybe<String16> optionalURL,
498 499 500
    Maybe<String16> optionalURLRegex, Maybe<String16> optionalScriptHash,
    Maybe<int> optionalColumnNumber, Maybe<String16> optionalCondition,
    String16* outBreakpointId,
501
    std::unique_ptr<protocol::Array<protocol::Debugger::Location>>* locations) {
502
  *locations = std::make_unique<Array<protocol::Debugger::Location>>();
503

504 505 506 507
  int specified = (optionalURL.isJust() ? 1 : 0) +
                  (optionalURLRegex.isJust() ? 1 : 0) +
                  (optionalScriptHash.isJust() ? 1 : 0);
  if (specified != 1) {
508
    return Response::ServerError(
509 510
        "Either url or urlRegex or scriptHash must be specified.");
  }
511 512 513
  int columnNumber = 0;
  if (optionalColumnNumber.isJust()) {
    columnNumber = optionalColumnNumber.fromJust();
514 515
    if (columnNumber < 0)
      return Response::ServerError("Incorrect column number");
516 517
  }

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  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);
534
  protocol::DictionaryValue* breakpoints;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
  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();
553 554
  }
  if (breakpoints->get(breakpointId)) {
555 556
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
557
  }
558

559
  String16 hint;
560
  for (const auto& script : m_scripts) {
561
    if (!matches(m_inspector, *script.second, type, selector)) continue;
562 563 564 565 566 567
    if (!hint.isEmpty()) {
      adjustBreakpointLocation(*script.second, hint, &lineNumber,
                               &columnNumber);
    }
    std::unique_ptr<protocol::Debugger::Location> location = setBreakpointImpl(
        breakpointId, script.first, condition, lineNumber, columnNumber);
568
    if (location && type != BreakpointType::kByUrlRegex) {
569
      hint = breakpointHint(*script.second, lineNumber, columnNumber);
570
    }
571
    if (location) (*locations)->emplace_back(std::move(location));
572
  }
573 574 575 576 577 578
  breakpoints->setString(breakpointId, condition);
  if (!hint.isEmpty()) {
    protocol::DictionaryValue* breakpointHints =
        getOrCreateObject(m_state, DebuggerAgentState::breakpointHints);
    breakpointHints->setString(breakpointId, hint);
  }
579
  *outBreakpointId = breakpointId;
580
  return Response::Success();
581 582
}

583
Response V8DebuggerAgentImpl::setBreakpoint(
584
    std::unique_ptr<protocol::Debugger::Location> location,
585
    Maybe<String16> optionalCondition, String16* outBreakpointId,
586
    std::unique_ptr<protocol::Debugger::Location>* actualLocation) {
587 588 589
  String16 breakpointId = generateBreakpointId(
      BreakpointType::kByScriptId, location->getScriptId(),
      location->getLineNumber(), location->getColumnNumber(0));
590 591
  if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) !=
      m_breakpointIdToDebuggerBreakpointIds.end()) {
592 593
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
594
  }
595 596 597 598
  *actualLocation = setBreakpointImpl(breakpointId, location->getScriptId(),
                                      optionalCondition.fromMaybe(String16()),
                                      location->getLineNumber(),
                                      location->getColumnNumber(0));
599 600
  if (!*actualLocation)
    return Response::ServerError("Could not resolve breakpoint");
601
  *outBreakpointId = breakpointId;
602
  return Response::Success();
603 604
}

605 606 607 608 609
Response V8DebuggerAgentImpl::setBreakpointOnFunctionCall(
    const String16& functionObjectId, Maybe<String16> optionalCondition,
    String16* outBreakpointId) {
  InjectedScript::ObjectScope scope(m_session, functionObjectId);
  Response response = scope.initialize();
610
  if (!response.IsSuccess()) return response;
611
  if (!scope.object()->IsFunction()) {
612
    return Response::ServerError("Could not find function with given id");
613 614 615 616 617 618 619
  }
  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()) {
620 621
    return Response::ServerError(
        "Breakpoint at specified location already exists.");
622 623 624 625 626
  }
  v8::Local<v8::String> condition =
      toV8String(m_isolate, optionalCondition.fromMaybe(String16()));
  setBreakpointImpl(breakpointId, function, condition);
  *outBreakpointId = breakpointId;
627
  return Response::Success();
628 629
}

630 631
Response V8DebuggerAgentImpl::setInstrumentationBreakpoint(
    const String16& instrumentation, String16* outBreakpointId) {
632
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
633 634 635 636
  String16 breakpointId = generateInstrumentationBreakpointId(instrumentation);
  protocol::DictionaryValue* breakpoints = getOrCreateObject(
      m_state, DebuggerAgentState::instrumentationBreakpoints);
  if (breakpoints->get(breakpointId)) {
637 638
    return Response::ServerError(
        "Instrumentation breakpoint is already enabled.");
639 640 641
  }
  breakpoints->setBoolean(breakpointId, true);
  *outBreakpointId = breakpointId;
642
  return Response::Success();
643 644
}

645
Response V8DebuggerAgentImpl::removeBreakpoint(const String16& breakpointId) {
646
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
647 648 649
  BreakpointType type;
  String16 selector;
  if (!parseBreakpointId(breakpointId, &type, &selector)) {
650
    return Response::Success();
651 652
  }
  protocol::DictionaryValue* breakpoints = nullptr;
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
  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;
671 672 673 674
    case BreakpointType::kInstrumentationBreakpoint:
      breakpoints =
          m_state->getObject(DebuggerAgentState::instrumentationBreakpoints);
      break;
675 676
    default:
      break;
677 678 679 680 681
  }
  if (breakpoints) breakpoints->remove(breakpointId);
  protocol::DictionaryValue* breakpointHints =
      m_state->getObject(DebuggerAgentState::breakpointHints);
  if (breakpointHints) breakpointHints->remove(breakpointId);
682 683 684 685 686 687 688 689 690 691 692 693

  // 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) {
    if (!matches(m_inspector, *scriptIter.second, type, selector)) continue;
    V8DebuggerScript* script = scriptIter.second.get();
    scripts.push_back(script);
  }
  removeBreakpointImpl(breakpointId, scripts);

694
  return Response::Success();
695 696
}

697 698 699
void V8DebuggerAgentImpl::removeBreakpointImpl(
    const String16& breakpointId,
    const std::vector<V8DebuggerScript*>& scripts) {
700 701 702 703 704
  DCHECK(enabled());
  BreakpointIdToDebuggerBreakpointIdsMap::iterator
      debuggerBreakpointIdsIterator =
          m_breakpointIdToDebuggerBreakpointIds.find(breakpointId);
  if (debuggerBreakpointIdsIterator ==
705
      m_breakpointIdToDebuggerBreakpointIds.end()) {
706
    return;
707 708
  }
  for (const auto& id : debuggerBreakpointIdsIterator->second) {
709 710 711
    for (auto& script : scripts) {
      script->removeWasmBreakpoint(id);
    }
712
    v8::debug::RemoveBreakpoint(m_isolate, id);
713
    m_debuggerBreakpointIdToBreakpointId.erase(id);
714 715 716 717
  }
  m_breakpointIdToDebuggerBreakpointIds.erase(breakpointId);
}

718 719
Response V8DebuggerAgentImpl::getPossibleBreakpoints(
    std::unique_ptr<protocol::Debugger::Location> start,
720
    Maybe<protocol::Debugger::Location> end, Maybe<bool> restrictToFunction,
721 722
    std::unique_ptr<protocol::Array<protocol::Debugger::BreakLocation>>*
        locations) {
723 724 725
  String16 scriptId = start->getScriptId();

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

729 730 731
  v8::debug::Location v8Start(start->getLineNumber(),
                              start->getColumnNumber(0));
  v8::debug::Location v8End;
732 733
  if (end.isJust()) {
    if (end.fromJust()->getScriptId() != scriptId)
734 735
      return Response::ServerError(
          "Locations should contain the same scriptId");
736 737 738
    int line = end.fromJust()->getLineNumber();
    int column = end.fromJust()->getColumnNumber(0);
    if (line < 0 || column < 0)
739
      return Response::ServerError(
740
          "end.lineNumber and end.columnNumber should be >= 0");
741
    v8End = v8::debug::Location(line, column);
742 743
  }
  auto it = m_scripts.find(scriptId);
744
  if (it == m_scripts.end()) return Response::ServerError("Script not found");
745
  std::vector<v8::debug::BreakLocation> v8Locations;
746 747
  {
    v8::HandleScope handleScope(m_isolate);
748 749 750
    int contextId = it->second->executionContextId();
    InspectedContext* inspected = m_inspector->getContext(contextId);
    if (!inspected) {
751
      return Response::ServerError("Cannot retrive script context");
752 753
    }
    v8::Context::Scope contextScope(inspected->context());
754 755
    v8::MicrotasksScope microtasks(m_isolate,
                                   v8::MicrotasksScope::kDoNotRunMicrotasks);
756 757 758
    v8::TryCatch tryCatch(m_isolate);
    it->second->getPossibleBreakpoints(
        v8Start, v8End, restrictToFunction.fromMaybe(false), &v8Locations);
759
  }
760

761 762
  *locations =
      std::make_unique<protocol::Array<protocol::Debugger::BreakLocation>>();
763 764 765 766 767 768

  // 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) {
769 770 771 772 773 774 775 776 777
    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()));
    }
778
    (*locations)->emplace_back(std::move(breakLocation));
779
  }
780
  return Response::Success();
781 782
}

783
Response V8DebuggerAgentImpl::continueToLocation(
784 785
    std::unique_ptr<protocol::Debugger::Location> location,
    Maybe<String16> targetCallFrames) {
786 787
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
788 789
  ScriptsMap::iterator it = m_scripts.find(location->getScriptId());
  if (it == m_scripts.end()) {
790
    return Response::ServerError("Cannot continue to specified location");
791 792 793 794 795
  }
  V8DebuggerScript* script = it->second.get();
  int contextId = script->executionContextId();
  InspectedContext* inspected = m_inspector->getContext(contextId);
  if (!inspected)
796
    return Response::ServerError("Cannot continue to specified location");
797
  v8::HandleScope handleScope(m_isolate);
798
  v8::Context::Scope contextScope(inspected->context());
799
  return m_debugger->continueToLocation(
800
      m_session->contextGroupId(), script, std::move(location),
801 802
      targetCallFrames.fromMaybe(
          protocol::Debugger::ContinueToLocation::TargetCallFramesEnum::Any));
803 804
}

805 806 807 808 809
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);
810
  if (!isOk) return Response::ServerError("Invalid stack trace id");
811 812

  V8DebuggerId debuggerId;
813
  if (inStackTraceId->hasDebuggerId()) {
814
    debuggerId = V8DebuggerId(inStackTraceId->getDebuggerId(String16()));
815 816 817
  } else {
    debuggerId = m_debugger->debuggerIdFor(m_session->contextGroupId());
  }
818 819
  if (!debuggerId.isValid())
    return Response::ServerError("Invalid stack trace id");
820 821 822

  V8StackTraceId v8StackTraceId(id, debuggerId.pair());
  if (v8StackTraceId.IsInvalid())
823
    return Response::ServerError("Invalid stack trace id");
824 825 826
  auto stack =
      m_debugger->stackTraceFor(m_session->contextGroupId(), v8StackTraceId);
  if (!stack) {
827
    return Response::ServerError("Stack trace with given id is not found");
828
  }
829 830
  *outStackTrace = stack->buildInspectorObject(
      m_debugger, m_debugger->maxAsyncCallChainDepth());
831
  return Response::Success();
832 833
}

834 835 836 837
bool V8DebuggerAgentImpl::isFunctionBlackboxed(const String16& scriptId,
                                               const v8::debug::Location& start,
                                               const v8::debug::Location& end) {
  ScriptsMap::iterator it = m_scripts.find(scriptId);
838 839 840 841 842 843 844 845 846 847
  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;
  }
848
  auto itBlackboxedPositions = m_blackboxedPositions.find(scriptId);
849 850 851 852
  if (itBlackboxedPositions == m_blackboxedPositions.end()) return false;

  const std::vector<std::pair<int, int>>& ranges =
      itBlackboxedPositions->second;
853
  auto itStartRange = std::lower_bound(
854
      ranges.begin(), ranges.end(),
855 856 857 858 859 860
      std::make_pair(start.GetLineNumber(), start.GetColumnNumber()),
      positionComparator);
  auto itEndRange = std::lower_bound(
      itStartRange, ranges.end(),
      std::make_pair(end.GetLineNumber(), end.GetColumnNumber()),
      positionComparator);
861 862 863
  // Ranges array contains positions in script where blackbox state is changed.
  // [(0,0) ... ranges[0]) isn't blackboxed, [ranges[0] ... ranges[1]) is
  // blackboxed...
864 865
  return itStartRange == itEndRange &&
         std::distance(ranges.begin(), itStartRange) % 2;
866 867
}

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
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;
}

895 896 897 898
bool V8DebuggerAgentImpl::acceptsPause(bool isOOMBreak) const {
  return enabled() && (isOOMBreak || !m_skipAllPauses);
}

899
std::unique_ptr<protocol::Debugger::Location>
900 901 902 903
V8DebuggerAgentImpl::setBreakpointImpl(const String16& breakpointId,
                                       const String16& scriptId,
                                       const String16& condition,
                                       int lineNumber, int columnNumber) {
904
  v8::HandleScope handles(m_isolate);
905
  DCHECK(enabled());
906 907

  ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
908
  if (scriptIterator == m_scripts.end()) return nullptr;
909
  V8DebuggerScript* script = scriptIterator->second.get();
910
  if (lineNumber < script->startLine() || script->endLine() < lineNumber) {
911
    return nullptr;
912
  }
913

914
  v8::debug::BreakpointId debuggerBreakpointId;
915
  v8::debug::Location location(lineNumber, columnNumber);
916 917 918 919 920 921
  int contextId = script->executionContextId();
  InspectedContext* inspected = m_inspector->getContext(contextId);
  if (!inspected) return nullptr;

  {
    v8::Context::Scope contextScope(inspected->context());
922
    if (!script->setBreakpoint(condition, &location, &debuggerBreakpointId)) {
923 924 925
      return nullptr;
    }
  }
926

927
  m_debuggerBreakpointIdToBreakpointId[debuggerBreakpointId] = breakpointId;
928 929
  m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(
      debuggerBreakpointId);
930 931 932 933 934 935

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

938 939 940 941 942 943 944 945 946 947 948 949 950
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);
}

951 952 953
Response V8DebuggerAgentImpl::searchInContent(
    const String16& scriptId, const String16& query,
    Maybe<bool> optionalCaseSensitive, Maybe<bool> optionalIsRegex,
954 955 956
    std::unique_ptr<Array<protocol::Debugger::SearchMatch>>* results) {
  v8::HandleScope handles(m_isolate);
  ScriptsMap::iterator it = m_scripts.find(scriptId);
957
  if (it == m_scripts.end())
958
    return Response::ServerError("No script for id: " + scriptId.utf8());
959

960 961 962 963
  *results = std::make_unique<protocol::Array<protocol::Debugger::SearchMatch>>(
      searchInTextByLinesImpl(m_session, it->second->source(0), query,
                              optionalCaseSensitive.fromMaybe(false),
                              optionalIsRegex.fromMaybe(false)));
964
  return Response::Success();
965 966
}

967 968
Response V8DebuggerAgentImpl::setScriptSource(
    const String16& scriptId, const String16& newContent, Maybe<bool> dryRun,
969
    Maybe<protocol::Array<protocol::Debugger::CallFrame>>* newCallFrames,
970 971
    Maybe<bool>* stackChanged,
    Maybe<protocol::Runtime::StackTrace>* asyncStackTrace,
972
    Maybe<protocol::Runtime::StackTraceId>* asyncStackTraceId,
973
    Maybe<protocol::Runtime::ExceptionDetails>* optOutCompileError) {
974
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
975

976 977
  ScriptsMap::iterator it = m_scripts.find(scriptId);
  if (it == m_scripts.end()) {
978
    return Response::ServerError("No script with given id found");
979
  }
980
  int contextId = it->second->executionContextId();
981
  InspectedContext* inspected = m_inspector->getContext(contextId);
982 983 984 985 986 987
  if (!inspected) {
    return Response::InternalError();
  }
  v8::HandleScope handleScope(m_isolate);
  v8::Local<v8::Context> context = inspected->context();
  v8::Context::Scope contextScope(context);
988 989 990 991 992 993 994

  v8::debug::LiveEditResult result;
  it->second->setSource(newContent, dryRun.fromMaybe(false), &result);
  if (result.status != v8::debug::LiveEditResult::OK) {
    *optOutCompileError =
        protocol::Runtime::ExceptionDetails::create()
            .setExceptionId(m_inspector->nextExceptionId())
995
            .setText(toProtocolString(m_isolate, result.message))
996 997 998 999 1000
            .setLineNumber(result.line_number != -1 ? result.line_number - 1
                                                    : 0)
            .setColumnNumber(result.column_number != -1 ? result.column_number
                                                        : 0)
            .build();
1001
    return Response::Success();
1002
  } else {
1003
    *stackChanged = result.stack_changed;
1004
  }
1005
  std::unique_ptr<Array<CallFrame>> callFrames;
1006
  Response response = currentCallFrames(&callFrames);
1007
  if (!response.IsSuccess()) return response;
1008 1009
  *newCallFrames = std::move(callFrames);
  *asyncStackTrace = currentAsyncStackTrace();
1010
  *asyncStackTraceId = currentExternalStackTrace();
1011
  return Response::Success();
1012 1013
}

1014 1015
Response V8DebuggerAgentImpl::restartFrame(
    const String16& callFrameId,
1016
    std::unique_ptr<Array<CallFrame>>* newCallFrames,
1017 1018
    Maybe<protocol::Runtime::StackTrace>* asyncStackTrace,
    Maybe<protocol::Runtime::StackTraceId>* asyncStackTraceId) {
1019
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1020
  InjectedScript::CallFrameScope scope(m_session, callFrameId);
1021
  Response response = scope.initialize();
1022
  if (!response.IsSuccess()) return response;
1023 1024 1025
  int frameOrdinal = static_cast<int>(scope.frameOrdinal());
  auto it = v8::debug::StackTraceIterator::Create(m_isolate, frameOrdinal);
  if (it->Done()) {
1026
    return Response::ServerError("Could not find call frame with given id");
1027 1028
  }
  if (!it->Restart()) {
1029
    return Response::InternalError();
1030
  }
1031
  response = currentCallFrames(newCallFrames);
1032
  if (!response.IsSuccess()) return response;
1033
  *asyncStackTrace = currentAsyncStackTrace();
1034
  *asyncStackTraceId = currentExternalStackTrace();
1035
  return Response::Success();
1036 1037
}

1038 1039 1040
Response V8DebuggerAgentImpl::getScriptSource(
    const String16& scriptId, String16* scriptSource,
    Maybe<protocol::Binary>* bytecode) {
1041
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1042
  ScriptsMap::iterator it = m_scripts.find(scriptId);
1043
  if (it == m_scripts.end())
1044
    return Response::ServerError("No script for id: " + scriptId.utf8());
1045
  *scriptSource = it->second->source(0);
1046 1047
  v8::MemorySpan<const uint8_t> span;
  if (it->second->wasmBytecode().To(&span)) {
1048 1049 1050
    if (span.size() > kWasmBytecodeMaxLength) {
      return Response::ServerError(kWasmBytecodeExceedsTransferLimit);
    }
1051 1052
    *bytecode = protocol::Binary::fromSpan(span.data(), span.size());
  }
1053
  return Response::Success();
1054 1055
}

1056 1057
Response V8DebuggerAgentImpl::getWasmBytecode(const String16& scriptId,
                                              protocol::Binary* bytecode) {
1058
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1059 1060
  ScriptsMap::iterator it = m_scripts.find(scriptId);
  if (it == m_scripts.end())
1061
    return Response::ServerError("No script for id: " + scriptId.utf8());
1062 1063
  v8::MemorySpan<const uint8_t> span;
  if (!it->second->wasmBytecode().To(&span))
1064 1065
    return Response::ServerError("Script with id " + scriptId.utf8() +
                                 " is not WebAssembly");
1066 1067 1068
  if (span.size() > kWasmBytecodeMaxLength) {
    return Response::ServerError(kWasmBytecodeExceedsTransferLimit);
  }
1069
  *bytecode = protocol::Binary::fromSpan(span.data(), span.size());
1070
  return Response::Success();
1071 1072
}

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
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);
}

1089 1090 1091
void V8DebuggerAgentImpl::schedulePauseOnNextStatement(
    const String16& breakReason,
    std::unique_ptr<protocol::DictionaryValue> data) {
1092
  if (isPaused() || !acceptsPause(false) || !m_breakpointsActive) return;
1093
  if (m_breakReason.empty()) {
1094
    m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
1095
  }
1096
  pushBreakDetails(breakReason, std::move(data));
1097 1098 1099
}

void V8DebuggerAgentImpl::cancelPauseOnNextStatement() {
1100
  if (isPaused() || !acceptsPause(false) || !m_breakpointsActive) return;
1101
  if (m_breakReason.size() == 1) {
1102
    m_debugger->setPauseOnNextCall(false, m_session->contextGroupId());
1103 1104
  }
  popBreakDetails();
1105 1106
}

1107
Response V8DebuggerAgentImpl::pause() {
1108 1109
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (isPaused()) return Response::Success();
1110 1111 1112 1113 1114 1115 1116
  if (m_debugger->canBreakProgram()) {
    m_debugger->interruptAndBreak(m_session->contextGroupId());
  } else {
    if (m_breakReason.empty()) {
      m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
    }
    pushBreakDetails(protocol::Debugger::Paused::ReasonEnum::Other, nullptr);
1117
  }
1118
  return Response::Success();
1119 1120
}

1121
Response V8DebuggerAgentImpl::resume(Maybe<bool> terminateOnResume) {
1122
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1123
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1124 1125
  m_debugger->continueProgram(m_session->contextGroupId(),
                              terminateOnResume.fromMaybe(false));
1126
  return Response::Success();
1127 1128
}

1129 1130
Response V8DebuggerAgentImpl::stepOver(
    Maybe<protocol::Array<protocol::Debugger::LocationRange>> inSkipList) {
1131
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1132 1133 1134 1135 1136 1137 1138 1139

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

1140
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1141
  m_debugger->stepOverStatement(m_session->contextGroupId());
1142
  return Response::Success();
1143 1144
}

1145 1146 1147
Response V8DebuggerAgentImpl::stepInto(
    Maybe<bool> inBreakOnAsyncCall,
    Maybe<protocol::Array<protocol::Debugger::LocationRange>> inSkipList) {
1148
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1149 1150 1151 1152 1153 1154 1155 1156

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

1157
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1158 1159
  m_debugger->stepIntoStatement(m_session->contextGroupId(),
                                inBreakOnAsyncCall.fromMaybe(false));
1160
  return Response::Success();
1161 1162
}

1163
Response V8DebuggerAgentImpl::stepOut() {
1164
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1165
  m_session->releaseObjectGroup(kBacktraceObjectGroup);
1166
  m_debugger->stepOutOfFunction(m_session->contextGroupId());
1167
  return Response::Success();
1168 1169
}

1170 1171
Response V8DebuggerAgentImpl::pauseOnAsyncCall(
    std::unique_ptr<protocol::Runtime::StackTraceId> inParentStackTraceId) {
1172
  // Deprecated, just return OK.
1173
  return Response::Success();
1174 1175
}

1176 1177
Response V8DebuggerAgentImpl::setPauseOnExceptions(
    const String16& stringPauseState) {
1178
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
1179
  v8::debug::ExceptionBreakState pauseState;
1180
  if (stringPauseState == "none") {
1181
    pauseState = v8::debug::NoBreakOnException;
1182
  } else if (stringPauseState == "all") {
1183
    pauseState = v8::debug::BreakOnAnyException;
1184
  } else if (stringPauseState == "uncaught") {
1185
    pauseState = v8::debug::BreakOnUncaughtException;
1186
  } else {
1187 1188
    return Response::ServerError("Unknown pause on exceptions mode: " +
                                 stringPauseState.utf8());
1189
  }
1190
  setPauseOnExceptionsImpl(pauseState);
1191
  return Response::Success();
1192 1193
}

1194
void V8DebuggerAgentImpl::setPauseOnExceptionsImpl(int pauseState) {
1195 1196
  // TODO(dgozman): this changes the global state and forces all context groups
  // to pause. We should make this flag be per-context-group.
1197
  m_debugger->setPauseOnExceptionsState(
1198
      static_cast<v8::debug::ExceptionBreakState>(pauseState));
1199
  m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, pauseState);
1200 1201
}

1202 1203 1204 1205
Response V8DebuggerAgentImpl::evaluateOnCallFrame(
    const String16& callFrameId, const String16& expression,
    Maybe<String16> objectGroup, Maybe<bool> includeCommandLineAPI,
    Maybe<bool> silent, Maybe<bool> returnByValue, Maybe<bool> generatePreview,
1206 1207
    Maybe<bool> throwOnSideEffect, Maybe<double> timeout,
    std::unique_ptr<RemoteObject>* result,
1208
    Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails) {
1209
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1210
  InjectedScript::CallFrameScope scope(m_session, callFrameId);
1211
  Response response = scope.initialize();
1212
  if (!response.IsSuccess()) return response;
1213
  if (includeCommandLineAPI.fromMaybe(false)) scope.installCommandLineAPI();
1214 1215
  if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole();

1216 1217 1218
  int frameOrdinal = static_cast<int>(scope.frameOrdinal());
  auto it = v8::debug::StackTraceIterator::Create(m_isolate, frameOrdinal);
  if (it->Done()) {
1219
    return Response::ServerError("Could not find call frame with given id");
1220
  }
1221 1222 1223

  v8::MaybeLocal<v8::Value> maybeResultValue;
  {
1224
    V8InspectorImpl::EvaluateScope evaluateScope(scope);
1225 1226
    if (timeout.isJust()) {
      response = evaluateScope.setTimeout(timeout.fromJust() / 1000.0);
1227
      if (!response.IsSuccess()) return response;
1228 1229 1230 1231
    }
    maybeResultValue = it->Evaluate(toV8String(m_isolate, expression),
                                    throwOnSideEffect.fromMaybe(false));
  }
1232 1233
  // Re-initialize after running client's code, as it could have destroyed
  // context or session.
1234
  response = scope.initialize();
1235
  if (!response.IsSuccess()) return response;
1236 1237 1238
  WrapMode mode = generatePreview.fromMaybe(false) ? WrapMode::kWithPreview
                                                   : WrapMode::kNoPreview;
  if (returnByValue.fromMaybe(false)) mode = WrapMode::kForceValue;
1239
  return scope.injectedScript()->wrapEvaluateResult(
1240 1241
      maybeResultValue, scope.tryCatch(), objectGroup.fromMaybe(""), mode,
      result, exceptionDetails);
1242 1243
}

1244 1245
Response V8DebuggerAgentImpl::setVariableValue(
    int scopeNumber, const String16& variableName,
1246 1247
    std::unique_ptr<protocol::Runtime::CallArgument> newValueArgument,
    const String16& callFrameId) {
1248 1249
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1250
  InjectedScript::CallFrameScope scope(m_session, callFrameId);
1251
  Response response = scope.initialize();
1252
  if (!response.IsSuccess()) return response;
1253
  v8::Local<v8::Value> newValue;
1254 1255
  response = scope.injectedScript()->resolveCallArgument(newValueArgument.get(),
                                                         &newValue);
1256
  if (!response.IsSuccess()) return response;
1257

1258 1259 1260
  int frameOrdinal = static_cast<int>(scope.frameOrdinal());
  auto it = v8::debug::StackTraceIterator::Create(m_isolate, frameOrdinal);
  if (it->Done()) {
1261
    return Response::ServerError("Could not find call frame with given id");
1262 1263 1264 1265 1266 1267 1268
  }
  auto scopeIterator = it->GetScopeIterator();
  while (!scopeIterator->Done() && scopeNumber > 0) {
    --scopeNumber;
    scopeIterator->Advance();
  }
  if (scopeNumber != 0) {
1269
    return Response::ServerError("Could not find scope with given number");
1270
  }
1271

1272 1273 1274
  if (!scopeIterator->SetVariableValue(toV8String(m_isolate, variableName),
                                       newValue) ||
      scope.tryCatch().HasCaught()) {
1275
    return Response::InternalError();
1276
  }
1277
  return Response::Success();
1278 1279
}

1280 1281
Response V8DebuggerAgentImpl::setReturnValue(
    std::unique_ptr<protocol::Runtime::CallArgument> protocolNewValue) {
1282 1283
  if (!enabled()) return Response::ServerError(kDebuggerNotEnabled);
  if (!isPaused()) return Response::ServerError(kDebuggerNotPaused);
1284
  v8::HandleScope handleScope(m_isolate);
1285 1286
  auto iterator = v8::debug::StackTraceIterator::Create(m_isolate);
  if (iterator->Done()) {
1287
    return Response::ServerError("Could not find top call frame");
1288 1289
  }
  if (iterator->GetReturnValue().IsEmpty()) {
1290
    return Response::ServerError(
1291 1292 1293 1294
        "Could not update return value at non-return position");
  }
  InjectedScript::ContextScope scope(m_session, iterator->GetContextId());
  Response response = scope.initialize();
1295
  if (!response.IsSuccess()) return response;
1296 1297 1298
  v8::Local<v8::Value> newValue;
  response = scope.injectedScript()->resolveCallArgument(protocolNewValue.get(),
                                                         &newValue);
1299
  if (!response.IsSuccess()) return response;
1300
  v8::debug::SetReturnValue(m_isolate, newValue);
1301
  return Response::Success();
1302 1303
}

1304
Response V8DebuggerAgentImpl::setAsyncCallStackDepth(int depth) {
1305
  if (!enabled() && !m_session->runtimeAgent()->enabled()) {
1306
    return Response::ServerError(kDebuggerNotEnabled);
1307
  }
1308 1309
  m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, depth);
  m_debugger->setAsyncCallStackDepth(this, depth);
1310
  return Response::Success();
1311 1312
}

1313
Response V8DebuggerAgentImpl::setBlackboxPatterns(
1314
    std::unique_ptr<protocol::Array<String16>> patterns) {
1315
  if (patterns->empty()) {
1316
    m_blackboxPattern = nullptr;
1317
    resetBlackboxedStateCache();
1318
    m_state->remove(DebuggerAgentState::blackboxPattern);
1319
    return Response::Success();
1320 1321 1322 1323
  }

  String16Builder patternBuilder;
  patternBuilder.append('(');
1324 1325
  for (size_t i = 0; i < patterns->size() - 1; ++i) {
    patternBuilder.append((*patterns)[i]);
1326 1327
    patternBuilder.append("|");
  }
1328
  patternBuilder.append(patterns->back());
1329 1330
  patternBuilder.append(')');
  String16 pattern = patternBuilder.toString();
1331
  Response response = setBlackboxPattern(pattern);
1332
  if (!response.IsSuccess()) return response;
1333
  resetBlackboxedStateCache();
1334
  m_state->setString(DebuggerAgentState::blackboxPattern, pattern);
1335
  return Response::Success();
1336 1337
}

1338
Response V8DebuggerAgentImpl::setBlackboxPattern(const String16& pattern) {
1339 1340
  std::unique_ptr<V8Regex> regex(new V8Regex(
      m_inspector, pattern, true /** caseSensitive */, false /** multiline */));
1341
  if (!regex->isValid())
1342 1343
    return Response::ServerError("Pattern parser error: " +
                                 regex->errorMessage().utf8());
1344
  m_blackboxPattern = std::move(regex);
1345
  return Response::Success();
1346 1347
}

1348 1349 1350 1351 1352 1353
void V8DebuggerAgentImpl::resetBlackboxedStateCache() {
  for (const auto& it : m_scripts) {
    it.second->resetBlackboxedStateCache();
  }
}

1354 1355
Response V8DebuggerAgentImpl::setBlackboxedRanges(
    const String16& scriptId,
1356 1357
    std::unique_ptr<protocol::Array<protocol::Debugger::ScriptPosition>>
        inPositions) {
1358 1359
  auto it = m_scripts.find(scriptId);
  if (it == m_scripts.end())
1360
    return Response::ServerError("No script with passed id.");
1361

1362
  if (inPositions->empty()) {
1363
    m_blackboxedPositions.erase(scriptId);
1364
    it->second->resetBlackboxedStateCache();
1365
    return Response::Success();
1366 1367 1368
  }

  std::vector<std::pair<int, int>> positions;
1369 1370 1371
  positions.reserve(inPositions->size());
  for (const std::unique_ptr<protocol::Debugger::ScriptPosition>& position :
       *inPositions) {
1372 1373 1374
    Response res = isValidPosition(position.get());
    if (res.IsError()) return res;

1375 1376 1377
    positions.push_back(
        std::make_pair(position->getLineNumber(), position->getColumnNumber()));
  }
1378 1379
  Response res = isValidRangeOfPositions(positions);
  if (res.IsError()) return res;
1380 1381

  m_blackboxedPositions[scriptId] = positions;
1382
  it->second->resetBlackboxedStateCache();
1383
  return Response::Success();
1384 1385
}

1386 1387
Response V8DebuggerAgentImpl::currentCallFrames(
    std::unique_ptr<Array<CallFrame>>* result) {
1388
  if (!isPaused()) {
1389
    *result = std::make_unique<Array<CallFrame>>();
1390
    return Response::Success();
1391
  }
1392
  v8::HandleScope handles(m_isolate);
1393
  *result = std::make_unique<Array<CallFrame>>();
1394 1395 1396 1397
  auto iterator = v8::debug::StackTraceIterator::Create(m_isolate);
  int frameOrdinal = 0;
  for (; !iterator->Done(); iterator->Advance(), frameOrdinal++) {
    int contextId = iterator->GetContextId();
1398 1399
    InjectedScript* injectedScript = nullptr;
    if (contextId) m_session->findInjectedScript(contextId, injectedScript);
1400 1401
    String16 callFrameId = RemoteCallFrameId::serialize(
        m_inspector->isolateId(), contextId, frameOrdinal);
1402 1403 1404 1405 1406

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

    std::unique_ptr<Array<Scope>> scopes;
    auto scopeIterator = iterator->GetScopeIterator();
1407 1408
    Response res =
        buildScopes(m_isolate, scopeIterator.get(), injectedScript, &scopes);
1409
    if (!res.IsSuccess()) return res;
1410

1411
    std::unique_ptr<RemoteObject> protocolReceiver;
1412
    if (injectedScript) {
1413 1414
      v8::Local<v8::Value> receiver;
      if (iterator->GetReceiver().ToLocal(&receiver)) {
1415 1416 1417
        res =
            injectedScript->wrapObject(receiver, kBacktraceObjectGroup,
                                       WrapMode::kNoPreview, &protocolReceiver);
1418
        if (!res.IsSuccess()) return res;
1419 1420 1421 1422 1423 1424
      }
    }
    if (!protocolReceiver) {
      protocolReceiver = RemoteObject::create()
                             .setType(RemoteObject::TypeEnum::Undefined)
                             .build();
1425 1426
    }

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    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();
    String16 scriptId = String16::fromInteger(script->Id());
    ScriptsMap::iterator scriptIterator =
        m_scripts.find(location->getScriptId());
    String16 url;
    if (scriptIterator != m_scripts.end()) {
      url = scriptIterator->second->sourceURL();
    }

1443 1444 1445 1446 1447 1448 1449 1450 1451
    auto frame = CallFrame::create()
                     .setCallFrameId(callFrameId)
                     .setFunctionName(toProtocolString(
                         m_isolate, iterator->GetFunctionDebugName()))
                     .setLocation(std::move(location))
                     .setUrl(url)
                     .setScopeChain(std::move(scopes))
                     .setThis(std::move(protocolReceiver))
                     .build();
1452 1453 1454 1455 1456 1457 1458 1459 1460

    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());
1461 1462
    }

1463 1464 1465 1466
    v8::Local<v8::Value> returnValue = iterator->GetReturnValue();
    if (!returnValue.IsEmpty() && injectedScript) {
      std::unique_ptr<RemoteObject> value;
      res = injectedScript->wrapObject(returnValue, kBacktraceObjectGroup,
1467
                                       WrapMode::kNoPreview, &value);
1468
      if (!res.IsSuccess()) return res;
1469
      frame->setReturnValue(std::move(value));
1470
    }
1471
    (*result)->emplace_back(std::move(frame));
1472
  }
1473
  return Response::Success();
1474 1475
}

1476 1477 1478 1479 1480 1481
std::unique_ptr<protocol::Runtime::StackTrace>
V8DebuggerAgentImpl::currentAsyncStackTrace() {
  std::shared_ptr<AsyncStackTrace> asyncParent =
      m_debugger->currentAsyncParent();
  if (!asyncParent) return nullptr;
  return asyncParent->buildInspectorObject(
1482
      m_debugger, m_debugger->maxAsyncCallChainDepth() - 1);
1483 1484
}

1485 1486 1487 1488 1489 1490
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))
1491
      .setDebuggerId(V8DebuggerId(externalParent.debugger_id).toString())
1492 1493 1494
      .build();
}

1495
bool V8DebuggerAgentImpl::isPaused() const {
1496
  return m_debugger->isPausedInContextGroup(m_session->contextGroupId());
1497
}
1498

1499 1500 1501 1502 1503 1504 1505 1506 1507
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;
  }
}

1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
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;
}

1541 1542 1543
void V8DebuggerAgentImpl::didParseSource(
    std::unique_ptr<V8DebuggerScript> script, bool success) {
  v8::HandleScope handles(m_isolate);
1544 1545 1546 1547 1548 1549
  if (!success) {
    DCHECK(!script->isSourceLoadedLazily());
    String16 scriptSource = script->source(0);
    script->setSourceURL(findSourceURL(scriptSource, false));
    script->setSourceMappingURL(findSourceMapURL(scriptSource, false));
  }
1550

1551 1552 1553 1554
  int contextId = script->executionContextId();
  int contextGroupId = m_inspector->contextGroupId(contextId);
  InspectedContext* inspected =
      m_inspector->getContext(contextGroupId, contextId);
1555
  std::unique_ptr<protocol::DictionaryValue> executionContextAuxData;
1556 1557 1558
  if (inspected) {
    // Script reused between different groups/sessions can have a stale
    // execution context id.
1559 1560 1561 1562
    const String16& aux = inspected->auxData();
    std::vector<uint8_t> cbor;
    v8_crdtp::json::ConvertJSONToCBOR(
        v8_crdtp::span<uint16_t>(aux.characters16(), aux.length()), &cbor);
1563
    executionContextAuxData = protocol::DictionaryValue::cast(
1564
        protocol::Value::parseBinary(cbor.data(), cbor.size()));
1565
  }
1566
  bool isLiveEdit = script->isLiveEdit();
1567
  bool hasSourceURLComment = script->hasSourceURLComment();
1568
  bool isModule = script->isModule();
1569 1570
  String16 scriptId = script->scriptId();
  String16 scriptURL = script->sourceURL();
1571
  String16 embedderName = script->embedderName();
1572
  String16 scriptLanguage = getScriptLanguage(*script);
1573 1574 1575
  Maybe<int> codeOffset;
  if (script->getLanguage() == V8DebuggerScript::Language::WebAssembly)
    codeOffset = script->codeOffset();
1576 1577
  std::unique_ptr<protocol::Debugger::DebugSymbols> debugSymbols =
      getDebugSymbols(*script);
1578

1579
  m_scripts[scriptId] = std::move(script);
1580 1581 1582
  // 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();
1583 1584 1585 1586

  ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
  DCHECK(scriptIterator != m_scripts.end());
  V8DebuggerScript* scriptRef = scriptIterator->second.get();
1587 1588 1589 1590 1591
  // 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();
1592 1593

  Maybe<String16> sourceMapURLParam = scriptRef->sourceMappingURL();
1594
  Maybe<protocol::DictionaryValue> executionContextAuxDataParam(
1595 1596
      std::move(executionContextAuxData));
  const bool* isLiveEditParam = isLiveEdit ? &isLiveEdit : nullptr;
1597 1598
  const bool* hasSourceURLParam =
      hasSourceURLComment ? &hasSourceURLComment : nullptr;
1599
  const bool* isModuleParam = isModule ? &isModule : nullptr;
1600 1601 1602
  std::unique_ptr<V8StackTraceImpl> stack =
      V8StackTraceImpl::capture(m_inspector->debugger(), contextGroupId, 1);
  std::unique_ptr<protocol::Runtime::StackTrace> stackTrace =
1603 1604 1605
      stack && !stack->isEmpty()
          ? stack->buildInspectorObjectImpl(m_debugger, 0)
          : nullptr;
1606 1607

  if (!success) {
1608
    m_frontend.scriptFailedToParse(
1609
        scriptId, scriptURL, scriptRef->startLine(), scriptRef->startColumn(),
1610
        scriptRef->endLine(), scriptRef->endColumn(), contextId,
1611
        scriptRef->hash(), std::move(executionContextAuxDataParam),
1612
        std::move(sourceMapURLParam), hasSourceURLParam, isModuleParam,
1613
        scriptRef->length(), std::move(stackTrace), std::move(codeOffset),
1614
        std::move(scriptLanguage), embedderName);
1615
    return;
1616
  }
1617

1618 1619 1620 1621 1622
  if (scriptRef->isSourceLoadedLazily()) {
    m_frontend.scriptParsed(
        scriptId, scriptURL, 0, 0, 0, 0, contextId, scriptRef->hash(),
        std::move(executionContextAuxDataParam), isLiveEditParam,
        std::move(sourceMapURLParam), hasSourceURLParam, isModuleParam, 0,
1623
        std::move(stackTrace), std::move(codeOffset), std::move(scriptLanguage),
1624
        std::move(debugSymbols), embedderName);
1625 1626 1627 1628 1629 1630
  } else {
    m_frontend.scriptParsed(
        scriptId, scriptURL, scriptRef->startLine(), scriptRef->startColumn(),
        scriptRef->endLine(), scriptRef->endColumn(), contextId,
        scriptRef->hash(), std::move(executionContextAuxDataParam),
        isLiveEditParam, std::move(sourceMapURLParam), hasSourceURLParam,
1631
        isModuleParam, scriptRef->length(), std::move(stackTrace),
1632
        std::move(codeOffset), std::move(scriptLanguage),
1633
        std::move(debugSymbols), embedderName);
1634
  }
1635

1636
  std::vector<protocol::DictionaryValue*> potentialBreakpoints;
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
  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()));
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  }
  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);

1667
      if (!matches(m_inspector, *scriptRef, type, selector)) continue;
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
      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));
1681
    }
1682
  }
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  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;
  if (!scriptRef->setBreakpointOnRun(&debuggerBreakpointId)) return;
  std::unique_ptr<protocol::DictionaryValue> data =
      protocol::DictionaryValue::create();
  data->setString("url", scriptRef->sourceURL());
  data->setString("scriptId", scriptRef->scriptId());
  if (!sourceMapURL.isEmpty()) data->setString("sourceMapURL", sourceMapURL);

  m_breakpointsOnScriptRun[debuggerBreakpointId] = std::move(data);
  m_debuggerBreakpointIdToBreakpointId[debuggerBreakpointId] = breakpointId;
  m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(
      debuggerBreakpointId);
1717 1718
}

1719 1720 1721
void V8DebuggerAgentImpl::didPause(
    int contextId, v8::Local<v8::Value> exception,
    const std::vector<v8::debug::BreakpointId>& hitBreakpoints,
1722 1723
    v8::debug::ExceptionType exceptionType, bool isUncaught, bool isOOMBreak,
    bool isAssert) {
1724 1725
  v8::HandleScope handles(m_isolate);

1726 1727
  std::vector<BreakReason> hitReasons;

1728
  if (isOOMBreak) {
1729 1730
    hitReasons.push_back(
        std::make_pair(protocol::Debugger::Paused::ReasonEnum::OOM, nullptr));
1731 1732 1733
  } else if (isAssert) {
    hitReasons.push_back(std::make_pair(
        protocol::Debugger::Paused::ReasonEnum::Assert, nullptr));
1734
  } else if (!exception.IsEmpty()) {
1735
    InjectedScript* injectedScript = nullptr;
1736
    m_session->findInjectedScript(contextId, injectedScript);
1737
    if (injectedScript) {
1738
      String16 breakReason =
1739
          exceptionType == v8::debug::kPromiseRejection
1740 1741
              ? protocol::Debugger::Paused::ReasonEnum::PromiseRejection
              : protocol::Debugger::Paused::ReasonEnum::Exception;
1742
      std::unique_ptr<protocol::Runtime::RemoteObject> obj;
1743 1744
      injectedScript->wrapObject(exception, kBacktraceObjectGroup,
                                 WrapMode::kNoPreview, &obj);
1745
      std::unique_ptr<protocol::DictionaryValue> breakAuxData;
1746
      if (obj) {
1747 1748 1749 1750
        std::vector<uint8_t> serialized;
        obj->AppendSerialized(&serialized);
        breakAuxData = protocol::DictionaryValue::cast(
            protocol::Value::parseBinary(serialized.data(), serialized.size()));
1751
        breakAuxData->setBoolean("uncaught", isUncaught);
1752
      }
1753 1754
      hitReasons.push_back(
          std::make_pair(breakReason, std::move(breakAuxData)));
1755 1756 1757
    }
  }

1758
  auto hitBreakpointIds = std::make_unique<Array<String16>>();
1759

1760
  for (const auto& id : hitBreakpoints) {
1761 1762 1763 1764 1765 1766 1767 1768
    auto it = m_breakpointsOnScriptRun.find(id);
    if (it != m_breakpointsOnScriptRun.end()) {
      hitReasons.push_back(std::make_pair(
          protocol::Debugger::Paused::ReasonEnum::Instrumentation,
          std::move(it->second)));
      m_breakpointsOnScriptRun.erase(it);
      continue;
    }
1769 1770 1771
    auto breakpointIterator = m_debuggerBreakpointIdToBreakpointId.find(id);
    if (breakpointIterator == m_debuggerBreakpointIdToBreakpointId.end()) {
      continue;
1772
    }
1773
    const String16& breakpointId = breakpointIterator->second;
1774
    hitBreakpointIds->emplace_back(breakpointId);
1775 1776 1777 1778 1779
    BreakpointType type;
    parseBreakpointId(breakpointId, &type);
    if (type != BreakpointType::kDebugCommand) continue;
    hitReasons.push_back(std::make_pair(
        protocol::Debugger::Paused::ReasonEnum::DebugCommand, nullptr));
1780 1781
  }

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
  for (size_t i = 0; i < m_breakReason.size(); ++i) {
    hitReasons.push_back(std::move(m_breakReason[i]));
  }
  clearBreakDetails();

  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));
  }

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

1813 1814
  m_frontend.paused(std::move(protocolCallFrames), breakReason,
                    std::move(breakAuxData), std::move(hitBreakpointIds),
1815
                    currentAsyncStackTrace(), currentExternalStackTrace());
1816 1817 1818 1819 1820
}

void V8DebuggerAgentImpl::didContinue() {
  clearBreakDetails();
  m_frontend.resumed();
1821
  m_frontend.flush();
1822 1823 1824 1825 1826
}

void V8DebuggerAgentImpl::breakProgram(
    const String16& breakReason,
    std::unique_ptr<protocol::DictionaryValue> data) {
1827
  if (!enabled() || m_skipAllPauses || !m_debugger->canBreakProgram()) return;
1828 1829 1830
  std::vector<BreakReason> currentScheduledReason;
  currentScheduledReason.swap(m_breakReason);
  pushBreakDetails(breakReason, std::move(data));
1831 1832 1833 1834 1835 1836 1837 1838 1839

  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;

1840 1841
  popBreakDetails();
  m_breakReason.swap(currentScheduledReason);
1842
  if (!m_breakReason.empty()) {
1843
    m_debugger->setPauseOnNextCall(true, m_session->contextGroupId());
1844
  }
1845 1846
}

1847 1848 1849
void V8DebuggerAgentImpl::setBreakpointFor(v8::Local<v8::Function> function,
                                           v8::Local<v8::String> condition,
                                           BreakpointSource source) {
1850 1851 1852
  String16 breakpointId = generateBreakpointId(
      source == DebugCommandBreakpointSource ? BreakpointType::kDebugCommand
                                             : BreakpointType::kMonitorCommand,
1853
      function);
1854 1855 1856 1857
  if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) !=
      m_breakpointIdToDebuggerBreakpointIds.end()) {
    return;
  }
1858
  setBreakpointImpl(breakpointId, function, condition);
1859 1860
}

1861 1862
void V8DebuggerAgentImpl::removeBreakpointFor(v8::Local<v8::Function> function,
                                              BreakpointSource source) {
1863 1864 1865
  String16 breakpointId = generateBreakpointId(
      source == DebugCommandBreakpointSource ? BreakpointType::kDebugCommand
                                             : BreakpointType::kMonitorCommand,
1866
      function);
1867 1868
  std::vector<V8DebuggerScript*> scripts;
  removeBreakpointImpl(breakpointId, scripts);
1869 1870 1871 1872 1873
}

void V8DebuggerAgentImpl::reset() {
  if (!enabled()) return;
  m_blackboxedPositions.clear();
1874
  resetBlackboxedStateCache();
1875
  m_skipList.clear();
1876
  m_scripts.clear();
1877 1878
  m_cachedScriptIds.clear();
  m_cachedScriptSize = 0;
1879 1880
}

1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
void V8DebuggerAgentImpl::ScriptCollected(const V8DebuggerScript* script) {
  DCHECK_NE(m_scripts.find(script->scriptId()), m_scripts.end());
  m_cachedScriptIds.push_back(script->scriptId());
  // TODO(alph): Properly calculate size when sources are one-byte strings.
  m_cachedScriptSize += script->length() * sizeof(uint16_t);

  while (m_cachedScriptSize > m_maxScriptCacheSize) {
    const String16& scriptId = m_cachedScriptIds.front();
    size_t scriptSize = m_scripts[scriptId]->length() * sizeof(uint16_t);
    DCHECK_GE(m_cachedScriptSize, scriptSize);
    m_cachedScriptSize -= scriptSize;
1892
    m_scripts.erase(scriptId);
1893
    m_cachedScriptIds.pop_front();
1894 1895 1896
  }
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
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();
}
1931
}  // namespace v8_inspector