v8-console.cc 36.9 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/inspector/v8-console.h"
6

7
#include "src/base/macros.h"
8 9 10 11 12 13 14 15 16 17
#include "src/inspector/injected-script.h"
#include "src/inspector/inspected-context.h"
#include "src/inspector/string-util.h"
#include "src/inspector/v8-console-message.h"
#include "src/inspector/v8-debugger-agent-impl.h"
#include "src/inspector/v8-inspector-impl.h"
#include "src/inspector/v8-inspector-session-impl.h"
#include "src/inspector/v8-profiler-agent-impl.h"
#include "src/inspector/v8-runtime-agent-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"
18
#include "src/inspector/v8-value-utils.h"
19 20

#include "include/v8-inspector.h"
21 22 23 24 25

namespace v8_inspector {

namespace {

26
String16 consoleContextToString(
27
    v8::Isolate* isolate, const v8::debug::ConsoleContext& consoleContext) {
28
  if (consoleContext.id() == 0) return String16();
29
  return toProtocolString(isolate, consoleContext.name()) + "#" +
30 31 32
         String16::fromInteger(consoleContext.id());
}

33 34
class ConsoleHelper {
 public:
35
  ConsoleHelper(const v8::debug::ConsoleCallArguments& info,
36
                const v8::debug::ConsoleContext& consoleContext,
37
                V8InspectorImpl* inspector)
38
      : m_info(info),
39
        m_consoleContext(consoleContext),
40 41
        m_isolate(inspector->isolate()),
        m_context(m_isolate->GetCurrentContext()),
42 43 44
        m_inspector(inspector),
        m_contextId(InspectedContext::contextId(m_context)),
        m_groupId(m_inspector->contextGroupId(m_contextId)) {}
45 46 47 48

  int contextId() const { return m_contextId; }
  int groupId() const { return m_groupId; }

49
  InjectedScript* injectedScript(int sessionId) {
50 51
    InspectedContext* context = m_inspector->getContext(m_groupId, m_contextId);
    if (!context) return nullptr;
52 53 54 55 56
    return context->getInjectedScript(sessionId);
  }

  V8InspectorSessionImpl* session(int sessionId) {
    return m_inspector->sessionById(m_groupId, sessionId);
57 58
  }

59
  V8ConsoleMessageStorage* consoleMessageStorage() {
60
    return m_inspector->ensureConsoleMessageStorage(m_groupId);
61 62 63 64 65
  }

  void reportCall(ConsoleAPIType type) {
    if (!m_info.Length()) return;
    std::vector<v8::Local<v8::Value>> arguments;
66
    arguments.reserve(m_info.Length());
67 68 69 70 71 72 73 74 75 76 77 78
    for (int i = 0; i < m_info.Length(); ++i) arguments.push_back(m_info[i]);
    reportCall(type, arguments);
  }

  void reportCallWithDefaultArgument(ConsoleAPIType type,
                                     const String16& message) {
    std::vector<v8::Local<v8::Value>> arguments;
    for (int i = 0; i < m_info.Length(); ++i) arguments.push_back(m_info[i]);
    if (!m_info.Length()) arguments.push_back(toV8String(m_isolate, message));
    reportCall(type, arguments);
  }

79 80 81 82 83 84 85 86
  void reportCallAndReplaceFirstArgument(ConsoleAPIType type,
                                         const String16& message) {
    std::vector<v8::Local<v8::Value>> arguments;
    arguments.push_back(toV8String(m_isolate, message));
    for (int i = 1; i < m_info.Length(); ++i) arguments.push_back(m_info[i]);
    reportCall(type, arguments);
  }

87 88 89 90 91 92 93 94
  void reportCallWithArgument(ConsoleAPIType type, const String16& message) {
    std::vector<v8::Local<v8::Value>> arguments(1,
                                                toV8String(m_isolate, message));
    reportCall(type, arguments);
  }

  void reportCall(ConsoleAPIType type,
                  const std::vector<v8::Local<v8::Value>>& arguments) {
95
    if (!m_groupId) return;
96 97
    std::unique_ptr<V8ConsoleMessage> message =
        V8ConsoleMessage::createForConsoleAPI(
98 99
            m_context, m_contextId, m_groupId, m_inspector,
            m_inspector->client()->currentTimeMS(), type, arguments,
100
            consoleContextToString(m_isolate, m_consoleContext),
101 102
            m_inspector->debugger()->captureStackTrace(false));
    consoleMessageStorage()->addMessage(std::move(message));
103 104 105
  }

  void reportDeprecatedCall(const char* id, const String16& message) {
106 107 108 109
    if (!consoleMessageStorage()->shouldReportDeprecationMessage(m_contextId,
                                                                 id)) {
      return;
    }
110 111 112 113 114 115 116 117
    std::vector<v8::Local<v8::Value>> arguments(1,
                                                toV8String(m_isolate, message));
    reportCall(ConsoleAPIType::kWarning, arguments);
  }

