v8-console-message.cc 24.8 KB
Newer Older
1 2 3 4
// Copyright 2016 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
#include "src/inspector/v8-console-message.h"
6

7 8
#include "include/v8-container.h"
#include "include/v8-context.h"
9
#include "include/v8-inspector.h"
10 11
#include "include/v8-microtask-queue.h"
#include "include/v8-primitive-object.h"
12
#include "src/debug/debug-interface.h"
13
#include "src/inspector/inspected-context.h"
14
#include "src/inspector/protocol/Protocol.h"
15 16 17 18 19 20
#include "src/inspector/string-util.h"
#include "src/inspector/v8-console-agent-impl.h"
#include "src/inspector/v8-inspector-impl.h"
#include "src/inspector/v8-inspector-session-impl.h"
#include "src/inspector/v8-runtime-agent-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"
21
#include "src/inspector/value-mirror.h"
22
#include "src/tracing/trace-event.h"
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
namespace v8_inspector {

namespace {

String16 consoleAPITypeValue(ConsoleAPIType type) {
  switch (type) {
    case ConsoleAPIType::kLog:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
    case ConsoleAPIType::kDebug:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug;
    case ConsoleAPIType::kInfo:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Info;
    case ConsoleAPIType::kError:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Error;
    case ConsoleAPIType::kWarning:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Warning;
    case ConsoleAPIType::kClear:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Clear;
    case ConsoleAPIType::kDir:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dir;
    case ConsoleAPIType::kDirXML:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dirxml;
    case ConsoleAPIType::kTable:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Table;
    case ConsoleAPIType::kTrace:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Trace;
    case ConsoleAPIType::kStartGroup:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroup;
    case ConsoleAPIType::kStartGroupCollapsed:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroupCollapsed;
    case ConsoleAPIType::kEndGroup:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::EndGroup;
    case ConsoleAPIType::kAssert:
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Assert;
    case ConsoleAPIType::kTimeEnd:
59
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::TimeEnd;
60
    case ConsoleAPIType::kCount:
61
      return protocol::Runtime::ConsoleAPICalled::TypeEnum::Count;
62 63 64 65
  }
  return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
}

66
const char kGlobalConsoleMessageHandleLabel[] = "DevTools console";
67
const unsigned maxConsoleMessageCount = 1000;
68
const int maxConsoleMessageV8Size = 10 * 1024 * 1024;
69 70 71 72 73
const unsigned maxArrayItemsLimit = 10000;
const unsigned maxStackDepthLimit = 32;

class V8ValueStringBuilder {
 public:
74 75 76
  static String16 toString(v8::Local<v8::Value> value,
                           v8::Local<v8::Context> context) {
    V8ValueStringBuilder builder(context);
77 78 79 80 81 82 83 84 85 86
    if (!builder.append(value)) return String16();
    return builder.toString();
  }

 private:
  enum {
    IgnoreNull = 1 << 0,
    IgnoreUndefined = 1 << 1,
  };

87
  explicit V8ValueStringBuilder(v8::Local<v8::Context> context)
88
      : m_arrayLimit(maxArrayItemsLimit),
89 90 91
        m_isolate(context->GetIsolate()),
        m_tryCatch(context->GetIsolate()),
        m_context(context) {}
92 93 94 95 96

