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/inspector/inspected-context.h"
8 #include "src/inspector/protocol/Protocol.h"
9 #include "src/inspector/string-util.h"
10 #include "src/inspector/v8-console-agent-impl.h"
11 #include "src/inspector/v8-inspector-impl.h"
12 #include "src/inspector/v8-inspector-session-impl.h"
13 #include "src/inspector/v8-runtime-agent-impl.h"
14 #include "src/inspector/v8-stack-trace-impl.h"
15
16 #include "include/v8-inspector.h"
17
18 namespace v8_inspector {
19
20 namespace {
21
consoleAPITypeValue(ConsoleAPIType type)22 String16 consoleAPITypeValue(ConsoleAPIType type) {
23 switch (type) {
24 case ConsoleAPIType::kLog:
25 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
26 case ConsoleAPIType::kDebug:
27 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug;
28 case ConsoleAPIType::kInfo:
29 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Info;
30 case ConsoleAPIType::kError:
31 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Error;
32 case ConsoleAPIType::kWarning:
33 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Warning;
34 case ConsoleAPIType::kClear:
35 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Clear;
36 case ConsoleAPIType::kDir:
37 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dir;
38 case ConsoleAPIType::kDirXML:
39 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dirxml;
40 case ConsoleAPIType::kTable:
41 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Table;
42 case ConsoleAPIType::kTrace:
43 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Trace;
44 case ConsoleAPIType::kStartGroup:
45 return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroup;
46 case ConsoleAPIType::kStartGroupCollapsed:
47 return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroupCollapsed;
48 case ConsoleAPIType::kEndGroup:
49 return protocol::Runtime::ConsoleAPICalled::TypeEnum::EndGroup;
50 case ConsoleAPIType::kAssert:
51 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Assert;
52 case ConsoleAPIType::kTimeEnd:
53 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug;
54 case ConsoleAPIType::kCount:
55 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug;
56 }
57 return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log;
58 }
59
60 const unsigned maxConsoleMessageCount = 1000;
61 const unsigned maxArrayItemsLimit = 10000;
62 const unsigned maxStackDepthLimit = 32;
63
64 class V8ValueStringBuilder {
65 public:
toString(v8::Local<v8::Value> value,v8::Local<v8::Context> context)66 static String16 toString(v8::Local<v8::Value> value,
67 v8::Local<v8::Context> context) {
68 V8ValueStringBuilder builder(context);
69 if (!builder.append(value)) return String16();
70 return builder.toString();
71 }
72
73 private:
74 enum {
75 IgnoreNull = 1 << 0,
76 IgnoreUndefined = 1 << 1,
77 };
78
V8ValueStringBuilder(v8::Local<v8::Context> context)79 explicit V8ValueStringBuilder(v8::Local<v8::Context> context)
80 : m_arrayLimit(maxArrayItemsLimit),
81 m_isolate(context->GetIsolate()),
82 m_tryCatch(context->GetIsolate()),
83 m_context(context) {}
84
append(v8::Local<v8::Value> value,unsigned ignoreOptions=0)85 bool append(v8::Local<v8::Value> value, unsigned ignoreOptions = 0) {
86 if (value.IsEmpty()) return true;
87 if ((ignoreOptions & IgnoreNull) && value->IsNull()) return true;
88 if ((ignoreOptions & IgnoreUndefined) && value->IsUndefined()) return true;
89 if (value->IsString()) return append(v8::Local<v8::String>::Cast(value));
90 if (value->IsStringObject())
91 return append(v8::Local<v8::StringObject>::Cast(value)->ValueOf());
92 if (value->IsSymbol()) return append(v8::Local<v8::Symbol>::Cast(value));
93 if (value->IsSymbolObject())
94 return append(v8::Local<v8::SymbolObject>::Cast(value)->ValueOf());
95 if (value->IsNumberObject()) {
96 m_builder.append(String16::fromDouble(
97 v8::Local<v8::NumberObject>::Cast(value)->ValueOf(), 6));
98 return true;
99 }
100 if (value->IsBooleanObject()) {
101 m_builder.append(v8::Local<v8::BooleanObject>::Cast(value)->ValueOf()
102 ? "true"
103 : "false");
104 return true;
105 }
106 if (value->IsArray()) return append(v8::Local<v8::Array>::Cast(value));
107 if (value->IsProxy()) {
108 m_builder.append("[object Proxy]");
109 return true;
110 }
111 if (value->IsObject() && !value->IsDate() && !value->IsFunction() &&
112 !value->IsNativeError() && !value->IsRegExp()) {
113 v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
114 v8::Local<v8::String> stringValue;
115 if (object->ObjectProtoToString(m_isolate->GetCurrentContext())
116 .ToLocal(&stringValue))
117 return append(stringValue);
118 }
119 v8::Local<v8::String> stringValue;
120 if (!value->ToString(m_isolate->GetCurrentContext()).ToLocal(&stringValue))
121 return false;
122 return append(stringValue);
123 }
124
append(v8::Local<v8::Array> array)125 bool append(v8::Local<v8::Array> array) {
126 for (const auto& it : m_visitedArrays) {
127 if (it == array) return true;
128 }
129 uint32_t length = array->Length();
130 if (length > m_arrayLimit) return false;
131 if (m_visitedArrays.size() > maxStackDepthLimit) return false;
132
133 bool result = true;
134 m_arrayLimit -= length;
135 m_visitedArrays.push_back(array);
136 for (uint32_t i = 0; i < length; ++i) {
137 if (i) m_builder.append(',');
138 v8::Local<v8::Value> value;
139 if (!array->Get(m_context, i).ToLocal(&value)) continue;
140 if (!append(value, IgnoreNull | IgnoreUndefined)) {
141 result = false;
142 break;
143 }
144 }
145 m_visitedArrays.pop_back();
146 return result;
147 }
148
append(v8::Local<v8::Symbol> symbol)149 bool append(v8::Local<v8::Symbol> symbol) {
150 m_builder.append("Symbol(");
151 bool result = append(symbol->Name(), IgnoreUndefined);
152 m_builder.append(')');
153 return result;
154 }
155
append(v8::Local<v8::String> string)156 bool append(v8::Local<v8::String> string) {
157 if (m_tryCatch.HasCaught()) return false;
158 if (!string.IsEmpty()) m_builder.append(toProtocolString(string));
159 return true;
160 }
161
toString()162 String16 toString() {
163 if (m_tryCatch.HasCaught()) return String16();
164 return m_builder.toString();
165 }
166
167 uint32_t m_arrayLimit;
168 v8::Isolate* m_isolate;
169 String16Builder m_builder;
170 std::vector<v8::Local<v8::Array>> m_visitedArrays;
171 v8::TryCatch m_tryCatch;
172 v8::Local<v8::Context> m_context;
173 };
174
175 } // namespace
176
V8ConsoleMessage(V8MessageOrigin origin,double timestamp,const String16 & message)177 V8ConsoleMessage::V8ConsoleMessage(V8MessageOrigin origin, double timestamp,
178 const String16& message)
179 : m_origin(origin),
180 m_timestamp(timestamp),
181 m_message(message),
182 m_lineNumber(0),
183 m_columnNumber(0),
184 m_scriptId(0),
185 m_contextId(0),
186 m_type(ConsoleAPIType::kLog),
187 m_exceptionId(0),
188 m_revokedExceptionId(0) {}
189
~V8ConsoleMessage()190 V8ConsoleMessage::~V8ConsoleMessage() {}
191
setLocation(const String16 & url,unsigned lineNumber,unsigned columnNumber,std::unique_ptr<V8StackTraceImpl> stackTrace,int scriptId)192 void V8ConsoleMessage::setLocation(const String16& url, unsigned lineNumber,
193 unsigned columnNumber,
194 std::unique_ptr<V8StackTraceImpl> stackTrace,
195 int scriptId) {
196 m_url = url;
197 m_lineNumber = lineNumber;
198 m_columnNumber = columnNumber;
199 m_stackTrace = std::move(stackTrace);
200 m_scriptId = scriptId;
201 }
202
reportToFrontend(protocol::Console::Frontend * frontend) const203 void V8ConsoleMessage::reportToFrontend(
204 protocol::Console::Frontend* frontend) const {
205 DCHECK(m_origin == V8MessageOrigin::kConsole);
206 String16 level = protocol::Console::ConsoleMessage::LevelEnum::Log;
207 if (m_type == ConsoleAPIType::kDebug || m_type == ConsoleAPIType::kCount ||
208 m_type == ConsoleAPIType::kTimeEnd)
209 level = protocol::Console::ConsoleMessage::LevelEnum::Debug;
210 else if (m_type == ConsoleAPIType::kError ||
211 m_type == ConsoleAPIType::kAssert)
212 level = protocol::Console::ConsoleMessage::LevelEnum::Error;
213 else if (m_type == ConsoleAPIType::kWarning)
214 level = protocol::Console::ConsoleMessage::LevelEnum::Warning;
215 else if (m_type == ConsoleAPIType::kInfo)
216 level = protocol::Console::ConsoleMessage::LevelEnum::Info;
217 std::unique_ptr<protocol::Console::ConsoleMessage> result =
218 protocol::Console::ConsoleMessage::create()
219 .setSource(protocol::Console::ConsoleMessage::SourceEnum::ConsoleApi)
220 .setLevel(level)
221 .setText(m_message)
222 .build();
223 result->setLine(static_cast<int>(m_lineNumber));
224 result->setColumn(static_cast<int>(m_columnNumber));
225 result->setUrl(m_url);
226 frontend->messageAdded(std::move(result));
227 }
228
229 std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
wrapArguments(V8InspectorSessionImpl * session,bool generatePreview) const230 V8ConsoleMessage::wrapArguments(V8InspectorSessionImpl* session,
231 bool generatePreview) const {
232 V8InspectorImpl* inspector = session->inspector();
233 int contextGroupId = session->contextGroupId();
234 int contextId = m_contextId;
235 if (!m_arguments.size() || !contextId) return nullptr;
236 InspectedContext* inspectedContext =
237 inspector->getContext(contextGroupId, contextId);
238 if (!inspectedContext) return nullptr;
239
240 v8::Isolate* isolate = inspectedContext->isolate();
241 v8::HandleScope handles(isolate);
242 v8::Local<v8::Context> context = inspectedContext->context();
243
244 std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>> args =
245 protocol::Array<protocol::Runtime::RemoteObject>::create();
246 if (m_type == ConsoleAPIType::kTable && generatePreview) {
247 v8::Local<v8::Value> table = m_arguments[0]->Get(isolate);
248 v8::Local<v8::Value> columns = m_arguments.size() > 1
249 ? m_arguments[1]->Get(isolate)
250 : v8::Local<v8::Value>();
251 std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
252 session->wrapTable(context, table, columns);
253 inspectedContext = inspector->getContext(contextGroupId, contextId);
254 if (!inspectedContext) return nullptr;
255 if (wrapped)
256 args->addItem(std::move(wrapped));
257 else
258 args = nullptr;
259 } else {
260 for (size_t i = 0; i < m_arguments.size(); ++i) {
261 std::unique_ptr<protocol::Runtime::RemoteObject> wrapped =
262 session->wrapObject(context, m_arguments[i]->Get(isolate), "console",
263 generatePreview);
264 inspectedContext = inspector->getContext(contextGroupId, contextId);
265 if (!inspectedContext) return nullptr;
266 if (!wrapped) {
267 args = nullptr;
268 break;
269 }
270 args->addItem(std::move(wrapped));
271 }
272 }
273 return args;
274 }
275
reportToFrontend(protocol::Runtime::Frontend * frontend,V8InspectorSessionImpl * session,bool generatePreview) const276 void V8ConsoleMessage::reportToFrontend(protocol::Runtime::Frontend* frontend,
277 V8InspectorSessionImpl* session,
278 bool generatePreview) const {
279 int contextGroupId = session->contextGroupId();
280 V8InspectorImpl* inspector = session->inspector();
281
282 if (m_origin == V8MessageOrigin::kException) {
283 std::unique_ptr<protocol::Runtime::RemoteObject> exception =
284 wrapException(session, generatePreview);
285 if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
286 std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails =
287 protocol::Runtime::ExceptionDetails::create()
288 .setExceptionId(m_exceptionId)
289 .setText(exception ? m_message : m_detailedMessage)
290 .setLineNumber(m_lineNumber ? m_lineNumber - 1 : 0)
291 .setColumnNumber(m_columnNumber ? m_columnNumber - 1 : 0)
292 .build();
293 if (m_scriptId)
294 exceptionDetails->setScriptId(String16::fromInteger(m_scriptId));
295 if (!m_url.isEmpty()) exceptionDetails->setUrl(m_url);
296 if (m_stackTrace)
297 exceptionDetails->setStackTrace(m_stackTrace->buildInspectorObjectImpl());
298 if (m_contextId) exceptionDetails->setExecutionContextId(m_contextId);
299 if (exception) exceptionDetails->setException(std::move(exception));
300 frontend->exceptionThrown(m_timestamp, std::move(exceptionDetails));
301 return;
302 }
303 if (m_origin == V8MessageOrigin::kRevokedException) {
304 frontend->exceptionRevoked(m_message, m_revokedExceptionId);
305 return;
306 }
307 if (m_origin == V8MessageOrigin::kConsole) {
308 std::unique_ptr<protocol::Array<protocol::Runtime::RemoteObject>>
309 arguments = wrapArguments(session, generatePreview);
310 if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
311 if (!arguments) {
312 arguments = protocol::Array<protocol::Runtime::RemoteObject>::create();
313 if (!m_message.isEmpty()) {
314 std::unique_ptr<protocol::Runtime::RemoteObject> messageArg =
315 protocol::Runtime::RemoteObject::create()
316 .setType(protocol::Runtime::RemoteObject::TypeEnum::String)
317 .build();
318 messageArg->setValue(protocol::StringValue::create(m_message));
319 arguments->addItem(std::move(messageArg));
320 }
321 }
322 frontend->consoleAPICalled(
323 consoleAPITypeValue(m_type), std::move(arguments), m_contextId,
324 m_timestamp,
325 m_stackTrace ? m_stackTrace->buildInspectorObjectImpl() : nullptr);
326 return;
327 }
328 UNREACHABLE();
329 }
330
331 std::unique_ptr<protocol::Runtime::RemoteObject>
wrapException(V8InspectorSessionImpl * session,bool generatePreview) const332 V8ConsoleMessage::wrapException(V8InspectorSessionImpl* session,
333 bool generatePreview) const {
334 if (!m_arguments.size() || !m_contextId) return nullptr;
335 DCHECK_EQ(1u, m_arguments.size());
336 InspectedContext* inspectedContext =
337 session->inspector()->getContext(session->contextGroupId(), m_contextId);
338 if (!inspectedContext) return nullptr;
339
340 v8::Isolate* isolate = inspectedContext->isolate();
341 v8::HandleScope handles(isolate);
342 // TODO(dgozman): should we use different object group?
343 return session->wrapObject(inspectedContext->context(),
344 m_arguments[0]->Get(isolate), "console",
345 generatePreview);
346 }
347
origin() const348 V8MessageOrigin V8ConsoleMessage::origin() const { return m_origin; }
349
type() const350 ConsoleAPIType V8ConsoleMessage::type() const { return m_type; }
351
352 // static
createForConsoleAPI(double timestamp,ConsoleAPIType type,const std::vector<v8::Local<v8::Value>> & arguments,std::unique_ptr<V8StackTraceImpl> stackTrace,InspectedContext * inspectedContext)353 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForConsoleAPI(
354 double timestamp, ConsoleAPIType type,
355 const std::vector<v8::Local<v8::Value>>& arguments,
356 std::unique_ptr<V8StackTraceImpl> stackTrace,
357 InspectedContext* inspectedContext) {
358 v8::Isolate* isolate = inspectedContext->isolate();
359 int contextId = inspectedContext->contextId();
360 int contextGroupId = inspectedContext->contextGroupId();
361 V8InspectorImpl* inspector = inspectedContext->inspector();
362 v8::Local<v8::Context> context = inspectedContext->context();
363
364 std::unique_ptr<V8ConsoleMessage> message = wrapUnique(
365 new V8ConsoleMessage(V8MessageOrigin::kConsole, timestamp, String16()));
366 if (stackTrace && !stackTrace->isEmpty()) {
367 message->m_url = toString16(stackTrace->topSourceURL());
368 message->m_lineNumber = stackTrace->topLineNumber();
369 message->m_columnNumber = stackTrace->topColumnNumber();
370 }
371 message->m_stackTrace = std::move(stackTrace);
372 message->m_type = type;
373 message->m_contextId = contextId;
374 for (size_t i = 0; i < arguments.size(); ++i)
375 message->m_arguments.push_back(
376 wrapUnique(new v8::Global<v8::Value>(isolate, arguments.at(i))));
377 if (arguments.size())
378 message->m_message = V8ValueStringBuilder::toString(arguments[0], context);
379
380 V8ConsoleAPIType clientType = V8ConsoleAPIType::kLog;
381 if (type == ConsoleAPIType::kDebug || type == ConsoleAPIType::kCount ||
382 type == ConsoleAPIType::kTimeEnd)
383 clientType = V8ConsoleAPIType::kDebug;
384 else if (type == ConsoleAPIType::kError || type == ConsoleAPIType::kAssert)
385 clientType = V8ConsoleAPIType::kError;
386 else if (type == ConsoleAPIType::kWarning)
387 clientType = V8ConsoleAPIType::kWarning;
388 else if (type == ConsoleAPIType::kInfo)
389 clientType = V8ConsoleAPIType::kInfo;
390 else if (type == ConsoleAPIType::kClear)
391 clientType = V8ConsoleAPIType::kClear;
392 inspector->client()->consoleAPIMessage(
393 contextGroupId, clientType, toStringView(message->m_message),
394 toStringView(message->m_url), message->m_lineNumber,
395 message->m_columnNumber, message->m_stackTrace.get());
396
397 return message;
398 }
399
400 // 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)401 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForException(
402 double timestamp, const String16& detailedMessage, const String16& url,
403 unsigned lineNumber, unsigned columnNumber,
404 std::unique_ptr<V8StackTraceImpl> stackTrace, int scriptId,
405 v8::Isolate* isolate, const String16& message, int contextId,
406 v8::Local<v8::Value> exception, unsigned exceptionId) {
407 std::unique_ptr<V8ConsoleMessage> consoleMessage = wrapUnique(
408 new V8ConsoleMessage(V8MessageOrigin::kException, timestamp, message));
409 consoleMessage->setLocation(url, lineNumber, columnNumber,
410 std::move(stackTrace), scriptId);
411 consoleMessage->m_exceptionId = exceptionId;
412 consoleMessage->m_detailedMessage = detailedMessage;
413 if (contextId && !exception.IsEmpty()) {
414 consoleMessage->m_contextId = contextId;
415 consoleMessage->m_arguments.push_back(
416 wrapUnique(new v8::Global<v8::Value>(isolate, exception)));
417 }
418 return consoleMessage;
419 }
420
421 // static
createForRevokedException(double timestamp,const String16 & messageText,unsigned revokedExceptionId)422 std::unique_ptr<V8ConsoleMessage> V8ConsoleMessage::createForRevokedException(
423 double timestamp, const String16& messageText,
424 unsigned revokedExceptionId) {
425 std::unique_ptr<V8ConsoleMessage> message = wrapUnique(new V8ConsoleMessage(
426 V8MessageOrigin::kRevokedException, timestamp, messageText));
427 message->m_revokedExceptionId = revokedExceptionId;
428 return message;
429 }
430
contextDestroyed(int contextId)431 void V8ConsoleMessage::contextDestroyed(int contextId) {
432 if (contextId != m_contextId) return;
433 m_contextId = 0;
434 if (m_message.isEmpty()) m_message = "<message collected>";
435 Arguments empty;
436 m_arguments.swap(empty);
437 }
438
439 // ------------------------ V8ConsoleMessageStorage ----------------------------
440
V8ConsoleMessageStorage(V8InspectorImpl * inspector,int contextGroupId)441 V8ConsoleMessageStorage::V8ConsoleMessageStorage(V8InspectorImpl* inspector,
442 int contextGroupId)
443 : m_inspector(inspector),
444 m_contextGroupId(contextGroupId),
445 m_expiredCount(0) {}
446
~V8ConsoleMessageStorage()447 V8ConsoleMessageStorage::~V8ConsoleMessageStorage() { clear(); }
448
addMessage(std::unique_ptr<V8ConsoleMessage> message)449 void V8ConsoleMessageStorage::addMessage(
450 std::unique_ptr<V8ConsoleMessage> message) {
451 int contextGroupId = m_contextGroupId;
452 V8InspectorImpl* inspector = m_inspector;
453 if (message->type() == ConsoleAPIType::kClear) clear();
454
455 V8InspectorSessionImpl* session =
456 inspector->sessionForContextGroup(contextGroupId);
457 if (session) {
458 if (message->origin() == V8MessageOrigin::kConsole)
459 session->consoleAgent()->messageAdded(message.get());
460 session->runtimeAgent()->messageAdded(message.get());
461 }
462 if (!inspector->hasConsoleMessageStorage(contextGroupId)) return;
463
464 DCHECK(m_messages.size() <= maxConsoleMessageCount);
465 if (m_messages.size() == maxConsoleMessageCount) {
466 ++m_expiredCount;
467 m_messages.pop_front();
468 }
469 m_messages.push_back(std::move(message));
470 }
471
clear()472 void V8ConsoleMessageStorage::clear() {
473 m_messages.clear();
474 m_expiredCount = 0;
475 if (V8InspectorSessionImpl* session =
476 m_inspector->sessionForContextGroup(m_contextGroupId))
477 session->releaseObjectGroup("console");
478 }
479
contextDestroyed(int contextId)480 void V8ConsoleMessageStorage::contextDestroyed(int contextId) {
481 for (size_t i = 0; i < m_messages.size(); ++i)
482 m_messages[i]->contextDestroyed(contextId);
483 }
484
485 } // namespace v8_inspector
486