  bool firstArgToBoolean(bool defaultValue) {
    if (m_info.Length() < 1) return defaultValue;
    if (m_info[0]->IsBoolean()) return m_info[0].As<v8::Boolean>()->Value();
118
    return m_info[0]->BooleanValue(m_context->GetIsolate());
119 120
  }

121 122 123 124 125
  String16 firstArgToString(const String16& defaultValue,
                            bool allowUndefined = true) {
    if (m_info.Length() < 1 || (!allowUndefined && m_info[0]->IsUndefined())) {
      return defaultValue;
    }
126
    v8::Local<v8::String> titleValue;
127 128
    if (!m_info[0]->ToString(m_context).ToLocal(&titleValue))
      return defaultValue;
129
    return toProtocolString(m_context->GetIsolate(), titleValue);
130 131 132 133 134 135 136 137 138 139 140
  }

  v8::MaybeLocal<v8::Object> firstArgAsObject() {
    if (m_info.Length() < 1 || !m_info[0]->IsObject())
      return v8::MaybeLocal<v8::Object>();
    return m_info[0].As<v8::Object>();
  }

  v8::MaybeLocal<v8::Function> firstArgAsFunction() {
    if (m_info.Length() < 1 || !m_info[0]->IsFunction())
      return v8::MaybeLocal<v8::Function>();
141 142 143 144
    v8::Local<v8::Function> func = m_info[0].As<v8::Function>();
    while (func->GetBoundFunction()->IsFunction())
      func = func->GetBoundFunction().As<v8::Function>();
    return func;
145 146
  }

147
  void forEachSession(std::function<void(V8InspectorSessionImpl*)> callback) {
148
    m_inspector->forEachSession(m_groupId, std::move(callback));
149 150 151
  }

 private:
152
  const v8::debug::ConsoleCallArguments& m_info;
153
  const v8::debug::ConsoleContext& m_consoleContext;
154 155
  v8::Isolate* m_isolate;
  v8::Local<v8::Context> m_context;
156 157 158
  V8InspectorImpl* m_inspector = nullptr;
  int m_contextId;
  int m_groupId;
159 160

  DISALLOW_COPY_AND_ASSIGN(ConsoleHelper);
161 162 163 164 165 166
};

void returnDataCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
  info.GetReturnValue().Set(info.Data());
}

167 168 169 170 171
void createBoundFunctionProperty(
    v8::Local<v8::Context> context, v8::Local<v8::Object> console,
    v8::Local<v8::Value> data, const char* name, v8::FunctionCallback callback,
    const char* description = nullptr,
    v8::SideEffectType side_effect_type = v8::SideEffectType::kHasSideEffect) {
172 173 174
  v8::Local<v8::String> funcName =
      toV8StringInternalized(context->GetIsolate(), name);
  v8::Local<v8::Function> func;
175
  if (!v8::Function::New(context, callback, data, 0,
176
                         v8::ConstructorBehavior::kThrow, side_effect_type)
177 178 179 180 181 182 183
           .ToLocal(&func))
    return;
  func->SetName(funcName);
  if (description) {
    v8::Local<v8::String> returnValue =
        toV8String(context->GetIsolate(), description);
    v8::Local<v8::Function> toStringFunction;
184
    if (v8::Function::New(context, returnDataCallback, returnValue, 0,
185 186
                          v8::ConstructorBehavior::kThrow,
                          v8::SideEffectType::kHasNoSideEffect)
187 188 189 190 191 192 193
            .ToLocal(&toStringFunction))
      createDataProperty(context, func, toV8StringInternalized(
                                            context->GetIsolate(), "toString"),
                         toStringFunction);
  }
  createDataProperty(context, console, funcName, func);
}
194 195 196

enum InspectRequest { kRegular, kCopyToClipboard, kQueryObjects };

197 198
}  // namespace

199 200
V8Console::V8Console(V8InspectorImpl* inspector) : m_inspector(inspector) {}

201 202 203 204
void V8Console::Debug(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kDebug);
205 206
}

207 208 209 210
void V8Console::Error(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kError);
211 212
}

213 214 215 216
void V8Console::Info(const v8::debug::ConsoleCallArguments& info,
                     const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kInfo);
217 218
}

219 220 221 222
void V8Console::Log(const v8::debug::ConsoleCallArguments& info,
                    const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kLog);
223 224
}

225 226 227 228
void V8Console::Warn(const v8::debug::ConsoleCallArguments& info,
                     const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kWarning);
229 230
}

231 232 233 234
void V8Console::Dir(const v8::debug::ConsoleCallArguments& info,
                    const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kDir);
235 236
}

237 238 239 240
void V8Console::DirXml(const v8::debug::ConsoleCallArguments& info,
                       const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kDirXML);
241 242
}

243 244 245 246
void V8Console::Table(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
      .reportCall(ConsoleAPIType::kTable);
247 248
}