  bool append(v8::Local<v8::Value> value, unsigned ignoreOptions = 0) {
    if (value.IsEmpty()) return true;
    if ((ignoreOptions & IgnoreNull) && value->IsNull()) return true;
    if ((ignoreOptions & IgnoreUndefined) && value->IsUndefined()) return true;
97 98 99 100 101 102 103 104 105 106 107 108 109
    if (value->IsBigIntObject()) {
      value = value.As<v8::BigIntObject>()->ValueOf();
    } else if (value->IsBooleanObject()) {
      value =
          v8::Boolean::New(m_isolate, value.As<v8::BooleanObject>()->ValueOf());
    } else if (value->IsNumberObject()) {
      value =
          v8::Number::New(m_isolate, value.As<v8::NumberObject>()->ValueOf());
    } else if (value->IsStringObject()) {
      value = value.As<v8::StringObject>()->ValueOf();
    } else if (value->IsSymbolObject()) {
      value = value.As<v8::SymbolObject>()->ValueOf();
    }
110 111 112 113
    if (value->IsString()) return append(value.As<v8::String>());
    if (value->IsBigInt()) return append(value.As<v8::BigInt>());
    if (value->IsSymbol()) return append(value.As<v8::Symbol>());
    if (value->IsArray()) return append(value.As<v8::Array>());
114 115 116 117 118 119
    if (value->IsProxy()) {
      m_builder.append("[object Proxy]");
      return true;
    }
    if (value->IsObject() && !value->IsDate() && !value->IsFunction() &&
        !value->IsNativeError() && !value->IsRegExp()) {
120
      v8::Local<v8::Object> object = value.As<v8::Object>();
121
      v8::Local<v8::String> stringValue;
122
      if (object->ObjectProtoToString(m_context).ToLocal(&stringValue))
123 124 125
        return append(stringValue);
    }
    v8::Local<v8::String> stringValue;
126
    if (!value->ToString(m_context).ToLocal(&stringValue)) return false;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    return append(stringValue);
  }

  bool append(v8::Local<v8::Array> array) {
    for (const auto& it : m_visitedArrays) {
      if (it == array) return true;
    }
    uint32_t length = array->Length();
    if (length > m_arrayLimit) return false;
    if (m_visitedArrays.size() > maxStackDepthLimit) return false;

    bool result = true;
    m_arrayLimit -= length;
    m_visitedArrays.push_back(array);
    for (uint32_t i = 0; i < length; ++i) {
      if (i) m_builder.append(',');
143 144 145
      v8::Local<v8::Value> value;
      if (!array->Get(m_context, i).ToLocal(&value)) continue;
      if (!append(value, IgnoreNull | IgnoreUndefined)) {
146 147 148 149 150 151 152 153 154 155
        result = false;
        break;
      }
    }
    m_visitedArrays.pop_back();
    return result;
  }

  bool append(v8::Local<v8::Symbol> symbol) {
    m_builder.append("Symbol(");
156
    bool result = append(symbol->Description(m_isolate), IgnoreUndefined);
157 158 159 160
    m_builder.append(')');
    return result;
  }

161
  bool append(v8::Local<v8::BigInt> bigint) {
162 163 164
    v8::Local<v8::String> bigint_string;
    if (!bigint->ToString(m_context).ToLocal(&bigint_string)) return false;
    bool result = append(bigint_string);
165 166 167 168 169
    if (m_tryCatch.HasCaught()) return false;
    m_builder.append('n');
    return result;
  }

170 171
  bool append(v8::Local<v8::String> string) {
    if (m_tryCatch.HasCaught()) return false;
172 173 174
    if (!string.IsEmpty()) {
      m_builder.append(toProtocolString(m_isolate, string));
    }
175 176 177 178 179 180 181 182 183 184 185 186 187
    return true;
  }

  String16 toString() {
    if (m_tryCatch.HasCaught()) return String16();
    return m_builder.toString();
  }

