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   result->setLine(static_cast<int>(m_lineNumber));
248   result->setColumn(static_cast<int>(m_columnNumber));
249   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::Local<v8::Context> context;
400   if (!inspector->exceptionMetaDataContext().ToLocal(&context)) return nullptr;
401   v8::MaybeLocal<v8::Value> maybe_exception = m_arguments[0]->Get(isolate);
402   v8::Local<v8::Value> exception;
403   if (!maybe_exception.ToLocal(&exception)) return nullptr;
404 
405   v8::MaybeLocal<v8::Object> maybe_data =
406       inspector->getAssociatedExceptionData(exception);
407   v8::Local<v8::Object> data;
408   if (!maybe_data.ToLocal(&data)) return nullptr;
409   v8::TryCatch tryCatch(isolate);
410   v8::MicrotasksScope microtasksScope(isolate,
411                                       v8::MicrotasksScope::kDoNotRunMicrotasks);
412   v8::Context::Scope contextScope(context);
413   std::unique_ptr<protocol::DictionaryValue> jsonObject;
414   objectToProtocolValue(context, data, 2, &jsonObject);
415   return jsonObject;
416 }
417 
418 std::unique_ptr<protocol::Runtime::RemoteObject>
wrapException(V8InspectorSessionImpl * session,bool generatePreview) const419 V8ConsoleMessage::wrapException(V8InspectorSessionImpl* session,
420                                 bool generatePreview) const {
421   if (!m_arguments.size() || !m_contextId) return nullptr;
422   DCHECK_EQ(1u, m_arguments.size());
423   InspectedContext* inspectedContext =
424       session->inspector()->getContext(session->contextGroupId(), m_contextId);
425   if (!inspectedContext) return nullptr;
426 
427   v8::Isolate* isolate = inspectedContext->isolate();
428   v8::HandleScope handles(isolate);
429   // TODO(dgozman): should we use different object group?
430   return session->wrapObject(inspectedContext->context(),
431                              m_arguments[0]->Get(isolate), "console",
432                              generatePreview);
433 }
434 
origin() const435 V8MessageOrigin V8ConsoleMessage::origin() const { return m_origin; }
436 
type() const437 ConsoleAPIType V8ConsoleMessage::type() const { return m_type; }
438 
439 // 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)440 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForConsoleAPI(
441     v8::Local<v8::Context> v8Context, int contextId, int groupId,
442     V8InspectorImpl* inspector, double timestamp, ConsoleAPIType type,
443     const std::vector<v8::Local<v8::Value>>& arguments,
444     const String16& consoleContext,
445     std::unique_ptr<V8StackTraceImpl> stackTrace) {
446   v8::Isolate* isolate = v8Context->GetIsolate();
447 
448   std::unique_ptr<V8ConsoleMessage> message(
449       new V8ConsoleMessage(V8MessageOrigin::kConsole, timestamp, String16()));
450   if (stackTrace && !stackTrace->isEmpty()) {
451     message->m_url = toString16(stackTrace->topSourceURL());
452     message->m_lineNumber = stackTrace->topLineNumber();
453     message->m_columnNumber = stackTrace->topColumnNumber();
454   }
455   message->m_stackTrace = std::move(stackTrace);
456   message->m_consoleContext = consoleContext;
457   message->m_type = type;
458   message->m_contextId = contextId;
459   for (size_t i = 0; i < arguments.size(); ++i) {
460     std::unique_ptr<v8::Global<v8::Value>> argument(
461         new v8::Global<v8::Value>(isolate, arguments.at(i)));
462     argument->AnnotateStrongRetainer(kGlobalConsoleMessageHandleLabel);
463     message->m_arguments.push_back(std::move(argument));
464     message->m_v8Size +=
465         v8::debug::EstimatedValueSize(isolate, arguments.at(i));
466   }
467   for (size_t i = 0, num_args = arguments.size(); i < num_args; ++i) {
468     if (i) message->m_message += String16(" ");
469     message->m_message +=
470         V8ValueStringBuilder::toString(arguments[i], v8Context);
471   }
472 
473   v8::Isolate::MessageErrorLevel clientLevel = v8::Isolate::kMessageInfo;
474   if (type == ConsoleAPIType::kDebug || type == ConsoleAPIType::kCount ||
475       type == ConsoleAPIType::kTimeEnd) {
476     clientLevel = v8::Isolate::kMessageDebug;
477   } else if (type == ConsoleAPIType::kError ||
478              type == ConsoleAPIType::kAssert) {
479     clientLevel = v8::Isolate::kMessageError;
480   } else if (type == ConsoleAPIType::kWarning) {
481     clientLevel = v8::Isolate::kMessageWarning;
482   } else if (type == ConsoleAPIType::kInfo || type == ConsoleAPIType::kLog) {
483     clientLevel = v8::Isolate::kMessageInfo;
484   }
485 
486   if (type != ConsoleAPIType::kClear) {
487     inspector->client()->consoleAPIMessage(
488         groupId, clientLevel, toStringView(message->m_message),
489         toStringView(message->m_url), message->m_lineNumber,
490         message->m_columnNumber, message->m_stackTrace.get());
491   }
492 
493   return message;
494 }
495 
496 // 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)497 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForException(
498     double timestamp, const String16& detailedMessage, const String16& url,
499     unsigned lineNumber, unsigned columnNumber,
500     std::unique_ptr<V8StackTraceImpl> stackTrace, int scriptId,
501     v8::Isolate* isolate, const String16& message, int contextId,
502     v8::Local<v8::Value> exception, unsigned exceptionId) {
503   std::unique_ptr<V8ConsoleMessage> consoleMessage(
504       new V8ConsoleMessage(V8MessageOrigin::kException, timestamp, message));
505   consoleMessage->setLocation(url, lineNumber, columnNumber,
506                               std::move(stackTrace), scriptId);
507   consoleMessage->m_exceptionId = exceptionId;
508   consoleMessage->m_detailedMessage = detailedMessage;
509   if (contextId && !exception.IsEmpty()) {
510     consoleMessage->m_contextId = contextId;
511     consoleMessage->m_arguments.push_back(
512         std::unique_ptr<v8::Global<v8::Value>>(
513             new v8::Global<v8::Value>(isolate, exception)));
514     consoleMessage->m_v8Size +=
515         v8::debug::EstimatedValueSize(isolate, exception);
516   }
517   return consoleMessage;
518 }
519 
520 // static
createForRevokedException(double timestamp,const String16 & messageText,unsigned revokedExceptionId)521 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForRevokedException(
522     double timestamp, const String16& messageText,
523     unsigned revokedExceptionId) {
524   std::unique_ptr<V8ConsoleMessage> message(new V8ConsoleMessage(
525       V8MessageOrigin::kRevokedException, timestamp, messageText));
526   message->m_revokedExceptionId = revokedExceptionId;
527   return message;
528 }
529 
contextDestroyed(int contextId)530 void V8ConsoleMessage::contextDestroyed(int contextId) {
531   if (contextId != m_contextId) return;
532   m_contextId = 0;
533   if (m_message.isEmpty()) m_message = "<message collected>";
534   Arguments empty;
535   m_arguments.swap(empty);
536   m_v8Size = 0;
537 }
538 
539 // ------------------------ V8ConsoleMessageStorage
540 // ----------------------------
541 
V8ConsoleMessageStorage(V8InspectorImpl * inspector,int contextGroupId)542 V8ConsoleMessageStorage::V8ConsoleMessageStorage(V8InspectorImpl* inspector,
543                                                  int contextGroupId)
544     : m_inspector(inspector), m_contextGroupId(contextGroupId) {}
545 
~V8ConsoleMessageStorage()546 V8ConsoleMessageStorage::~V8ConsoleMessageStorage() { clear(); }
547 
548 namespace {
549 
TraceV8ConsoleMessageEvent(V8MessageOrigin origin,ConsoleAPIType type)550 void TraceV8ConsoleMessageEvent(V8MessageOrigin origin, ConsoleAPIType type) {
551   // Change in this function requires adjustment of Catapult/Telemetry metric
552   // tracing/tracing/metrics/console_error_metric.html.
553   // See https://crbug.com/880432
554   if (origin == V8MessageOrigin::kException) {
555     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Exception",
556                          TRACE_EVENT_SCOPE_THREAD);
557   } else if (type == ConsoleAPIType::kError) {
558     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Error",
559                          TRACE_EVENT_SCOPE_THREAD);
560   } else if (type == ConsoleAPIType::kAssert) {
561     TRACE_EVENT_INSTANT0("v8.console", "V8ConsoleMessage::Assert",
562                          TRACE_EVENT_SCOPE_THREAD);
563   }
564 }
565 
566 }  // anonymous namespace
567 
addMessage(std::unique_ptr<V8ConsoleMessage> message)568 void V8ConsoleMessageStorage::addMessage(
569     std::unique_ptr<V8ConsoleMessage> message) {
570   int contextGroupId = m_contextGroupId;
571   V8InspectorImpl* inspector = m_inspector;
572   if (message->type() == ConsoleAPIType::kClear) clear();
573 
574   TraceV8ConsoleMessageEvent(message->origin(), message->type());
575 
576   inspector->forEachSession(
577       contextGroupId, [&message](V8InspectorSessionImpl* session) {
578         if (message->origin() == V8MessageOrigin::kConsole)
579           session->consoleAgent()->messageAdded(message.get());
580         session->runtimeAgent()->messageAdded(message.get());
581       });
582   if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
583 
584   DCHECK(m_messages.size() <= maxConsoleMessageCount);
585   if (m_messages.size() == maxConsoleMessageCount) {
586     m_estimatedSize -= m_messages.front()->estimatedSize();
587     m_messages.pop_front();
588   }
589   while (m_estimatedSize + message->estimatedSize() > maxConsoleMessageV8Size &&
590          !m_messages.empty()) {
591     m_estimatedSize -= m_messages.front()->estimatedSize();
592     m_messages.pop_front();
593   }
594 
595   m_messages.push_back(std::move(message));
596   m_estimatedSize += m_messages.back()->estimatedSize();
597 }
598 
clear()599 void V8ConsoleMessageStorage::clear() {
600   m_messages.clear();
601   m_estimatedSize = 0;
602   m_inspector->forEachSession(m_contextGroupId,
603                               [](V8InspectorSessionImpl* session) {
604                                 session->releaseObjectGroup("console");
605                               });
606   m_data.clear();
607 }
608 
shouldReportDeprecationMessage(int contextId,const String16 & method)609 bool V8ConsoleMessageStorage::shouldReportDeprecationMessage(
610     int contextId, const String16& method) {
611   std::set<String16>& reportedDeprecationMessages =
612       m_data[contextId].m_reportedDeprecationMessages;
613   auto it = reportedDeprecationMessages.find(method);
614   if (it != reportedDeprecationMessages.end()) return false;
615   reportedDeprecationMessages.insert(it, method);
616   return true;
617 }
618 
count(int contextId,const String16 & id)619 int V8ConsoleMessageStorage::count(int contextId, const String16& id) {
620   return ++m_data[contextId].m_count[id];
621 }
622 
time(int contextId,const String16 & id)623 void V8ConsoleMessageStorage::time(int contextId, const String16& id) {
624   m_data[contextId].m_time[id] = m_inspector->client()->currentTimeMS();
625 }
626 
countReset(int contextId,const String16 & id)627 bool V8ConsoleMessageStorage::countReset(int contextId, const String16& id) {
628   std::map<String16, int>& count_map = m_data[contextId].m_count;
629   if (count_map.find(id) == count_map.end()) return false;
630 
631   count_map[id] = 0;
632   return true;
633 }
634 
timeLog(int contextId,const String16 & id)635 double V8ConsoleMessageStorage::timeLog(int contextId, const String16& id) {
636   std::map<String16, double>& time = m_data[contextId].m_time;
637   auto it = time.find(id);
638   if (it == time.end()) return 0.0;
639   return m_inspector->client()->currentTimeMS() - it->second;
640 }
641 
timeEnd(int contextId,const String16 & id)642 double V8ConsoleMessageStorage::timeEnd(int contextId, const String16& id) {
643   std::map<String16, double>& time = m_data[contextId].m_time;
644   auto it = time.find(id);
645   if (it == time.end()) return 0.0;
646   double elapsed = m_inspector->client()->currentTimeMS() - it->second;
647   time.erase(it);
648   return elapsed;
649 }
650 
hasTimer(int contextId,const String16 & id)651 bool V8ConsoleMessageStorage::hasTimer(int contextId, const String16& id) {
652   const std::map<String16, double>& time = m_data[contextId].m_time;
653   return time.find(id) != time.end();
654 }
655 
contextDestroyed(int contextId)656 void V8ConsoleMessageStorage::contextDestroyed(int contextId) {
657   m_estimatedSize = 0;
658   for (size_t i = 0; i < m_messages.size(); ++i) {
659     m_messages[i]->contextDestroyed(contextId);
660     m_estimatedSize += m_messages[i]->estimatedSize();
661   }
662   auto it = m_data.find(contextId);
663   if (it != m_data.end()) m_data.erase(contextId);
664 }
665 
666 }  // namespace v8_inspector
667