249 250 251
void V8Console::Trace(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
252 253
      .reportCallWithDefaultArgument(ConsoleAPIType::kTrace,
                                     String16("console.trace"));
254 255
}

256 257 258
void V8Console::Group(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
259 260
      .reportCallWithDefaultArgument(ConsoleAPIType::kStartGroup,
                                     String16("console.group"));
261 262
}

263 264 265 266
void V8Console::GroupCollapsed(
    const v8::debug::ConsoleCallArguments& info,
    const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
267 268
      .reportCallWithDefaultArgument(ConsoleAPIType::kStartGroupCollapsed,
                                     String16("console.groupCollapsed"));
269 270
}

271 272 273
void V8Console::GroupEnd(const v8::debug::ConsoleCallArguments& info,
                         const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper(info, consoleContext, m_inspector)
274 275
      .reportCallWithDefaultArgument(ConsoleAPIType::kEndGroup,
                                     String16("console.groupEnd"));
276 277
}

278 279 280
void V8Console::Clear(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
281
  if (!helper.groupId()) return;
282
  m_inspector->client()->consoleClear(helper.groupId());
283 284
  helper.reportCallWithDefaultArgument(ConsoleAPIType::kClear,
                                       String16("console.clear"));
285 286
}

287 288 289 290
static String16 identifierFromTitleOrStackTrace(
    const String16& title, const ConsoleHelper& helper,
    const v8::debug::ConsoleContext& consoleContext,
    V8InspectorImpl* inspector) {
291 292 293
  String16 identifier;
  if (title.isEmpty()) {
    std::unique_ptr<V8StackTraceImpl> stackTrace =
294
        V8StackTraceImpl::capture(inspector->debugger(), helper.groupId(), 1);
295
    if (stackTrace && !stackTrace->isEmpty()) {
296 297
      identifier = toString16(stackTrace->topSourceURL()) + ":" +
                   String16::fromInteger(stackTrace->topLineNumber());
298
    }
299 300 301
  } else {
    identifier = title + "@";
  }
302 303
  identifier = consoleContextToString(inspector->isolate(), consoleContext) +
               "@" + identifier;
304

305 306 307 308 309 310 311 312 313 314
  return identifier;
}