  uint32_t m_arrayLimit;
  v8::Isolate* m_isolate;
  String16Builder m_builder;
  std::vector<v8::Local<v8::Array>> m_visitedArrays;
  v8::TryCatch m_tryCatch;
188
  v8::Local<v8::Context> m_context;
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
};

}  // namespace

V8ConsoleMessage::V8ConsoleMessage(V8MessageOrigin origin, double timestamp,
                                   const String16& message)
    : m_origin(origin),
      m_timestamp(timestamp),
      m_message(message),
      m_lineNumber(0),
      m_columnNumber(0),
      m_scriptId(0),
      m_contextId(0),
      m_type(ConsoleAPIType::kLog),
      m_exceptionId(0),
      m_revokedExceptionId(0) {}

206
V8ConsoleMessage::~V8ConsoleMessage() = default;
207 208 209 210 211

void V8ConsoleMessage::setLocation(const String16& url, unsigned lineNumber,
                                   unsigned columnNumber,
                                   std::unique_ptr<V8StackTraceImpl> stackTrace,
                                   int scriptId) {
212 213 214 215 216 217
  const char* dataURIPrefix = "data:";
  if (url.substring(0, strlen(dataURIPrefix)) == dataURIPrefix) {
    m_url = String16();
  } else {
    m_url = url;
  }
218 219 220 221 222 223 224 225
  m_lineNumber = lineNumber;
  m_columnNumber = columnNumber;
  m_stackTrace = std::move(stackTrace);
  m_scriptId = scriptId;
}

void V8ConsoleMessage::reportToFrontend(
    protocol::Console::Frontend* frontend) const {
226
  DCHECK_EQ(V8MessageOrigin::kConsole, m_origin);
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  String16 level = protocol::Console::ConsoleMessage::LevelEnum::Log;
  if (m_type == ConsoleAPIType::kDebug || m_type == ConsoleAPIType::kCount ||
      m_type == ConsoleAPIType::kTimeEnd)
    level = protocol::Console::ConsoleMessage::LevelEnum::Debug;
  else if (m_type == ConsoleAPIType::kError ||
           m_type == ConsoleAPIType::kAssert)
    level = protocol::Console::ConsoleMessage::LevelEnum::Error;
  else if (m_type == ConsoleAPIType::kWarning)
    level = protocol::Console::ConsoleMessage::LevelEnum::Warning;
  else if (m_type == ConsoleAPIType::kInfo)
    level = protocol::Console::ConsoleMessage::LevelEnum::Info;
  std::unique_ptr<protocol::Console::ConsoleMessage> result =
      protocol::Console::ConsoleMessage::create()
          .setSource(protocol::Console::ConsoleMessage::SourceEnum::ConsoleApi)
          .setLevel(level)
          .setText(m_message)
          .build();
244 245 246
  if (m_lineNumber) result->setLine(m_lineNumber);
  if (m_columnNumber) result->setColumn(m_columnNumber);
  if (!m_url.isEmpty()) result->setUrl(m_url);
247 248 249 250 251 252
  frontend->messageAdded(std::move(result));
}

std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
V8ConsoleMessage::wrapArguments(V8InspectorSessionImpl* session,
                                bool generatePreview) const {
253 254 255 256
  V8InspectorImpl* inspector = session->inspector();
  int contextGroupId = session->contextGroupId();
  int contextId = m_contextId;
  if (!m_arguments.size() || !contextId) return nullptr;
257
  InspectedContext* inspectedContext =
258
      inspector->getContext(contextGroupId, contextId);
259 260 261 262 263 264
  if (!inspectedContext) return nullptr;

  v8::Isolate* isolate = inspectedContext->isolate();
  v8::HandleScope handles(isolate);
  v8::Local<v8::Context> context = inspectedContext->context();

265
  auto args =
266
      std::make_unique<protocol::Array<protocol::Runtime::RemoteObject>>();
267 268 269 270 271 272 273 274

  v8::Local<v8::Value> value = m_arguments[0]->Get(isolate);
  if (value->IsObject() && m_type == ConsoleAPIType::kTable &&
      generatePreview) {
    v8::MaybeLocal<v8::Array> columns;
    if (m_arguments.size() > 1) {
      v8::Local<v8::Value> secondArgument = m_arguments[1]->Get(isolate);
      if (secondArgument->IsArray()) {
275
        columns = secondArgument.As<v8::Array>();
276 277 278 279 280 281 282 283
      } else if (secondArgument->IsString()) {
        v8::TryCatch tryCatch(isolate);
        v8::Local<v8::Array> array = v8::Array::New(isolate);
        if (array->Set(context, 0, secondArgument).IsJust()) {
          columns = array;
        }
      }
    }
284
    std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
285
        session->wrapTable(context, value.As<v8::Object>(), columns);
286 287
    inspectedContext = inspector->getContext(contextGroupId, contextId);
    if (!inspectedContext) return nullptr;
288
    if (wrapped) {
289
      args->emplace_back(std::move(wrapped));
290
    } else {
291
      args = nullptr;
292
    }
293 294 295 296 297
  } else {
    for (size_t i = 0; i < m_arguments.size(); ++i) {
      std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
          session->wrapObject(context, m_arguments[i]->Get(isolate), "console",
                              generatePreview);
298 299
      inspectedContext = inspector->getContext(contextGroupId, contextId);
      if (!inspectedContext) return nullptr;
300 301 302 303
      if (!wrapped) {
        args = nullptr;
        break;
      }
304
      args->emplace_back(std::move(wrapped));
305 306 307 308 309 310 311 312
    }
  }
  return args;
}

void V8ConsoleMessage::reportToFrontend(protocol::Runtime::Frontend* frontend,
                                        V8InspectorSessionImpl* session,
                                        bool generatePreview) const {
313 314 315
  int contextGroupId = session->contextGroupId();
  V8InspectorImpl* inspector = session->inspector();

316 317 318
  if (m_origin == V8MessageOrigin::kException) {
    std::unique_ptr<protocol::Runtime::RemoteObject> exception =
        wrapException(session, generatePreview);
319
    if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
320 321 322 323 324 325 326 327 328 329
    std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails =
        protocol::Runtime::ExceptionDetails::create()
            .setExceptionId(m_exceptionId)
            .setText(exception ? m_message : m_detailedMessage)
            .setLineNumber(m_lineNumber ? m_lineNumber - 1 : 0)
            .setColumnNumber(m_columnNumber ? m_columnNumber - 1 : 0)
            .build();
    if (m_scriptId)
      exceptionDetails->setScriptId(String16::fromInteger(m_scriptId));
    if (!m_url.isEmpty()) exceptionDetails->setUrl(m_url);
330 331 332 333
    if (m_stackTrace) {
      exceptionDetails->setStackTrace(
          m_stackTrace->buildInspectorObjectImpl(inspector->debugger()));
    }
334 335
    if (m_contextId) exceptionDetails->setExecutionContextId(m_contextId);
    if (exception) exceptionDetails->setException(std::move(exception));
336 337
    std::unique_ptr<protocol::DictionaryValue> data =
        getAssociatedExceptionData(inspector, session);
338
    if (data) exceptionDetails->setExceptionMetaData(std::move(data));
339 340 341 342 343 344 345 346 347 348
    frontend->exceptionThrown(m_timestamp, std::move(exceptionDetails));
    return;
  }
  if (m_origin == V8MessageOrigin::kRevokedException) {
    frontend->exceptionRevoked(m_message, m_revokedExceptionId);
    return;
  }
  if (m_origin == V8MessageOrigin::kConsole) {
    std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
        arguments = wrapArguments(session, generatePreview);
349
    if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
350
    if (!arguments) {
351 352
      arguments =
          std::make_unique<protocol::Array<protocol::Runtime::RemoteObject>>();
353 354 355 356 357 358
      if (!m_message.isEmpty()) {
        std::unique_ptr<protocol::Runtime::RemoteObject> messageArg =
            protocol::Runtime::RemoteObject::create()
                .setType(protocol::Runtime::RemoteObject::TypeEnum::String)
                .build();
        messageArg->setValue(protocol::StringValue::create(m_message));
359
        arguments->emplace_back(std::move(messageArg));
360 361
      }
    }
362 363
    Maybe<String16> consoleContext;
    if (!m_consoleContext.isEmpty()) consoleContext = m_consoleContext;
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    std::unique_ptr<protocol::Runtime::StackTrace> stackTrace;
    if (m_stackTrace) {
      switch (m_type) {
        case ConsoleAPIType::kAssert:
        case ConsoleAPIType::kError:
        case ConsoleAPIType::kTrace:
        case ConsoleAPIType::kWarning:
          stackTrace =
              m_stackTrace->buildInspectorObjectImpl(inspector->debugger());
          break;
        default:
          stackTrace =
              m_stackTrace->buildInspectorObjectImpl(inspector->debugger(), 0);
          break;
      }
    }
380 381
    frontend->consoleAPICalled(
        consoleAPITypeValue(m_type), std::move(arguments), m_contextId,
382
        m_timestamp, std::move(stackTrace), std::move(consoleContext));
383 384
    return;
  }
385
  UNREACHABLE();
386 387
}

388 389 390 391 392 393
std::unique_ptr<protocol::DictionaryValue>
V8ConsoleMessage::getAssociatedExceptionData(
    V8InspectorImpl* inspector, V8InspectorSessionImpl* session) const {
  if (!m_arguments.size() || !m_contextId) return nullptr;
  DCHECK_EQ(1u, m_arguments.size());

394
  v8::Isolate* isolate = inspector->isolate();
395 396 397 398 399
  v8::HandleScope handles(isolate);
  v8::MaybeLocal<v8::Value> maybe_exception = m_arguments[0]->Get(isolate);
  v8::Local<v8::Value> exception;
  if (!maybe_exception.ToLocal(&exception)) return nullptr;

400
  return inspector->getAssociatedExceptionDataForProtocol(exception);
401 402
}

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
std::unique_ptr<protocol::Runtime::RemoteObject>
V8ConsoleMessage::wrapException(V8InspectorSessionImpl* session,
                                bool generatePreview) const {
  if (!m_arguments.size() || !m_contextId) return nullptr;
  DCHECK_EQ(1u, m_arguments.size());
  InspectedContext* inspectedContext =
      session->inspector()->getContext(session->contextGroupId(), m_contextId);
  if (!inspectedContext) return nullptr;

  v8::Isolate* isolate = inspectedContext->isolate();
  v8::HandleScope handles(isolate);
  // TODO(dgozman): should we use different object group?
  return session->wrapObject(inspectedContext->context(),
                             m_arguments[0]->Get(isolate), "console",
                             generatePreview);
}

V8MessageOrigin V8ConsoleMessage::origin() const { return m_origin; }

ConsoleAPIType V8ConsoleMessage::type() const { return m_type; }

// static
std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForConsoleAPI(
426 427
    v8::Local<v8::Context> v8Context, int contextId, int groupId,
    V8InspectorImpl* inspector, double timestamp, ConsoleAPIType type,
428
    const std::vector<v8::Local<v8::Value>>& arguments,
429
    const String16& consoleContext,
430 431
    std::unique_ptr<V8StackTraceImpl> stackTrace) {
  v8::Isolate* isolate = v8Context->GetIsolate();
432

433
  std::unique_ptr<V8ConsoleMessage> message(
434 435 436 437 438 439 440
      new V8ConsoleMessage(V8MessageOrigin::kConsole, timestamp, String16()));
  if (stackTrace && !stackTrace->isEmpty()) {
    message->m_url = toString16(stackTrace->topSourceURL());
    message->m_lineNumber = stackTrace->topLineNumber();
    message->m_columnNumber = stackTrace->topColumnNumber();
  }
  message->m_stackTrace = std::move(stackTrace);
441
  message->m_consoleContext = consoleContext;
442
  message->m_type = type;
443
  message->m_contextId = contextId;
444
  for (size_t i = 0; i < arguments.size(); ++i) {
445 446
    std::unique_ptr<v8::Global<v8::Value>> argument(
        new v8::Global<v8::Value>(isolate, arguments.at(i)));
447
    argument->AnnotateStrongRetainer(kGlobalConsoleMessageHandleLabel);
448
    message->m_arguments.push_back(std::move(argument));
449 450 451
    message->m_v8Size +=
        v8::debug::EstimatedValueSize(isolate, arguments.at(i));
  }
452 453 454 455 456
  for (size_t i = 0, num_args = arguments.size(); i < num_args; ++i) {
    if (i) message->m_message += String16(" ");
    message->m_message +=
        V8ValueStringBuilder::toString(arguments[i], v8Context);
  }
457

458
  v8::Isolate::MessageErrorLevel clientLevel = v8::Isolate::kMessageInfo;
459
  if (type == ConsoleAPIType::kDebug || type == ConsoleAPIType::kCount ||
460 461 462 463 464 465 466
      type == ConsoleAPIType::kTimeEnd) {
    clientLevel = v8::Isolate::kMessageDebug;
  } else if (type == ConsoleAPIType::kError ||
             type == ConsoleAPIType::kAssert) {
    clientLevel = v8::Isolate::kMessageError;
  } else if (type == ConsoleAPIType::kWarning) {
    clientLevel = v8::Isolate::kMessageWarning;
467
  } else if (type == ConsoleAPIType::kInfo) {
468
    clientLevel = v8::Isolate::kMessageInfo;
469 470
  } else if (type == ConsoleAPIType::kLog) {
    clientLevel = v8::Isolate::kMessageLog;
471 472 473 474
  }

  if (type != ConsoleAPIType::kClear) {
    inspector->client()->consoleAPIMessage(
475
        groupId, clientLevel, toStringView(message->m_message),
476 477 478 479
        toStringView(message->m_url), message->m_lineNumber,
        message->m_columnNumber, message->m_stackTrace.get());
  }

480 481 482 483 484 485 486 487 488 489
  return message;
}

// static
std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForException(
    double timestamp, const String16& detailedMessage, const String16& url,
    unsigned lineNumber, unsigned columnNumber,
    std::unique_ptr<V8StackTraceImpl> stackTrace, int scriptId,
    v8::Isolate* isolate, const String16& message, int contextId,
    v8::Local<v8::Value> exception, unsigned exceptionId) {
490
  std::unique_ptr<V8ConsoleMessage> consoleMessage(
491 492 493 494 495 496 497 498
      new V8ConsoleMessage(V8MessageOrigin::kException, timestamp, message));
  consoleMessage->setLocation(url, lineNumber, columnNumber,
                              std::move(stackTrace), scriptId);
  consoleMessage->m_exceptionId = exceptionId;
  consoleMessage->m_detailedMessage = detailedMessage;
  if (contextId && !exception.IsEmpty()) {
    consoleMessage->m_contextId = contextId;
    consoleMessage->m_arguments.push_back(
499 500
        std::unique_ptr<v8::Global<v8::Value>>(
            new v8::Global<v8::Value>(isolate, exception)));
501 502
    consoleMessage->m_v8Size +=
        v8::debug::EstimatedValueSize(isolate, exception);
503 504 505 506 507 508 509 510
  }
  return consoleMessage;
}

// static
std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForRevokedException(
    double timestamp, const String16& messageText,
    unsigned revokedExceptionId) {
511
  std::unique_ptr<V8ConsoleMessage> message(new V8ConsoleMessage(
512 513 514 515 516 517 518 519 520 521 522
      V8MessageOrigin::kRevokedException, timestamp, messageText));
  message->m_revokedExceptionId = revokedExceptionId;
  return message;
}

void V8ConsoleMessage::contextDestroyed(int contextId) {
  if (contextId != m_contextId) return;
  m_contextId = 0;
  if (m_message.isEmpty()) m_message = "<message collected>";
  Arguments empty;
  m_arguments.swap(empty);
523
  m_v8Size = 0;
524 525
}

526 527
// ------------------------ V8ConsoleMessageStorage
// ----------------------------
528 529 530

V8ConsoleMessageStorage::V8ConsoleMessageStorage(V8InspectorImpl* inspector,
                                                 int contextGroupId)
531
    : m_inspector(inspector), m_contextGroupId(contextGroupId) {}
532 533 534

V8ConsoleMessageStorage::~V8ConsoleMessageStorage() { clear(); }

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
namespace {

void TraceV8ConsoleMessageEvent(V8MessageOrigin origin, ConsoleAPIType type) {
  // Change in this function requires adjustment of Catapult/Telemetry metric
  // tracing/tracing/metrics/console_error_metric.html.
  // See https://crbug.com/880432
  if (origin == V8MessageOrigin::kException) {
    TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Exception",
                         TRACE_EVENT_SCOPE_THREAD);
  } else if (type == ConsoleAPIType::kError) {
    TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Error",
                         TRACE_EVENT_SCOPE_THREAD);
  } else if (type == ConsoleAPIType::kAssert) {
    TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Assert",
                         TRACE_EVENT_SCOPE_THREAD);
  }
}

}  // anonymous namespace

