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