void V8Console::Count(const v8::debug::ConsoleCallArguments& info,
                      const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
  String16 title = helper.firstArgToString(String16("default"), false);
  String16 identifier = identifierFromTitleOrStackTrace(
      title, helper, consoleContext, m_inspector);

315 316
  int count =
      helper.consoleMessageStorage()->count(helper.contextId(), identifier);
317 318 319 320
  String16 countString = String16::fromInteger(count);
  helper.reportCallWithArgument(
      ConsoleAPIType::kCount,
      title.isEmpty() ? countString : (title + ": " + countString));
321 322
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336
void V8Console::CountReset(const v8::debug::ConsoleCallArguments& info,
                           const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
  String16 title = helper.firstArgToString(String16("default"), false);
  String16 identifier = identifierFromTitleOrStackTrace(
      title, helper, consoleContext, m_inspector);

  if (!helper.consoleMessageStorage()->countReset(helper.contextId(),
                                                  identifier)) {
    helper.reportCallWithArgument(ConsoleAPIType::kWarning,
                                  "Count for '" + title + "' does not exist");
  }
}

337 338 339
void V8Console::Assert(const v8::debug::ConsoleCallArguments& info,
                       const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
340
  DCHECK(!helper.firstArgToBoolean(false));
341 342 343 344 345

  std::vector<v8::Local<v8::Value>> arguments;
  for (int i = 1; i < info.Length(); ++i) arguments.push_back(info[i]);
  if (info.Length() < 2)
    arguments.push_back(
346
        toV8String(m_inspector->isolate(), String16("console.assert")));
347
  helper.reportCall(ConsoleAPIType::kAssert, arguments);
348
  m_inspector->debugger()->breakProgramOnAssert(helper.groupId());
349 350
}

351 352 353
void V8Console::Profile(const v8::debug::ConsoleCallArguments& info,
                        const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
354 355 356 357
  helper.forEachSession([&helper](V8InspectorSessionImpl* session) {
    session->profilerAgent()->consoleProfile(
        helper.firstArgToString(String16()));
  });
358 359
}

360 361 362
void V8Console::ProfileEnd(const v8::debug::ConsoleCallArguments& info,
                           const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
363 364 365 366
  helper.forEachSession([&helper](V8InspectorSessionImpl* session) {
    session->profilerAgent()->consoleProfileEnd(
        helper.firstArgToString(String16()));
  });
367 368
}

369
static void timeFunction(const v8::debug::ConsoleCallArguments& info,
370
                         const v8::debug::ConsoleContext& consoleContext,
371
                         bool timelinePrefix, V8InspectorImpl* inspector) {
372
  ConsoleHelper helper(info, consoleContext, inspector);
373
  String16 protocolTitle = helper.firstArgToString("default", false);
374
  if (timelinePrefix) protocolTitle = "Timeline '" + protocolTitle + "'";
375
  const String16& timerId =
376 377
      protocolTitle + "@" +
      consoleContextToString(inspector->isolate(), consoleContext);
378 379 380 381 382 383
  if (helper.consoleMessageStorage()->hasTimer(helper.contextId(), timerId)) {
    helper.reportCallWithArgument(
        ConsoleAPIType::kWarning,
        "Timer '" + protocolTitle + "' already exists");
    return;
  }
384
  inspector->client()->consoleTime(toStringView(protocolTitle));
385
  helper.consoleMessageStorage()->time(helper.contextId(), timerId);
386 387
}

388
static void timeEndFunction(const v8::debug::ConsoleCallArguments& info,
389
                            const v8::debug::ConsoleContext& consoleContext,
390
                            bool timeLog, V8InspectorImpl* inspector) {
391
  ConsoleHelper helper(info, consoleContext, inspector);
392
  String16 protocolTitle = helper.firstArgToString("default", false);
393
  const String16& timerId =
394 395
      protocolTitle + "@" +
      consoleContextToString(inspector->isolate(), consoleContext);
396 397 398 399 400 401
  if (!helper.consoleMessageStorage()->hasTimer(helper.contextId(), timerId)) {
    helper.reportCallWithArgument(
        ConsoleAPIType::kWarning,
        "Timer '" + protocolTitle + "' does not exist");
    return;
  }
402
  inspector->client()->consoleTimeEnd(toStringView(protocolTitle));
403 404 405 406 407 408 409 410 411 412
  String16 title = protocolTitle + "@" +
                   consoleContextToString(inspector->isolate(), consoleContext);
  double elapsed;
  if (timeLog) {
    elapsed =
        helper.consoleMessageStorage()->timeLog(helper.contextId(), title);
  } else {
    elapsed =
        helper.consoleMessageStorage()->timeEnd(helper.contextId(), title);
  }
413
  String16 message =
414
      protocolTitle + ": " + String16::fromDouble(elapsed) + " ms";
415 416 417 418
  if (timeLog)
    helper.reportCallAndReplaceFirstArgument(ConsoleAPIType::kLog, message);
  else
    helper.reportCallWithArgument(ConsoleAPIType::kTimeEnd, message);
419 420
}

421 422 423
void V8Console::Time(const v8::debug::ConsoleCallArguments& info,
                     const v8::debug::ConsoleContext& consoleContext) {
  timeFunction(info, consoleContext, false, m_inspector);
424 425
}

426 427 428 429 430
void V8Console::TimeLog(const v8::debug::ConsoleCallArguments& info,
                        const v8::debug::ConsoleContext& consoleContext) {
  timeEndFunction(info, consoleContext, true, m_inspector);
}

431 432 433
void V8Console::TimeEnd(const v8::debug::ConsoleCallArguments& info,
                        const v8::debug::ConsoleContext& consoleContext) {
  timeEndFunction(info, consoleContext, false, m_inspector);
434 435
}

436 437 438
void V8Console::TimeStamp(const v8::debug::ConsoleCallArguments& info,
                          const v8::debug::ConsoleContext& consoleContext) {
  ConsoleHelper helper(info, consoleContext, m_inspector);
439
  String16 title = helper.firstArgToString(String16());
440
  m_inspector->client()->consoleTimeStamp(toStringView(title));
441 442 443 444
}

void V8Console::memoryGetterCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
445
  v8::Local<v8::Value> memoryValue;
446
  if (!m_inspector->client()
447 448 449 450 451
           ->memoryInfo(info.GetIsolate(),
                        info.GetIsolate()->GetCurrentContext())
           .ToLocal(&memoryValue))
    return;
  info.GetReturnValue().Set(memoryValue);
452 453 454 455 456 457 458 459 460
}

void V8Console::memorySetterCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  // We can't make the attribute readonly as it breaks existing code that relies
  // on being able to assign to console.memory in strict mode. Instead, the
  // setter just ignores the passed value.  http://crbug.com/468611
}

461 462
void V8Console::keysCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
                             int sessionId) {
463 464 465
  v8::Isolate* isolate = info.GetIsolate();
  info.GetReturnValue().Set(v8::Array::New(isolate));

466
  v8::debug::ConsoleCallArguments args(info);
467
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
468 469 470 471 472 473 474 475
  v8::Local<v8::Object> obj;
  if (!helper.firstArgAsObject().ToLocal(&obj)) return;
  v8::Local<v8::Array> names;
  if (!obj->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocal(&names))
    return;
  info.GetReturnValue().Set(names);
}