555 556
void V8ConsoleMessageStorage::addMessage(
    std::unique_ptr<V8ConsoleMessage> message) {
557 558
  int contextGroupId = m_contextGroupId;
  V8InspectorImpl* inspector = m_inspector;
559 560
  if (message->type() == ConsoleAPIType::kClear) clear();

561 562
  TraceV8ConsoleMessageEvent(message->origin(), message->type());

563 564 565 566 567 568
  inspector->forEachSession(
      contextGroupId, [&message](V8InspectorSessionImpl* session) {
        if (message->origin() == V8MessageOrigin::kConsole)
          session->consoleAgent()->messageAdded(message.get());
        session->runtimeAgent()->messageAdded(message.get());
      });
569
  if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
570 571 572

  DCHECK(m_messages.size() <= maxConsoleMessageCount);
  if (m_messages.size() == maxConsoleMessageCount) {
573 574 575 576 577 578
    m_estimatedSize -= m_messages.front()->estimatedSize();
    m_messages.pop_front();
  }
  while (m_estimatedSize + message->estimatedSize() > maxConsoleMessageV8Size &&
         !m_messages.empty()) {
    m_estimatedSize -= m_messages.front()->estimatedSize();
579 580
    m_messages.pop_front();
  }
581

582
  m_messages.push_back(std::move(message));
583
  m_estimatedSize += m_messages.back()->estimatedSize();
584 585 586 587
}

