1 // Copyright 2016 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/inspector/v8-console-message.h"
6 
7 #include "include/v8-container.h"
8 #include "include/v8-context.h"
9 #include "include/v8-inspector.h"
10 #include "include/v8-microtask-queue.h"
11 #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 #include "src/inspector/string-util.h"
16 #include "src/inspector/v8-console-agent-impl.h"
17 #include "src/inspector/v8-inspector-impl.h"
18 #include "src/inspector/v8-inspector-session-impl.h"
19 #include "src/inspector/v8-runtime-agent-impl.h"
20 #include "src/inspector/v8-stack-trace-impl.h"
21 #include "src/inspector/value-mirror.h"
22 #include "src/tracing/trace-event.h"
23 
24 namespace v8_inspector {
25 
26 namespace {
27 
consoleAPITypeValue(ConsoleAPIType type)28 String16 consoleAPITypeValue(ConsoleAPIType type) {
29   switch (type) {
30     case ConsoleAPIType::kLog:
31       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
32     case ConsoleAPIType::kDebug:
33       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug;
34     case ConsoleAPIType::kInfo:
35       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Info;
36     case ConsoleAPIType::kError:
37       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Error;
38     case ConsoleAPIType::kWarning:
39       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Warning;
40     case ConsoleAPIType::kClear:
41       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Clear;
42     case ConsoleAPIType::kDir:
43       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dir;
44     case ConsoleAPIType::kDirXML:
45       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dirxml;
46     case ConsoleAPIType::kTable:
47       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Table;
48     case ConsoleAPIType::kTrace:
49       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Trace;
50     case ConsoleAPIType::kStartGroup:
51       return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroup;
52     case ConsoleAPIType::kStartGroupCollapsed:
53       return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroupCollapsed;
54     case ConsoleAPIType::kEndGroup:
55       return protocol::Runtime::ConsoleAPICalled::TypeEnum::EndGroup;
56     case ConsoleAPIType::kAssert:
57       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Assert;
58     case ConsoleAPIType::kTimeEnd:
59       return protocol::Runtime::ConsoleAPICalled::TypeEnum::TimeEnd;
60     case ConsoleAPIType::kCount:
61       return protocol::Runtime::ConsoleAPICalled::TypeEnum::Count;
62   }
63   return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
64 }
65 
66 const char kGlobalConsoleMessageHandleLabel[] = "DevTools console";
67 const unsigned maxConsoleMessageCount = 1000;
68 const int maxConsoleMessageV8Size = 10 * 1024 * 1024;
69 const unsigned maxArrayItemsLimit = 10000;
70 const unsigned maxStackDepthLimit = 32;
71 
72 class V8ValueStringBuilder {
73  public:
toString(v8::Local<v8::Value> value, v8::Local<v8::Context> context)74   static String16 toString(v8::Local<v8::Value> value,
75                            v8::Local<v8::Context> context) {
76     V8ValueStringBuilder builder(context);
77     if (!builder.append(value)) return String16();
78     return builder.toString();
79   }
80 
81  private:
82   enum {
83     IgnoreNull = 1 << 0,
84     IgnoreUndefined = 1 << 1,
85   };
86 
V8ValueStringBuilder(v8::Local<v8::Context> context)87   explicit V8ValueStringBuilder(v8::Local<v8::Context> context)
88       : m_arrayLimit(maxArrayItemsLimit),
89         m_isolate(context->GetIsolate()),
90         m_tryCatch(context->GetIsolate()),
91         m_context(context) {}
92 
append(v8::Local<v8::Value> value, unsigned ignoreOptions = 0)93   bool append(v8::Local<v8::Value> value, unsigned ignoreOptions = 0) {
94     if (value.IsEmpty()) return true;
95     if ((ignoreOptions & IgnoreNull) && value->IsNull()) return true;
96     if ((ignoreOptions & IgnoreUndefined) && value->IsUndefined()) return true;
97     if (value->IsString()) return append(value.As<v8::String>());
98     if (value->IsStringObject())
99       return append(value.As<v8::StringObject>()->ValueOf());
100     if (value->IsBigInt()) return append(value.As<v8::BigInt>());
101     if (value->IsBigIntObject())
102       return append(value.As<v8::BigIntObject>()->ValueOf());
103     if (value->IsSymbol()) return append(value.As<v8::Symbol>());
104     if (value->IsSymbolObject())
105       return append(value.As<v8::SymbolObject>()->ValueOf());
106     if (value->IsNumberObject()) {
107       m_builder.append(
108           String16::fromDouble(value.As<v8::NumberObject>()->ValueOf(), 6));
109       return true;
110     }
111     if (value->IsBooleanObject()) {
112       m_builder.append(value.As<v8::BooleanObject>()->ValueOf() ? "true"
113                                                                 : "false");
114       return true;
115     }
116     if (value->IsArray()) return append(value.As<v8::Array>());
117     if (value->IsProxy()) {
118       m_builder.append("[object Proxy]");
119       return true;
120     }
121     if (value->IsObject() && !value->IsDate() && !value->IsFunction() &&
122         !value->IsNativeError() && !value->IsRegExp()) {
123       v8::Local<v8::Object> object = value.As<v8::Object>();
124       v8::Local<v8::String> stringValue;
125       if (object->ObjectProtoToString(m_context).ToLocal(&stringValue))
126         return append(stringValue);
127     }
128     v8::Local<v8::String> stringValue;
129     if (!value->ToString(m_context).ToLocal(&stringValue)) return false;
130     return append(stringValue);
131   }
132 
append(v8::Local<v8::Array> array)133   bool append(v8::Local<v8::Array> array) {
134     for (const auto& it : m_visitedArrays) {
135       if (it == array) return true;
136     }
137     uint32_t length = array->Length();
138     if (length > m_arrayLimit) return false;
139     if (m_visitedArrays.size() > maxStackDepthLimit) return false;
140 
141     bool result = true;
142     m_arrayLimit -= length;
143     m_visitedArrays.push_back(array);
144     for (uint32_t i = 0; i < length; ++i) {
145       if (i) m_builder.append(',');
146       v8::Local<v8::Value> value;
147       if (!array->Get(m_context, i).ToLocal(&value)) continue;
148       if (!append(value, IgnoreNull | IgnoreUndefined)) {
149         result = false;
150         break;
151       }
152     }
153     m_visitedArrays.pop_back();
154     return result;
155   }
156 
append(v8::Local<v8::Symbol> symbol)157   bool append(v8::Local<v8::Symbol> symbol) {
158     m_builder.append("Symbol(");
159     bool result = append(symbol->Description(m_isolate), IgnoreUndefined);
160     m_builder.append(')');
161     return result;
162   }
163 
append(v8::Local<v8::BigInt> bigint)164   bool append(v8::Local<v8::BigInt> bigint) {
165     v8::Local<v8::String> bigint_string;
166     if (!bigint->ToString(m_context).ToLocal(&bigint_string)) return false;
167     bool result = append(bigint_string);
168     if (m_tryCatch.HasCaught()) return false;
169     m_builder.append('n');
170     return result;
171   }
172 
append(v8::Local<v8::String> string)173   bool append(v8::Local<v8::String> string) {
174     if (m_tryCatch.HasCaught()) return false;
175     if (!string.IsEmpty()) {
176       m_builder.append(toProtocolString(m_isolate, string));
177     }
178     return true;
179   }
180 
toString()181   String16 toString() {
182     if (m_tryCatch.HasCaught()) return String16();
183     return m_builder.toString();
184   }
185 
186   uint32_t m_arrayLimit;
187   v8::Isolate* m_isolate;
188   String16Builder m_builder;
189   std::vector<v8::Local<v8::Array>> m_visitedArrays;
190   v8::TryCatch m_tryCatch;
191   v8::Local<v8::Context> m_context;
192 };
193 
194 }  // namespace
195 
V8ConsoleMessage(V8MessageOrigin origin, double timestamp, const String16& message)196 V8ConsoleMessage::V8ConsoleMessage(V8MessageOrigin origin, double timestamp,
197                                    const String16& message)
198     : m_origin(origin),
199       m_timestamp(timestamp),
200       m_message(message),
201       m_lineNumber(0),
202       m_columnNumber(0),
203       m_scriptId(0),
204       m_contextId(0),
205       m_type(ConsoleAPIType::kLog),
206       m_exceptionId(0),
207       m_revokedExceptionId(0) {}
208 
209 V8ConsoleMessage::~V8ConsoleMessage() = default;
210 
setLocation(const String16& url, unsigned lineNumber, unsigned columnNumber, std::unique_ptr<V8StackTraceImpl> stackTrace, int scriptId)211 void V8ConsoleMessage::setLocation(const String16& url, unsigned lineNumber,
212                                    unsigned columnNumber,
213                                    std::unique_ptr<V8StackTraceImpl> stackTrace,
214                                    int scriptId) {
215   const char* dataURIPrefix = "data:";
216   if (url.substring(0, strlen(dataURIPrefix)) == dataURIPrefix) {
217     m_url = String16();
218   } else {
219     m_url = url;
220   }
221   m_lineNumber = lineNumber;
222   m_columnNumber = columnNumber;
223   m_stackTrace = std::move(stackTrace);
224   m_scriptId = scriptId;
225 }
226 
reportToFrontend( protocol::Console::Frontend* frontend) const227 void V8ConsoleMessage::reportToFrontend(
228     protocol::Console::Frontend* frontend) const {
229   DCHECK_EQ(V8MessageOrigin::kConsole, m_origin);
230   String16 level = protocol::Console::ConsoleMessage::LevelEnum::Log;
231   if (m_type == ConsoleAPIType::kDebug || m_type == ConsoleAPIType::kCount ||
232       m_type == ConsoleAPIType::kTimeEnd)
233     level = protocol::Console::ConsoleMessage::LevelEnum::Debug;
234   else if (m_type == ConsoleAPIType::kError ||
235            m_type == ConsoleAPIType::kAssert)
236     level = protocol::Console::ConsoleMessage::LevelEnum::Error;
237   else if (m_type == ConsoleAPIType::kWarning)
238     level = protocol::Console::ConsoleMessage::LevelEnum::Warning;
239   else if (m_type == ConsoleAPIType::kInfo)
240     level = protocol::Console::ConsoleMessage::LevelEnum::Info;
241   std::unique_ptr<protocol::Console::ConsoleMessage> result =
242       protocol::Console::ConsoleMessage::create()
243           .setSource(protocol::Console::ConsoleMessage::SourceEnum::ConsoleApi)
244           .setLevel(level)
245           .setText(m_message)
246           .build();
247   if (m_lineNumber) result->setLine(m_lineNumber);
248   if (m_columnNumber) result->setColumn(m_columnNumber);
249   if (!m_url.isEmpty()) result->setUrl(m_url);
250   frontend->messageAdded(std::move(result));
251 }
252 
253 std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
wrapArguments(V8InspectorSessionImpl* session, bool generatePreview) const254 V8ConsoleMessage::wrapArguments(V8InspectorSessionImpl* session,
255                                 bool generatePreview) const {
256   V8InspectorImpl* inspector = session->inspector();
257   int contextGroupId = session->contextGroupId();
258   int contextId = m_contextId;
259   if (!m_arguments.size() || !contextId) return nullptr;
260   InspectedContext* inspectedContext =
261       inspector->getContext(contextGroupId, contextId);
262   if (!inspectedContext) return nullptr;
263 
264   v8::Isolate* isolate = inspectedContext->isolate();
265   v8::HandleScope handles(isolate);
266   v8::Local<v8::Context> context = inspectedContext->context();
267 
268   auto args =
269       std::make_unique<protocol::Array<protocol::Runtime::RemoteObject>>();
270 
271   v8::Local<v8::Value> value = m_arguments[0]->Get(isolate);
272   if (value->IsObject() && m_type == ConsoleAPIType::kTable &&
273       generatePreview) {
274     v8::MaybeLocal<v8::Array> columns;
275     if (m_arguments.size() > 1) {
276       v8::Local<v8::Value> secondArgument = m_arguments[1]->Get(isolate);
277       if (secondArgument->IsArray()) {
278         columns = secondArgument.As<v8::Array>();
279       } else if (secondArgument->IsString()) {
280         v8::TryCatch tryCatch(isolate);
281         v8::Local<v8::Array> array = v8::Array::New(isolate);
282         if (array->Set(context, 0, secondArgument).IsJust()) {
283           columns = array;
284         }
285       }
286     }
287     std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
288         session->wrapTable(context, value.As<v8::Object>(), columns);
289     inspectedContext = inspector->getContext(contextGroupId, contextId);
290     if (!inspectedContext) return nullptr;
291     if (wrapped) {
292       args->emplace_back(std::move(wrapped));
293     } else {
294       args = nullptr;
295     }
296   } else {
297     for (size_t i = 0; i < m_arguments.size(); ++i) {
298       std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
299           session->wrapObject(context, m_arguments[i]->Get(isolate), "console",
300                               generatePreview);
301       inspectedContext = inspector->getContext(contextGroupId, contextId);
302       if (!inspectedContext) return nullptr;
303       if (!wrapped) {
304         args = nullptr;
305         break;
306       }
307       args->emplace_back(std::move(wrapped));
308     }
309   }
310   return args;
311 }
312 
reportToFrontend(protocol::Runtime::Frontend* frontend, V8InspectorSessionImpl* session, bool generatePreview) const313 void V8ConsoleMessage::reportToFrontend(protocol::Runtime::Frontend* frontend,
314                                         V8InspectorSessionImpl* session,
315                                         bool generatePreview) const {
316   int contextGroupId = session->contextGroupId();
317   V8InspectorImpl* inspector = session->inspector();
318 
319   if (m_origin == V8MessageOrigin::kException) {
320     std::unique_ptr<protocol::Runtime::RemoteObject> exception =
321         wrapException(session, generatePreview);
322     if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
323     std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails =
324         protocol::Runtime::ExceptionDetails::create()
325             .setExceptionId(m_exceptionId)
326             .setText(exception ? m_message : m_detailedMessage)
327             .setLineNumber(m_lineNumber ? m_lineNumber - 1 : 0)
328             .setColumnNumber(m_columnNumber ? m_columnNumber - 1 : 0)
329             .build();
330     if (m_scriptId)
331       exceptionDetails->setScriptId(String16::fromInteger(m_scriptId));
332     if (!m_url.isEmpty()) exceptionDetails->setUrl(m_url);
333     if (m_stackTrace) {
334       exceptionDetails->setStackTrace(
335           m_stackTrace->buildInspectorObjectImpl(inspector->debugger()));
336     }
337     if (m_contextId) exceptionDetails->setExecutionContextId(m_contextId);
338     if (exception) exceptionDetails->setException(std::move(exception));
339     std::unique_ptr<protocol::DictionaryValue> data =
340         getAssociatedExceptionData(inspector, session);
341     if (data) exceptionDetails->setExceptionMetaData(std::move(data));
342     frontend->exceptionThrown(m_timestamp, std::move(exceptionDetails));
343     return;
344   }
345   if (m_origin == V8MessageOrigin::kRevokedException) {
346     frontend->exceptionRevoked(m_message, m_revokedExceptionId);
347     return;
348   }
349   if (m_origin == V8MessageOrigin::kConsole) {
350     std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
351         arguments = wrapArguments(session, generatePreview);
352     if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
353     if (!arguments) {
354       arguments =
355           std::make_unique<protocol::Array<protocol::Runtime::RemoteObject>>();
356       if (!m_message.isEmpty()) {
357         std::unique_ptr<protocol::Runtime::RemoteObject> messageArg =
358             protocol::Runtime::RemoteObject::create()
359                 .setType(protocol::Runtime::RemoteObject::TypeEnum::String)
360                 .build();
361         messageArg->setValue(protocol::StringValue::create(m_message));
362         arguments->emplace_back(std::move(messageArg));
363       }
364     }
365     Maybe<String16> consoleContext;
366     if (!m_consoleContext.isEmpty()) consoleContext = m_consoleContext;
367     std::unique_ptr<protocol::Runtime::StackTrace> stackTrace;
368     if (m_stackTrace) {
369       switch (m_type) {
370         case ConsoleAPIType::kAssert:
371         case ConsoleAPIType::kError:
372         case ConsoleAPIType::kTrace:
373         case ConsoleAPIType::kWarning:
374           stackTrace =
375               m_stackTrace->buildInspectorObjectImpl(inspector->debugger());
376           break;
377         default:
378           stackTrace =
379               m_stackTrace->buildInspectorObjectImpl(inspector->debugger(), 0);
380           break;
381       }
382     }
383     frontend->consoleAPICalled(
384         consoleAPITypeValue(m_type), std::move(arguments), m_contextId,
385         m_timestamp, std::move(stackTrace), std::move(consoleContext));
386     return;
387   }
388   UNREACHABLE();
389 }
390 
391 std::unique_ptr<protocol::DictionaryValue>
getAssociatedExceptionData( V8InspectorImpl* inspector, V8InspectorSessionImpl* session) const392 V8ConsoleMessage::getAssociatedExceptionData(
393     V8InspectorImpl* inspector, V8InspectorSessionImpl* session) const {
394   if (!m_arguments.size() || !m_contextId) return nullptr;
395   DCHECK_EQ(1u, m_arguments.size());
396 
397   v8::Isolate* isolate = inspector->isolate();
398   v8::HandleScope handles(isolate);
399   v8::MaybeLocal<v8::Value> maybe_exception = m_arguments[0]->Get(isolate);
400   v8::Local<v8::Value> exception;
401   if (!maybe_exception.ToLocal(&exception)) return nullptr;
402 
403   return inspector->getAssociatedExceptionDataForProtocol(exception);
404 }
405 
406 std::unique_ptr<protocol::Runtime::RemoteObject>
wrapException(V8InspectorSessionImpl* session, bool generatePreview) const407 V8ConsoleMessage::wrapException(V8InspectorSessionImpl* session,
408                                 bool generatePreview) const {
409   if (!m_arguments.size() || !m_contextId) return nullptr;
410   DCHECK_EQ(1u, m_arguments.size());
411   InspectedContext* inspectedContext =
412       session->inspector()->getContext(session->contextGroupId(), m_contextId);
413   if (!inspectedContext) return nullptr;
414 
415   v8::Isolate* isolate = inspectedContext->isolate();
416   v8::HandleScope handles(isolate);
417   // TODO(dgozman): should we use different object group?
418   return session->wrapObject(inspectedContext->context(),
419                              m_arguments[0]->Get(isolate), "console",
420                              generatePreview);
421 }
422 
origin() const423 V8MessageOrigin V8ConsoleMessage::origin() const { return m_origin; }
424 
type() const425 ConsoleAPIType V8ConsoleMessage::type() const { return m_type; }
426 
427 // static
createForConsoleAPI( v8::Local<v8::Context> v8Context, int contextId, int groupId, V8InspectorImpl* inspector, double timestamp, ConsoleAPIType type, const std::vector<v8::Local<v8::Value>>& arguments, const String16& consoleContext, std::unique_ptr<V8StackTraceImpl> stackTrace)428 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForConsoleAPI(
429     v8::Local<v8::Context> v8Context, int contextId, int groupId,
430     V8InspectorImpl* inspector, double timestamp, ConsoleAPIType type,
431     const std::vector<v8::Local<v8::Value>>& arguments,
432     const String16& consoleContext,
433     std::unique_ptr<V8StackTraceImpl> stackTrace) {
434   v8::Isolate* isolate = v8Context->GetIsolate();
435 
436   std::unique_ptr<V8ConsoleMessage> message(
437       new V8ConsoleMessage(V8MessageOrigin::kConsole, timestamp, String16()));
438   if (stackTrace && !stackTrace->isEmpty()) {
439     message->m_url = toString16(stackTrace->topSourceURL());
440     message->m_lineNumber = stackTrace->topLineNumber();
441     message->m_columnNumber = stackTrace->topColumnNumber();
442   }
443   message->m_stackTrace = std::move(stackTrace);
444   message->m_consoleContext = consoleContext;
445   message->m_type = type;
446   message->m_contextId = contextId;
447   for (size_t i = 0; i < arguments.size(); ++i) {
448     std::unique_ptr<v8::Global<v8::Value>> argument(
449         new v8::Global<v8::Value>(isolate, arguments.at(i)));
450     argument->AnnotateStrongRetainer(kGlobalConsoleMessageHandleLabel);
451     message->m_arguments.push_back(std::move(argument));
452     message->m_v8Size +=
453         v8::debug::EstimatedValueSize(isolate, arguments.at(i));
454   }
455   for (size_t i = 0, num_args = arguments.size(); i < num_args; ++i) {
456     if (i) message->m_message += String16(" ");
457     message->m_message +=
458         V8ValueStringBuilder::toString(arguments[i], v8Context);
459   }
460 
461   v8::Isolate::MessageErrorLevel clientLevel = v8::Isolate::kMessageInfo;
462   if (type == ConsoleAPIType::kDebug || type == ConsoleAPIType::kCount ||
463       type == ConsoleAPIType::kTimeEnd) {
464     clientLevel = v8::Isolate::kMessageDebug;
465   } else if (type == ConsoleAPIType::kError ||
466              type == ConsoleAPIType::kAssert) {
467     clientLevel = v8::Isolate::kMessageError;
468   } else if (type == ConsoleAPIType::kWarning) {
469     clientLevel = v8::Isolate::kMessageWarning;
470   } else if (type == ConsoleAPIType::kInfo) {
471     clientLevel = v8::Isolate::kMessageInfo;
472   } else if (type == ConsoleAPIType::kLog) {
473     clientLevel = v8::Isolate::kMessageLog;
474   }
475 
476   if (type != ConsoleAPIType::kClear) {
477     inspector->client()->consoleAPIMessage(
478         groupId, clientLevel, toStringView(message->m_message),
479         toStringView(message->m_url), message->m_lineNumber,
480         message->m_columnNumber, message->m_stackTrace.get());
481   }
482 
483   return message;
484 }
485 
486 // static
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)487 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForException(
488     double timestamp, const String16& detailedMessage, const String16& url,
489     unsigned lineNumber, unsigned columnNumber,
490     std::unique_ptr<V8StackTraceImpl> stackTrace, int scriptId,
491     v8::Isolate* isolate, const String16& message, int contextId,
492     v8::Local<v8::Value> exception, unsigned exceptionId) {
493   std::unique_ptr<V8ConsoleMessage> consoleMessage(
494       new V8ConsoleMessage(V8MessageOrigin::kException, timestamp, message));
495   consoleMessage->setLocation(url, lineNumber, columnNumber,
496                               std::move(stackTrace), scriptId);
497   consoleMessage->m_exceptionId = exceptionId;
498   consoleMessage->m_detailedMessage = detailedMessage;
499   if (contextId && !exception.IsEmpty()) {
500     consoleMessage->m_contextId = contextId;
501     consoleMessage->m_arguments.push_back(
502         std::unique_ptr<v8::Global<v8::Value>>(
503             new v8::Global<v8::Value>(isolate, exception)));
504     consoleMessage->m_v8Size +=
505         v8::debug::EstimatedValueSize(isolate, exception);
506   }
507   return consoleMessage;
508 }
509 
510 // static
createForRevokedException( double timestamp, const String16& messageText, unsigned revokedExceptionId)511 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForRevokedException(
512     double timestamp, const String16& messageText,
513     unsigned revokedExceptionId) {
514   std::unique_ptr<V8ConsoleMessage> message(new V8ConsoleMessage(
515       V8MessageOrigin::kRevokedException, timestamp, messageText));
516   message->m_revokedExceptionId = revokedExceptionId;
517   return message;
518 }
519 
contextDestroyed(int contextId)520 void V8ConsoleMessage::contextDestroyed(int contextId) {
521   if (contextId != m_contextId) return;
522   m_contextId = 0;
523   if (m_message.isEmpty()) m_message = "<message collected>";
524   Arguments empty;
525   m_arguments.swap(empty);
526   m_v8Size = 0;
527 }
528 
529 // ------------------------ V8ConsoleMessageStorage
530 // ----------------------------
531 
V8ConsoleMessageStorage(V8InspectorImpl* inspector, int contextGroupId)532 V8ConsoleMessageStorage::V8ConsoleMessageStorage(V8InspectorImpl* inspector,
533                                                  int contextGroupId)
534     : m_inspector(inspector), m_contextGroupId(contextGroupId) {}
535 
~V8ConsoleMessageStorage()536 V8ConsoleMessageStorage::~V8ConsoleMessageStorage() { clear(); }
537 
538 namespace {
539 
TraceV8ConsoleMessageEvent(V8MessageOrigin origin, ConsoleAPIType type)540 void TraceV8ConsoleMessageEvent(V8MessageOrigin origin, ConsoleAPIType type) {
541   // Change in this function requires adjustment of Catapult/Telemetry metric
542   // tracing/tracing/metrics/console_error_metric.html.
543   // See https://crbug.com/880432
544   if (origin == V8MessageOrigin::kException) {
545     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Exception",
546                          TRACE_EVENT_SCOPE_THREAD);
547   } else if (type == ConsoleAPIType::kError) {
548     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Error",
549                          TRACE_EVENT_SCOPE_THREAD);
550   } else if (type == ConsoleAPIType::kAssert) {
551     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Assert",
552                          TRACE_EVENT_SCOPE_THREAD);
553   }
554 }
555 
556 }  // anonymous namespace
557 
addMessage( std::unique_ptr<V8ConsoleMessage> message)558 void V8ConsoleMessageStorage::addMessage(
559     std::unique_ptr<V8ConsoleMessage> message) {
560   int contextGroupId = m_contextGroupId;
561   V8InspectorImpl* inspector = m_inspector;
562   if (message->type() == ConsoleAPIType::kClear) clear();
563 
564   TraceV8ConsoleMessageEvent(message->origin(), message->type());
565 
566   inspector->forEachSession(
567       contextGroupId, [&message](V8InspectorSessionImpl* session) {
568         if (message->origin() == V8MessageOrigin::kConsole)
569           session->consoleAgent()->messageAdded(message.get());
570         session->runtimeAgent()->messageAdded(message.get());
571       });
572   if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
573 
574   DCHECK(m_messages.size() <= maxConsoleMessageCount);
575   if (m_messages.size() == maxConsoleMessageCount) {
576     m_estimatedSize -= m_messages.front()->estimatedSize();
577     m_messages.pop_front();
578   }
579   while (m_estimatedSize + message->estimatedSize() > maxConsoleMessageV8Size &&
580          !m_messages.empty()) {
581     m_estimatedSize -= m_messages.front()->estimatedSize();
582     m_messages.pop_front();
583   }
584 
585   m_messages.push_back(std::move(message));
586   m_estimatedSize += m_messages.back()->estimatedSize();
587 }
588 
clear()589 void V8ConsoleMessageStorage::clear() {
590   m_messages.clear();
591   m_estimatedSize = 0;
592   m_inspector->forEachSession(m_contextGroupId,
593                               [](V8InspectorSessionImpl* session) {
594                                 session->releaseObjectGroup("console");
595                               });
596   m_data.clear();
597 }
598 
shouldReportDeprecationMessage( int contextId, const String16& method)599 bool V8ConsoleMessageStorage::shouldReportDeprecationMessage(
600     int contextId, const String16& method) {
601   std::set<String16>& reportedDeprecationMessages =
602       m_data[contextId].m_reportedDeprecationMessages;
603   auto it = reportedDeprecationMessages.find(method);
604   if (it != reportedDeprecationMessages.end()) return false;
605   reportedDeprecationMessages.insert(it, method);
606   return true;
607 }
608 
count(int contextId, const String16& id)609 int V8ConsoleMessageStorage::count(int contextId, const String16& id) {
610   return ++m_data[contextId].m_count[id];
611 }
612 
time(int contextId, const String16& id)613 void V8ConsoleMessageStorage::time(int contextId, const String16& id) {
614   m_data[contextId].m_time[id] = m_inspector->client()->currentTimeMS();
615 }
616 
countReset(int contextId, const String16& id)617 bool V8ConsoleMessageStorage::countReset(int contextId, const String16& id) {
618   std::map<String16, int>& count_map = m_data[contextId].m_count;
619   if (count_map.find(id) == count_map.end()) return false;
620 
621   count_map[id] = 0;
622   return true;
623 }
624 
timeLog(int contextId, const String16& id)625 double V8ConsoleMessageStorage::timeLog(int contextId, const String16& id) {
626   std::map<String16, double>& time = m_data[contextId].m_time;
627   auto it = time.find(id);
628   if (it == time.end()) return 0.0;
629   return m_inspector->client()->currentTimeMS() - it->second;
630 }
631 
timeEnd(int contextId, const String16& id)632 double V8ConsoleMessageStorage::timeEnd(int contextId, const String16& id) {
633   std::map<String16, double>& time = m_data[contextId].m_time;
634   auto it = time.find(id);
635   if (it == time.end()) return 0.0;
636   double elapsed = m_inspector->client()->currentTimeMS() - it->second;
637   time.erase(it);
638   return elapsed;
639 }
640 
hasTimer(int contextId, const String16& id)641 bool V8ConsoleMessageStorage::hasTimer(int contextId, const String16& id) {
642   const std::map<String16, double>& time = m_data[contextId].m_time;
643   return time.find(id) != time.end();
644 }
645 
contextDestroyed(int contextId)646 void V8ConsoleMessageStorage::contextDestroyed(int contextId) {
647   m_estimatedSize = 0;
648   for (size_t i = 0; i < m_messages.size(); ++i) {
649     m_messages[i]->contextDestroyed(contextId);
650     m_estimatedSize += m_messages[i]->estimatedSize();
651   }
652   auto it = m_data.find(contextId);
653   if (it != m_data.end()) m_data.erase(contextId);
654 }
655 
656 }  // namespace v8_inspector
657