476 477
void V8Console::valuesCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
                               int sessionId) {
478 479 480
  v8::Isolate* isolate = info.GetIsolate();
  info.GetReturnValue().Set(v8::Array::New(isolate));

481
  v8::debug::ConsoleCallArguments args(info);
482
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
483 484 485 486 487 488
  v8::Local<v8::Object> obj;
  if (!helper.firstArgAsObject().ToLocal(&obj)) return;
  v8::Local<v8::Array> names;
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  if (!obj->GetOwnPropertyNames(context).ToLocal(&names)) return;
  v8::Local<v8::Array> values = v8::Array::New(isolate, names->Length());
489
  for (uint32_t i = 0; i < names->Length(); ++i) {
490 491 492 493 494 495 496 497 498
    v8::Local<v8::Value> key;
    if (!names->Get(context, i).ToLocal(&key)) continue;
    v8::Local<v8::Value> value;
    if (!obj->Get(context, key).ToLocal(&value)) continue;
    createDataProperty(context, values, i, value);
  }
  info.GetReturnValue().Set(values);
}

499 500 501 502 503
static void setFunctionBreakpoint(
    ConsoleHelper& helper,  // NOLINT(runtime/references)
    int sessionId, v8::Local<v8::Function> function,
    V8DebuggerAgentImpl::BreakpointSource source,
    v8::Local<v8::String> condition, bool enable) {
504 505 506 507 508 509 510
  V8InspectorSessionImpl* session = helper.session(sessionId);
  if (session == nullptr) return;
  if (!session->debuggerAgent()->enabled()) return;
  if (enable) {
    session->debuggerAgent()->setBreakpointFor(function, condition, source);
  } else {
    session->debuggerAgent()->removeBreakpointFor(function, source);
511
  }
512 513 514
}

void V8Console::debugFunctionCallback(
515
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
516
  v8::debug::ConsoleCallArguments args(info);
517
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
518
  v8::Local<v8::Function> function;
519
  v8::Local<v8::String> condition;
520
  if (!helper.firstArgAsFunction().ToLocal(&function)) return;
521 522 523
  if (args.Length() > 1 && args[1]->IsString()) {
    condition = args[1].As<v8::String>();
  }
524
  setFunctionBreakpoint(helper, sessionId, function,
525
                        V8DebuggerAgentImpl::DebugCommandBreakpointSource,
526
                        condition, true);
527 528 529
}

void V8Console::undebugFunctionCallback(
530
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
531
  v8::debug::ConsoleCallArguments args(info);
532
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
533 534
  v8::Local<v8::Function> function;
  if (!helper.firstArgAsFunction().ToLocal(&function)) return;
535
  setFunctionBreakpoint(helper, sessionId, function,
536
                        V8DebuggerAgentImpl::DebugCommandBreakpointSource,
537
                        v8::Local<v8::String>(), false);
538 539 540
}

void V8Console::monitorFunctionCallback(
541
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
542
  v8::debug::ConsoleCallArguments args(info);
543
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
544 545 546 547 548
  v8::Local<v8::Function> function;
  if (!helper.firstArgAsFunction().ToLocal(&function)) return;
  v8::Local<v8::Value> name = function->GetName();
  if (!name->IsString() || !v8::Local<v8::String>::Cast(name)->Length())
    name = function->GetInferredName();
549 550
  String16 functionName =
      toProtocolStringWithTypeCheck(info.GetIsolate(), name);
551 552 553 554 555 556 557 558 559
  String16Builder builder;
  builder.append("console.log(\"function ");
  if (functionName.isEmpty())
    builder.append("(anonymous function)");
  else
    builder.append(functionName);
  builder.append(
      " called\" + (arguments.length > 0 ? \" with arguments: \" + "
      "Array.prototype.join.call(arguments, \", \") : \"\")) && false");
560
  setFunctionBreakpoint(helper, sessionId, function,
561
                        V8DebuggerAgentImpl::MonitorCommandBreakpointSource,
562 563
                        toV8String(info.GetIsolate(), builder.toString()),
                        true);
564 565 566
}

void V8Console::unmonitorFunctionCallback(
567
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
568
  v8::debug::ConsoleCallArguments args(info);
569
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
570 571
  v8::Local<v8::Function> function;
  if (!helper.firstArgAsFunction().ToLocal(&function)) return;
572
  setFunctionBreakpoint(helper, sessionId, function,
573
                        V8DebuggerAgentImpl::MonitorCommandBreakpointSource,
574
                        v8::Local<v8::String>(), false);
575 576 577
}

void V8Console::lastEvaluationResultCallback(
578
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
579
  v8::debug::ConsoleCallArguments args(info);
580
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
581
  InjectedScript* injectedScript = helper.injectedScript(sessionId);
582 583
  if (!injectedScript) return;
  info.GetReturnValue().Set(injectedScript->lastEvaluationResult());
584 585 586
}

static void inspectImpl(const v8::FunctionCallbackInfo<v8::Value>& info,
587
                        v8::Local<v8::Value> value, int sessionId,
588 589
                        InspectRequest request, V8InspectorImpl* inspector) {
  if (request == kRegular) info.GetReturnValue().Set(value);
590

591
  v8::debug::ConsoleCallArguments args(info);
592
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), inspector);
593
  InjectedScript* injectedScript = helper.injectedScript(sessionId);