void V8ConsoleMessageStorage::clear() {
  m_messages.clear();
588
  m_estimatedSize = 0;
589 590 591 592
  m_inspector->forEachSession(m_contextGroupId,
                              [](V8InspectorSessionImpl* session) {
                                session->releaseObjectGroup("console");
                              });
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  m_data.clear();
}

bool V8ConsoleMessageStorage::shouldReportDeprecationMessage(
    int contextId, const String16& method) {
  std::set<String16>& reportedDeprecationMessages =
      m_data[contextId].m_reportedDeprecationMessages;
  auto it = reportedDeprecationMessages.find(method);
  if (it != reportedDeprecationMessages.end()) return false;
  reportedDeprecationMessages.insert(it, method);
  return true;
}

int V8ConsoleMessageStorage::count(int contextId, const String16& id) {
  return ++m_data[contextId].m_count[id];
}

void V8ConsoleMessageStorage::time(int contextId, const String16& id) {
  m_data[contextId].m_time[id] = m_inspector->client()->currentTimeMS();
}

614 615 616 617 618 619 620 621
bool V8ConsoleMessageStorage::countReset(int contextId, const String16& id) {
  std::map<String16, int>& count_map = m_data[contextId].m_count;
  if (count_map.find(id) == count_map.end()) return false;

  count_map[id] = 0;
  return true;
}