594
  if (!injectedScript) return;
595
  std::unique_ptr<protocol::Runtime::RemoteObject> wrappedObject;
596 597
  protocol::Response response = injectedScript->wrapObject(
      value, "", WrapMode::kNoPreview, &wrappedObject);
598
  if (!response.IsSuccess()) return;
599 600 601

  std::unique_ptr<protocol::DictionaryValue> hints =
      protocol::DictionaryValue::create();
602 603 604 605
  if (request == kCopyToClipboard) {
    hints->setBoolean("copyToClipboard", true);
  } else if (request == kQueryObjects) {
    hints->setBoolean("queryObjects", true);
606
  }
607 608 609 610
  if (V8InspectorSessionImpl* session = helper.session(sessionId)) {
    session->runtimeAgent()->inspect(std::move(wrappedObject),
                                     std::move(hints));
  }
611 612
}

613 614
void V8Console::inspectCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
                                int sessionId) {
615
  if (info.Length() < 1) return;
616
  inspectImpl(info, info[0], sessionId, kRegular, m_inspector);
617 618
}

619 620
void V8Console::copyCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
                             int sessionId) {
621
  if (info.Length() < 1) return;
622
  inspectImpl(info, info[0], sessionId, kCopyToClipboard, m_inspector);
623 624 625 626
}

void V8Console::queryObjectsCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info, int sessionId) {
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
  if (info.Length() < 1) return;
  v8::Local<v8::Value> arg = info[0];
  if (arg->IsFunction()) {
    v8::Isolate* isolate = info.GetIsolate();
    v8::TryCatch tryCatch(isolate);
    v8::Local<v8::Value> prototype;
    if (arg.As<v8::Function>()
            ->Get(isolate->GetCurrentContext(),
                  toV8StringInternalized(isolate, "prototype"))
            .ToLocal(&prototype) &&
        prototype->IsObject()) {
      arg = prototype;
    }
    if (tryCatch.HasCaught()) {
      tryCatch.ReThrow();
      return;
    }
  }
645
  inspectImpl(info, arg, sessionId, kQueryObjects, m_inspector);
646 647 648
}

void V8Console::inspectedObject(const v8::FunctionCallbackInfo<v8::Value>& info,
649
                                int sessionId, unsigned num) {
650
  DCHECK_GT(V8InspectorSessionImpl::kInspectedObjectBufferSize, num);
651
  v8::debug::ConsoleCallArguments args(info);
652
  ConsoleHelper helper(args, v8::debug::ConsoleContext(), m_inspector);
653
  if (V8InspectorSessionImpl* session = helper.session(sessionId)) {
654 655 656 657 658 659
    V8InspectorSession::Inspectable* object = session->inspectedObject(num);
    v8::Isolate* isolate = info.GetIsolate();
    if (object)
      info.GetReturnValue().Set(object->get(isolate->GetCurrentContext()));
    else
      info.GetReturnValue().Set(v8::Undefined(isolate));
660
  }
661 662
}

663
void V8Console::installMemoryGetter(v8::Local<v8::Context> context,
664
                                    v8::Local<v8::Object> console) {
665 666
  v8::Isolate* isolate = context->GetIsolate();
  v8::Local<v8::External> data = v8::External::New(isolate, this);
667
  console->SetAccessorProperty(
668
      toV8StringInternalized(isolate, "memory"),
669 670 671
      v8::Function::New(
          context, &V8Console::call<&V8Console::memoryGetterCallback>, data, 0,
          v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect)
672
          .ToLocalChecked(),
673 674 675
      v8::Function::New(context,
                        &V8Console::call<&V8Console::memorySetterCallback>,
                        data, 0, v8::ConstructorBehavior::kThrow)
676 677 678 679
          .ToLocalChecked(),
      static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT);
}

680
v8::Local<v8::Object> V8Console::createCommandLineAPI(
681
    v8::Local<v8::Context> context, int sessionId) {
682 683 684 685 686 687 688 689
  v8::Isolate* isolate = context->GetIsolate();
  v8::MicrotasksScope microtasksScope(isolate,
                                      v8::MicrotasksScope::kDoNotRunMicrotasks);

  v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate);
  bool success =
      commandLineAPI->SetPrototype(context, v8::Null(isolate)).FromMaybe(false);
  DCHECK(success);
690
  USE(success);
691

692 693
  v8::Local<v8::ArrayBuffer> data =
      v8::ArrayBuffer::New(isolate, sizeof(CommandLineAPIData));
694
  *static_cast<CommandLineAPIData*>(data->GetBackingStore()->Data()) =
695
      CommandLineAPIData(this, sessionId);
696
  createBoundFunctionProperty(context, commandLineAPI, data, "dir",
697
                              &V8Console::call<&V8Console::Dir>,
698
                              "function dir(value) { [Command Line API] }");
699
  createBoundFunctionProperty(context, commandLineAPI, data, "dirxml",
700
                              &V8Console::call<&V8Console::DirXml>,
701
                              "function dirxml(value) { [Command Line API] }");
702
  createBoundFunctionProperty(context, commandLineAPI, data, "profile",
703
                              &V8Console::call<&V8Console::Profile>,
704 705
                              "function profile(title) { [Command Line API] }");
  createBoundFunctionProperty(
706
      context, commandLineAPI, data, "profileEnd",
707
      &V8Console::call<&V8Console::ProfileEnd>,
708
      "function profileEnd(title) { [Command Line API] }");
709
  createBoundFunctionProperty(context, commandLineAPI, data, "clear",
710
                              &V8Console::call<&V8Console::Clear>,
711 712
                              "function clear() { [Command Line API] }");
  createBoundFunctionProperty(
713
      context, commandLineAPI, data, "table",
714
      &V8Console::call<&V8Console::Table>,
715 716
      "function table(data, [columns]) { [Command Line API] }");

717
  createBoundFunctionProperty(context, commandLineAPI, data, "keys",
718
                              &V8Console::call<&V8Console::keysCallback>,
719 720
                              "function keys(object) { [Command Line API] }",
                              v8::SideEffectType::kHasNoSideEffect);
721
  createBoundFunctionProperty(context, commandLineAPI, data, "values",
722
                              &V8Console::call<&V8Console::valuesCallback>,
723 724
                              "function values(object) { [Command Line API] }",
                              v8::SideEffectType::kHasNoSideEffect);
725
  createBoundFunctionProperty(
726 727
      context, commandLineAPI, data, "debug",
      &V8Console::call<&V8Console::debugFunctionCallback>,
728
      "function debug(function, condition) { [Command Line API] }");
729
  createBoundFunctionProperty(
730
      context, commandLineAPI, data, "undebug",
731
      &V8Console::call<&V8Console::undebugFunctionCallback>,
732 733
      "function undebug(function) { [Command Line API] }");
  createBoundFunctionProperty(
734
      context, commandLineAPI, data, "monitor",
735
      &V8Console::call<&V8Console::monitorFunctionCallback>,
736 737
      "function monitor(function) { [Command Line API] }");
  createBoundFunctionProperty(
738
      context, commandLineAPI, data, "unmonitor",
739
      &V8Console::call<&V8Console::unmonitorFunctionCallback>,
740 741
      "function unmonitor(function) { [Command Line API] }");
  createBoundFunctionProperty(
742 743
      context, commandLineAPI, data, "inspect",
      &V8Console::call<&V8Console::inspectCallback>,
744
      "function inspect(object) { [Command Line API] }");
745
  createBoundFunctionProperty(context, commandLineAPI, data, "copy",
746
                              &V8Console::call<&V8Console::copyCallback>,
747
                              "function copy(value) { [Command Line API] }");
748 749 750 751
  createBoundFunctionProperty(
      context, commandLineAPI, data, "queryObjects",
      &V8Console::call<&V8Console::queryObjectsCallback>,
      "function queryObjects(constructor) { [Command Line API] }");
752 753
  createBoundFunctionProperty(
      context, commandLineAPI, data, "$_",
754 755
      &V8Console::call<&V8Console::lastEvaluationResultCallback>, nullptr,
      v8::SideEffectType::kHasNoSideEffect);
756
  createBoundFunctionProperty(context, commandLineAPI, data, "$0",
757 758
                              &V8Console::call<&V8Console::inspectedObject0>,
                              nullptr, v8::SideEffectType::kHasNoSideEffect);
759
  createBoundFunctionProperty(context, commandLineAPI, data, "$1",
760 761
                              &V8Console::call<&V8Console::inspectedObject1>,
                              nullptr, v8::SideEffectType::kHasNoSideEffect);
762
  createBoundFunctionProperty(context, commandLineAPI, data, "$2",
763 764
                              &V8Console::call<&V8Console::inspectedObject2>,
                              nullptr, v8::SideEffectType::kHasNoSideEffect);
765
  createBoundFunctionProperty(context, commandLineAPI, data, "$3",
766 767
                              &V8Console::call<&V8Console::inspectedObject3>,
                              nullptr, v8::SideEffectType::kHasNoSideEffect);
768
  createBoundFunctionProperty(context, commandLineAPI, data, "$4",
769 770
                              &V8Console::call<&V8Console::inspectedObject4>,
                              nullptr, v8::SideEffectType::kHasNoSideEffect);
771

772 773
  m_inspector->client()->installAdditionalCommandLineAPI(context,
                                                         commandLineAPI);
774 775 776 777 778 779 780 781 782 783 784 785
  return commandLineAPI;
}

static bool isCommandLineAPIGetter(const String16& name) {
  if (name.length() != 2) return false;
  // $0 ... $4, $_
  return name[0] == '$' &&
         ((name[1] >= '0' && name[1] <= '4') || name[1] == '_');
}