622 623 624 625 626 627 628
double V8ConsoleMessageStorage::timeLog(int contextId, const String16& id) {
  std::map<String16, double>& time = m_data[contextId].m_time;
  auto it = time.find(id);
  if (it == time.end()) return 0.0;
  return m_inspector->client()->currentTimeMS() - it->second;
}

629 630 631 632 633 634 635
double V8ConsoleMessageStorage::timeEnd(int contextId, const String16& id) {
  std::map<String16, double>& time = m_data[contextId].m_time;
  auto it = time.find(id);
  if (it == time.end()) return 0.0;
  double elapsed = m_inspector->client()->currentTimeMS() - it->second;
  time.erase(it);
  return elapsed;
636 637
}

638 639 640 641 642
bool V8ConsoleMessageStorage::hasTimer(int contextId, const String16& id) {
  const std::map<String16, double>& time = m_data[contextId].m_time;
  return time.find(id) != time.end();
}

643
void V8ConsoleMessageStorage::contextDestroyed(int contextId) {
644 645
  m_estimatedSize = 0;
  for (size_t i = 0; i < m_messages.size(); ++i) {
646
    m_messages[i]->contextDestroyed(contextId);
647 648
    m_estimatedSize += m_messages[i]->estimatedSize();
  }
649 650
  auto it = m_data.find(contextId);
  if (it != m_data.end()) m_data.erase(contextId);
651 652 653
}

}  // namespace v8_inspector