void V8Console::CommandLineAPIScope::accessorGetterCallback(
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
786 787
  CommandLineAPIScope* scope = *static_cast<CommandLineAPIScope**>(
      info.Data().As<v8::ArrayBuffer>()->GetBackingStore()->Data());
788
  v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
789 790
  if (scope == nullptr) {
    USE(info.Holder()->Delete(context, name).FromMaybe(false));
791 792 793 794 795 796
    return;
  }
  v8::Local<v8::Object> commandLineAPI = scope->m_commandLineAPI;

  v8::Local<v8::Value> value;
  if (!commandLineAPI->Get(context, name).ToLocal(&value)) return;
797 798
  if (isCommandLineAPIGetter(
          toProtocolStringWithTypeCheck(info.GetIsolate(), name))) {
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    DCHECK(value->IsFunction());
    v8::MicrotasksScope microtasks(info.GetIsolate(),
                                   v8::MicrotasksScope::kDoNotRunMicrotasks);
    if (value.As<v8::Function>()
            ->Call(context, commandLineAPI, 0, nullptr)
            .ToLocal(&value))
      info.GetReturnValue().Set(value);
  } else {
    info.GetReturnValue().Set(value);
  }
}

void V8Console::CommandLineAPIScope::accessorSetterCallback(
    v8::Local<v8::Name> name, v8::Local<v8::Value> value,
    const v8::PropertyCallbackInfo<void>& info) {
814 815 816
  CommandLineAPIScope* scope = *static_cast<CommandLineAPIScope**>(
      info.Data().As<v8::ArrayBuffer>()->GetBackingStore()->Data());
  if (scope == nullptr) return;
817 818 819 820
  v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
  if (!info.Holder()->Delete(context, name).FromMaybe(false)) return;
  if (!info.Holder()->CreateDataProperty(context, name, value).FromMaybe(false))
    return;
821
  USE(scope->m_installedMethods->Delete(context, name).FromMaybe(false));
822 823 824 825 826 827 828 829
}

V8Console::CommandLineAPIScope::CommandLineAPIScope(
    v8::Local<v8::Context> context, v8::Local<v8::Object> commandLineAPI,
    v8::Local<v8::Object> global)
    : m_context(context),
      m_commandLineAPI(commandLineAPI),
      m_global(global),
830
      m_installedMethods(v8::Set::New(context->GetIsolate())) {
831 832
  v8::MicrotasksScope microtasksScope(context->GetIsolate(),
                                      v8::MicrotasksScope::kDoNotRunMicrotasks);
833 834
  v8::Local<v8::Array> names;
  if (!m_commandLineAPI->GetOwnPropertyNames(context).ToLocal(&names)) return;
835 836 837 838
  m_thisReference =
      v8::ArrayBuffer::New(context->GetIsolate(), sizeof(CommandLineAPIScope*));
  *static_cast<CommandLineAPIScope**>(
      m_thisReference->GetBackingStore()->Data()) = this;
839
  for (uint32_t i = 0; i < names->Length(); ++i) {
840 841 842 843 844 845 846 847 848
    v8::Local<v8::Value> name;
    if (!names->Get(context, i).ToLocal(&name) || !name->IsName()) continue;
    if (m_global->Has(context, name).FromMaybe(true)) continue;
    if (!m_installedMethods->Add(context, name).ToLocal(&m_installedMethods))
      continue;
    if (!m_global
             ->SetAccessor(context, v8::Local<v8::Name>::Cast(name),
                           CommandLineAPIScope::accessorGetterCallback,
                           CommandLineAPIScope::accessorSetterCallback,
849
                           m_thisReference, v8::DEFAULT, v8::DontEnum,
850
                           v8::SideEffectType::kHasNoSideEffect)
851 852 853
             .FromMaybe(false)) {
      bool removed = m_installedMethods->Delete(context, name).FromMaybe(false);
      DCHECK(removed);
854
      USE(removed);
855 856 857 858 859 860
      continue;
    }
  }
}

V8Console::CommandLineAPIScope::~CommandLineAPIScope() {
861 862
  v8::MicrotasksScope microtasksScope(m_context->GetIsolate(),
                                      v8::MicrotasksScope::kDoNotRunMicrotasks);
863 864
  *static_cast<CommandLineAPIScope**>(
      m_thisReference->GetBackingStore()->Data()) = nullptr;
865
  v8::Local<v8::Array> names = m_installedMethods->AsArray();
866
  for (uint32_t i = 0; i < names->Length(); ++i) {
867 868 869 870 871 872 873 874 875
    v8::Local<v8::Value> name;
    if (!names->Get(m_context, i).ToLocal(&name) || !name->IsName()) continue;
    if (name->IsString()) {
      v8::Local<v8::Value> descriptor;
      bool success = m_global
                         ->GetOwnPropertyDescriptor(
                             m_context, v8::Local<v8::String>::Cast(name))
                         .ToLocal(&descriptor);
      DCHECK(success);
876
      USE(success);
877 878 879 880 881
    }
  }
}

}  // namespace v8_inspector