log.cc 74.3 KB
Newer Older
danno@chromium.org's avatar
danno@chromium.org committed
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/logging/log.h"
6 7

#include <cstdarg>
8
#include <memory>
9
#include <sstream>
10

11
#include "src/api/api-inl.h"
12
#include "src/base/platform/platform.h"
13 14 15
#include "src/codegen/bailout-reason.h"
#include "src/codegen/macro-assembler.h"
#include "src/codegen/source-position-table.h"
16
#include "src/deoptimizer/deoptimizer.h"
17
#include "src/diagnostics/perf-jit.h"
18 19 20
#include "src/execution/isolate.h"
#include "src/execution/runtime-profiler.h"
#include "src/execution/vm-state-inl.h"
21
#include "src/handles/global-handles.h"
22
#include "src/init/bootstrapper.h"
23 24
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter.h"
25
#include "src/libsampler/sampler.h"
26 27 28
#include "src/logging/counters.h"
#include "src/logging/log-inl.h"
#include "src/logging/log-utils.h"
29
#include "src/objects/api-callbacks.h"
30
#include "src/profiler/tick-sample.h"
31
#include "src/snapshot/embedded/embedded-data.h"
32 33
#include "src/strings/string-stream.h"
#include "src/strings/unicode-inl.h"
34
#include "src/tracing/tracing-category-observer.h"
35
#include "src/utils/memcopy.h"
36
#include "src/wasm/wasm-code-manager.h"
37
#include "src/wasm/wasm-objects-inl.h"
38

39
#include "src/utils/version.h"
40

41 42
namespace v8 {
namespace internal {
43

44
#define DECLARE_EVENT(ignore1, name) #name,
45 46
static const char* kLogEventsNames[CodeEventListener::NUMBER_OF_LOG_EVENTS] = {
    LOG_EVENTS_AND_TAGS_LIST(DECLARE_EVENT)};
47 48
#undef DECLARE_EVENT

49 50 51 52 53 54 55 56 57 58 59 60 61 62
static v8::CodeEventType GetCodeEventTypeForTag(
    CodeEventListener::LogEventsAndTags tag) {
  switch (tag) {
    case CodeEventListener::NUMBER_OF_LOG_EVENTS:
#define V(Event, _) case CodeEventListener::Event:
      LOG_EVENTS_LIST(V)
#undef V
      return v8::CodeEventType::kUnknownType;
#define V(From, To)             \
  case CodeEventListener::From: \
    return v8::CodeEventType::k##To##Type;
      TAGS_LIST(V)
#undef V
  }
63 64 65 66
  // The execution should never pass here
  UNREACHABLE();
  // NOTE(mmarchini): Workaround to fix a compiler failure on GCC 4.9
  return v8::CodeEventType::kUnknownType;
67 68 69 70 71 72 73 74
}
#define CALL_CODE_EVENT_HANDLER(Call) \
  if (listener_) {                    \
    listener_->Call;                  \
  } else {                            \
    PROFILE(isolate_, Call);          \
  }

75
static const char* ComputeMarker(SharedFunctionInfo shared, AbstractCode code) {
76
  switch (code.kind()) {
77
    case AbstractCode::INTERPRETED_FUNCTION:
78
      return shared.optimization_disabled() ? "" : "~";
79
    case AbstractCode::OPTIMIZED_FUNCTION:
80 81 82
      return "*";
    default:
      return "";
83 84 85
  }
}

86
static const char* ComputeMarker(const wasm::WasmCode* code) {
87 88 89
  switch (code->kind()) {
    case wasm::WasmCode::kFunction:
      return code->is_liftoff() ? "" : "*";
90
    case wasm::WasmCode::kInterpreterEntry:
91 92 93 94 95
      return "~";
    default:
      return "";
  }
}
96

97
class CodeEventLogger::NameBuffer {
98
 public:
99
  NameBuffer() { Reset(); }
100

101
  void Reset() { utf8_pos_ = 0; }
102

103
  void Init(LogEventsAndTags tag) {
104 105 106 107 108
    Reset();
    AppendBytes(kLogEventsNames[tag]);
    AppendByte(':');
  }

109
  void AppendName(Name name) {
110
    if (name.IsString()) {
111 112
      AppendString(String::cast(name));
    } else {
113
      Symbol symbol = Symbol::cast(name);
114
      AppendBytes("symbol(");
115
      if (!symbol.description().IsUndefined()) {
116
        AppendBytes("\"");
117
        AppendString(String::cast(symbol.description()));
118
        AppendBytes("\" ");
119
      }
120
      AppendBytes("hash ");
121
      AppendHex(symbol.Hash());
122
      AppendByte(')');
123
    }
124
  }
125

126 127
  void AppendString(String str) {
    if (str.is_null()) return;
128 129
    int length = 0;
    std::unique_ptr<char[]> c_str =
130
        str.ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL, &length);
131
    AppendBytes(c_str.get(), length);
132
  }
133

134 135
  void AppendBytes(const char* bytes, int size) {
    size = Min(size, kUtf8BufferSize - utf8_pos_);
136
    MemCopy(utf8_buffer_ + utf8_pos_, bytes, size);
137 138
    utf8_pos_ += size;
  }
139

140
  void AppendBytes(const char* bytes) {
141 142 143
    size_t len = strlen(bytes);
    DCHECK_GE(kMaxInt, len);
    AppendBytes(bytes, static_cast<int>(len));
144
  }
145

146 147 148 149
  void AppendByte(char c) {
    if (utf8_pos_ >= kUtf8BufferSize) return;
    utf8_buffer_[utf8_pos_++] = c;
  }
150

151
  void AppendInt(int n) {
152 153 154
    int space = kUtf8BufferSize - utf8_pos_;
    if (space <= 0) return;
    Vector<char> buffer(utf8_buffer_ + utf8_pos_, space);
155
    int size = SNPrintF(buffer, "%d", n);
156 157
    if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) {
      utf8_pos_ += size;
158
    }
159
  }
160

161
  void AppendHex(uint32_t n) {
162 163 164
    int space = kUtf8BufferSize - utf8_pos_;
    if (space <= 0) return;
    Vector<char> buffer(utf8_buffer_ + utf8_pos_, space);
165
    int size = SNPrintF(buffer, "%x", n);
166 167
    if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) {
      utf8_pos_ += size;
168
    }
169
  }
170

171 172
  const char* get() { return utf8_buffer_; }
  int size() const { return utf8_pos_; }
173 174

 private:
175
  static const int kUtf8BufferSize = 512;
176
  static const int kUtf16BufferSize = kUtf8BufferSize;
177

178 179
  int utf8_pos_;
  char utf8_buffer_[kUtf8BufferSize];
180 181
};

182
CodeEventLogger::CodeEventLogger(Isolate* isolate)
183
    : isolate_(isolate), name_buffer_(std::make_unique<NameBuffer>()) {}
184

185
CodeEventLogger::~CodeEventLogger() = default;
186

187 188 189
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
                                      Handle<AbstractCode> code,
                                      const char* comment) {
190 191
  name_buffer_->Init(tag);
  name_buffer_->AppendBytes(comment);
192 193
  LogRecordedBuffer(code, MaybeHandle<SharedFunctionInfo>(),
                    name_buffer_->get(), name_buffer_->size());
194 195
}

196 197 198
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
                                      Handle<AbstractCode> code,
                                      Handle<Name> name) {
199
  name_buffer_->Init(tag);
200
  name_buffer_->AppendName(*name);
201 202
  LogRecordedBuffer(code, MaybeHandle<SharedFunctionInfo>(),
                    name_buffer_->get(), name_buffer_->size());
203 204
}

205 206 207 208
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
                                      Handle<AbstractCode> code,
                                      Handle<SharedFunctionInfo> shared,
                                      Handle<Name> script_name) {
209
  name_buffer_->Init(tag);
210
  name_buffer_->AppendBytes(ComputeMarker(*shared, *code));
211
  name_buffer_->AppendByte(' ');
212
  name_buffer_->AppendName(*script_name);
213
  LogRecordedBuffer(code, shared, name_buffer_->get(), name_buffer_->size());
214 215
}

216 217 218 219 220
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
                                      Handle<AbstractCode> code,
                                      Handle<SharedFunctionInfo> shared,
                                      Handle<Name> script_name, int line,
                                      int column) {
221
  name_buffer_->Init(tag);
222 223
  name_buffer_->AppendBytes(ComputeMarker(*shared, *code));
  name_buffer_->AppendString(shared->DebugName());
224
  name_buffer_->AppendByte(' ');
225 226
  if (script_name->IsString()) {
    name_buffer_->AppendString(String::cast(*script_name));
227
  } else {
228
    name_buffer_->AppendBytes("symbol(hash ");
229
    name_buffer_->AppendHex(Name::cast(*script_name).Hash());
230
    name_buffer_->AppendByte(')');
231
  }
232 233
  name_buffer_->AppendByte(':');
  name_buffer_->AppendInt(line);
234
  LogRecordedBuffer(code, shared, name_buffer_->get(), name_buffer_->size());
235 236
}

237
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
238
                                      const wasm::WasmCode* code,
239 240
                                      wasm::WasmName name) {
  name_buffer_->Init(tag);
241 242
  DCHECK(!name.empty());
  name_buffer_->AppendBytes(name.begin(), name.length());
243 244 245 246 247 248
  name_buffer_->AppendByte('-');
  if (code->IsAnonymous()) {
    name_buffer_->AppendBytes("<anonymous>");
  } else {
    name_buffer_->AppendInt(code->index());
  }
249 250
  name_buffer_->AppendByte('-');
  name_buffer_->AppendBytes(ExecutionTierToString(code->tier()));
251 252 253
  LogRecordedBuffer(code, name_buffer_->get(), name_buffer_->size());
}

254 255
void CodeEventLogger::RegExpCodeCreateEvent(Handle<AbstractCode> code,
                                            Handle<String> source) {
256
  name_buffer_->Init(CodeEventListener::REG_EXP_TAG);
257
  name_buffer_->AppendString(*source);
258 259
  LogRecordedBuffer(code, MaybeHandle<SharedFunctionInfo>(),
                    name_buffer_->get(), name_buffer_->size());
260 261
}

262 263
// Linux perf tool logging support.
#if V8_OS_LINUX
264 265
class PerfBasicLogger : public CodeEventLogger {
 public:
266
  explicit PerfBasicLogger(Isolate* isolate);
267
  ~PerfBasicLogger() override;
268

269
  void CodeMoveEvent(AbstractCode from, AbstractCode to) override {}
270 271
  void CodeDisableOptEvent(Handle<AbstractCode> code,
                           Handle<SharedFunctionInfo> shared) override {}
272 273

 private:
274 275
  void LogRecordedBuffer(Handle<AbstractCode> code,
                         MaybeHandle<SharedFunctionInfo> maybe_shared,
276
                         const char* name, int length) override;
277
  void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
278 279 280
                         int length) override;
  void WriteLogRecordedBuffer(uintptr_t address, int size, const char* name,
                              int name_length);
281 282 283 284 285 286 287 288 289 290 291 292

  // Extension added to V8 log file name to get the low-level log name.
  static const char kFilenameFormatString[];
  static const int kFilenameBufferPadding;

  FILE* perf_output_handle_;
};

const char PerfBasicLogger::kFilenameFormatString[] = "/tmp/perf-%d.map";
// Extra space for the PID in the filename
const int PerfBasicLogger::kFilenameBufferPadding = 16;

293 294
PerfBasicLogger::PerfBasicLogger(Isolate* isolate)
    : CodeEventLogger(isolate), perf_output_handle_(nullptr) {
295 296 297
  // Open the perf JIT dump file.
  int bufferSize = sizeof(kFilenameFormatString) + kFilenameBufferPadding;
  ScopedVector<char> perf_dump_name(bufferSize);
298 299
  int size = SNPrintF(perf_dump_name, kFilenameFormatString,
                      base::OS::GetCurrentProcessId());
300
  CHECK_NE(size, -1);
301
  perf_output_handle_ =
302
      base::OS::FOpen(perf_dump_name.begin(), base::OS::LogFileOpenMode);
303
  CHECK_NOT_NULL(perf_output_handle_);
304
  setvbuf(perf_output_handle_, nullptr, _IOLBF, 0);
305 306 307 308
}

PerfBasicLogger::~PerfBasicLogger() {
  fclose(perf_output_handle_);
309
  perf_output_handle_ = nullptr;
310 311
}

312 313 314 315 316 317 318 319 320 321 322 323 324
void PerfBasicLogger::WriteLogRecordedBuffer(uintptr_t address, int size,
                                             const char* name,
                                             int name_length) {
  // Linux perf expects hex literals without a leading 0x, while some
  // implementations of printf might prepend one when using the %p format
  // for pointers, leading to wrongly formatted JIT symbols maps.
  //
  // Instead, we use V8PRIxPTR format string and cast pointer to uintpr_t,
  // so that we have control over the exact output format.
  base::OS::FPrint(perf_output_handle_, "%" V8PRIxPTR " %x %.*s\n", address,
                   size, name_length, name);
}

325 326
void PerfBasicLogger::LogRecordedBuffer(Handle<AbstractCode> code,
                                        MaybeHandle<SharedFunctionInfo>,
327
                                        const char* name, int length) {
328
  if (FLAG_perf_basic_prof_only_functions &&
329 330 331
      (code->kind() != AbstractCode::INTERPRETED_FUNCTION &&
       code->kind() != AbstractCode::BUILTIN &&
       code->kind() != AbstractCode::OPTIMIZED_FUNCTION)) {
332 333 334
    return;
  }

335 336
  WriteLogRecordedBuffer(static_cast<uintptr_t>(code->InstructionStart()),
                         code->InstructionSize(), name, length);
337 338
}

339 340
void PerfBasicLogger::LogRecordedBuffer(const wasm::WasmCode* code,
                                        const char* name, int length) {
341 342
  WriteLogRecordedBuffer(static_cast<uintptr_t>(code->instruction_start()),
                         code->instructions().length(), name, length);
343
}
344
#endif  // V8_OS_LINUX
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
// External CodeEventListener
ExternalCodeEventListener::ExternalCodeEventListener(Isolate* isolate)
    : is_listening_(false), isolate_(isolate), code_event_handler_(nullptr) {}

ExternalCodeEventListener::~ExternalCodeEventListener() {
  if (is_listening_) {
    StopListening();
  }
}

void ExternalCodeEventListener::LogExistingCode() {
  HandleScope scope(isolate_);
  ExistingCodeLogger logger(isolate_, this);
  logger.LogCodeObjects();
  logger.LogCompiledFunctions();
}

void ExternalCodeEventListener::StartListening(
    CodeEventHandler* code_event_handler) {
  if (is_listening_ || code_event_handler == nullptr) {
    return;
  }
  code_event_handler_ = code_event_handler;
  is_listening_ = isolate_->code_event_dispatcher()->AddListener(this);
  if (is_listening_) {
    LogExistingCode();
  }
}
374

375 376 377 378 379 380 381 382 383
void ExternalCodeEventListener::StopListening() {
  if (!is_listening_) {
    return;
  }

  isolate_->code_event_dispatcher()->RemoveListener(this);
  is_listening_ = false;
}

384 385 386
void ExternalCodeEventListener::CodeCreateEvent(LogEventsAndTags tag,
                                                Handle<AbstractCode> code,
                                                const char* comment) {
387 388
  CodeEvent code_event;
  code_event.code_start_address =
389 390
      static_cast<uintptr_t>(code->InstructionStart());
  code_event.code_size = static_cast<size_t>(code->InstructionSize());
391 392 393 394 395 396 397 398 399 400
  code_event.function_name = isolate_->factory()->empty_string();
  code_event.script_name = isolate_->factory()->empty_string();
  code_event.script_line = 0;
  code_event.script_column = 0;
  code_event.code_type = GetCodeEventTypeForTag(tag);
  code_event.comment = comment;

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

401 402 403
void ExternalCodeEventListener::CodeCreateEvent(LogEventsAndTags tag,
                                                Handle<AbstractCode> code,
                                                Handle<Name> name) {
404
  Handle<String> name_string =
405
      Name::ToFunctionName(isolate_, name).ToHandleChecked();
406 407 408

  CodeEvent code_event;
  code_event.code_start_address =
409 410
      static_cast<uintptr_t>(code->InstructionStart());
  code_event.code_size = static_cast<size_t>(code->InstructionSize());
411 412 413 414 415 416 417 418 419 420 421
  code_event.function_name = name_string;
  code_event.script_name = isolate_->factory()->empty_string();
  code_event.script_line = 0;
  code_event.script_column = 0;
  code_event.code_type = GetCodeEventTypeForTag(tag);
  code_event.comment = "";

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

void ExternalCodeEventListener::CodeCreateEvent(
422 423
    LogEventsAndTags tag, Handle<AbstractCode> code,
    Handle<SharedFunctionInfo> shared, Handle<Name> name) {
424
  Handle<String> name_string =
425
      Name::ToFunctionName(isolate_, name).ToHandleChecked();
426 427 428

  CodeEvent code_event;
  code_event.code_start_address =
429 430
      static_cast<uintptr_t>(code->InstructionStart());
  code_event.code_size = static_cast<size_t>(code->InstructionSize());
431 432 433 434 435 436 437 438 439 440 441
  code_event.function_name = name_string;
  code_event.script_name = isolate_->factory()->empty_string();
  code_event.script_line = 0;
  code_event.script_column = 0;
  code_event.code_type = GetCodeEventTypeForTag(tag);
  code_event.comment = "";

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

void ExternalCodeEventListener::CodeCreateEvent(
442 443 444
    LogEventsAndTags tag, Handle<AbstractCode> code,
    Handle<SharedFunctionInfo> shared, Handle<Name> source, int line,
    int column) {
445
  Handle<String> name_string =
446
      Name::ToFunctionName(isolate_, handle(shared->Name(), isolate_))
447 448
          .ToHandleChecked();
  Handle<String> source_string =
449
      Name::ToFunctionName(isolate_, source).ToHandleChecked();
450 451 452

  CodeEvent code_event;
  code_event.code_start_address =
453 454
      static_cast<uintptr_t>(code->InstructionStart());
  code_event.code_size = static_cast<size_t>(code->InstructionSize());
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
  code_event.function_name = name_string;
  code_event.script_name = source_string;
  code_event.script_line = line;
  code_event.script_column = column;
  code_event.code_type = GetCodeEventTypeForTag(tag);
  code_event.comment = "";

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

void ExternalCodeEventListener::CodeCreateEvent(LogEventsAndTags tag,
                                                const wasm::WasmCode* code,
                                                wasm::WasmName name) {
  // TODO(mmarchini): handle later
}

471 472
void ExternalCodeEventListener::RegExpCodeCreateEvent(Handle<AbstractCode> code,
                                                      Handle<String> source) {
473 474
  CodeEvent code_event;
  code_event.code_start_address =
475 476 477
      static_cast<uintptr_t>(code->InstructionStart());
  code_event.code_size = static_cast<size_t>(code->InstructionSize());
  code_event.function_name = source;
478 479 480 481 482 483 484 485 486
  code_event.script_name = isolate_->factory()->empty_string();
  code_event.script_line = 0;
  code_event.script_column = 0;
  code_event.code_type = GetCodeEventTypeForTag(CodeEventListener::REG_EXP_TAG);
  code_event.comment = "";

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
void ExternalCodeEventListener::CodeMoveEvent(AbstractCode from,
                                              AbstractCode to) {
  CodeEvent code_event;
  code_event.previous_code_start_address =
      static_cast<uintptr_t>(from.InstructionStart());
  code_event.code_start_address = static_cast<uintptr_t>(to.InstructionStart());
  code_event.code_size = static_cast<size_t>(to.InstructionSize());
  code_event.function_name = isolate_->factory()->empty_string();
  code_event.script_name = isolate_->factory()->empty_string();
  code_event.script_line = 0;
  code_event.script_column = 0;
  code_event.code_type = v8::CodeEventType::kRelocationType;
  code_event.comment = "";

  code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}

504
// Low-level logging support.
505
class LowLevelLogger : public CodeEventLogger {
506
 public:
507
  LowLevelLogger(Isolate* isolate, const char* file_name);
508
  ~LowLevelLogger() override;
509

510
  void CodeMoveEvent(AbstractCode from, AbstractCode to) override;
511 512
  void CodeDisableOptEvent(Handle<AbstractCode> code,
                           Handle<SharedFunctionInfo> shared) override {}
513
  void SnapshotPositionEvent(HeapObject obj, int pos);
514
  void CodeMovingGCEvent() override;
515 516

 private:
517 518
  void LogRecordedBuffer(Handle<AbstractCode> code,
                         MaybeHandle<SharedFunctionInfo> maybe_shared,
519
                         const char* name, int length) override;
520
  void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
521
                         int length) override;
522

523
  // Low-level profiling event structures.
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
  struct CodeCreateStruct {
    static const char kTag = 'C';

    int32_t name_size;
    Address code_address;
    int32_t code_size;
  };

  struct CodeMoveStruct {
    static const char kTag = 'M';

    Address from_address;
    Address to_address;
  };

  static const char kCodeMovingGCTag = 'G';

  // Extension added to V8 log file name to get the low-level log name.
  static const char kLogExt[];

  void LogCodeInfo();
  void LogWriteBytes(const char* bytes, int size);

  template <typename T>
  void LogWriteStruct(const T& s) {
    char tag = T::kTag;
    LogWriteBytes(reinterpret_cast<const char*>(&tag), sizeof(tag));
    LogWriteBytes(reinterpret_cast<const char*>(&s), sizeof(s));
  }

  FILE* ll_output_handle_;
};

const char LowLevelLogger::kLogExt[] = ".ll";

559 560
LowLevelLogger::LowLevelLogger(Isolate* isolate, const char* name)
    : CodeEventLogger(isolate), ll_output_handle_(nullptr) {
561 562 563
  // Open the low-level log file.
  size_t len = strlen(name);
  ScopedVector<char> ll_name(static_cast<int>(len + sizeof(kLogExt)));
564 565
  MemCopy(ll_name.begin(), name, len);
  MemCopy(ll_name.begin() + len, kLogExt, sizeof(kLogExt));
566
  ll_output_handle_ =
567
      base::OS::FOpen(ll_name.begin(), base::OS::LogFileOpenMode);
568
  setvbuf(ll_output_handle_, nullptr, _IOLBF, 0);
569 570 571 572 573 574

  LogCodeInfo();
}

LowLevelLogger::~LowLevelLogger() {
  fclose(ll_output_handle_);
575
  ll_output_handle_ = nullptr;
576 577 578 579 580
}

void LowLevelLogger::LogCodeInfo() {
#if V8_TARGET_ARCH_IA32
  const char arch[] = "ia32";
581
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
582 583 584
  const char arch[] = "x64";
#elif V8_TARGET_ARCH_ARM
  const char arch[] = "arm";
585 586
#elif V8_TARGET_ARCH_PPC
  const char arch[] = "ppc";
587 588
#elif V8_TARGET_ARCH_PPC64
  const char arch[] = "ppc64";
589 590
#elif V8_TARGET_ARCH_MIPS
  const char arch[] = "mips";
591 592
#elif V8_TARGET_ARCH_ARM64
  const char arch[] = "arm64";
593 594
#elif V8_TARGET_ARCH_S390
  const char arch[] = "s390";
595 596 597 598 599 600
#else
  const char arch[] = "unknown";
#endif
  LogWriteBytes(arch, sizeof(arch));
}

601 602
void LowLevelLogger::LogRecordedBuffer(Handle<AbstractCode> code,
                                       MaybeHandle<SharedFunctionInfo>,
603
                                       const char* name, int length) {
604
  CodeCreateStruct event;
605
  event.name_size = length;
606 607
  event.code_address = code->InstructionStart();
  event.code_size = code->InstructionSize();
608
  LogWriteStruct(event);
609
  LogWriteBytes(name, length);
610 611
  LogWriteBytes(reinterpret_cast<const char*>(code->InstructionStart()),
                code->InstructionSize());
612 613
}

614 615
void LowLevelLogger::LogRecordedBuffer(const wasm::WasmCode* code,
                                       const char* name, int length) {
616 617
  CodeCreateStruct event;
  event.name_size = length;
618
  event.code_address = code->instruction_start();
619 620 621
  event.code_size = code->instructions().length();
  LogWriteStruct(event);
  LogWriteBytes(name, length);
622
  LogWriteBytes(reinterpret_cast<const char*>(code->instruction_start()),
623 624 625
                code->instructions().length());
}

626
void LowLevelLogger::CodeMoveEvent(AbstractCode from, AbstractCode to) {
627
  CodeMoveStruct event;
628 629
  event.from_address = from.InstructionStart();
  event.to_address = to.InstructionStart();
630 631 632 633 634
  LogWriteStruct(event);
}

void LowLevelLogger::LogWriteBytes(const char* bytes, int size) {
  size_t rv = fwrite(bytes, 1, size, ll_output_handle_);
635
  DCHECK(static_cast<size_t>(size) == rv);
636 637 638 639 640 641 642 643 644 645 646
  USE(rv);
}

void LowLevelLogger::CodeMovingGCEvent() {
  const char tag = kCodeMovingGCTag;

  LogWriteBytes(&tag, sizeof(tag));
}

class JitLogger : public CodeEventLogger {
 public:
647
  JitLogger(Isolate* isolate, JitCodeEventHandler code_event_handler);
648

649
  void CodeMoveEvent(AbstractCode from, AbstractCode to) override;
650 651
  void CodeDisableOptEvent(Handle<AbstractCode> code,
                           Handle<SharedFunctionInfo> shared) override {}
652 653 654
  void AddCodeLinePosInfoEvent(void* jit_handler_data, int pc_offset,
                               int position,
                               JitCodeEvent::PositionType position_type);
655

656
  void* StartCodePosInfoEvent();
657
  void EndCodePosInfoEvent(Address start_address, void* jit_handler_data);
658 659

 private:
660 661
  void LogRecordedBuffer(Handle<AbstractCode> code,
                         MaybeHandle<SharedFunctionInfo> maybe_shared,
662
                         const char* name, int length) override;
663
  void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
664
                         int length) override;
665 666

  JitCodeEventHandler code_event_handler_;
667
  base::Mutex logger_mutex_;
668 669
};

670 671
JitLogger::JitLogger(Isolate* isolate, JitCodeEventHandler code_event_handler)
    : CodeEventLogger(isolate), code_event_handler_(code_event_handler) {}
672

673 674
void JitLogger::LogRecordedBuffer(Handle<AbstractCode> code,
                                  MaybeHandle<SharedFunctionInfo> maybe_shared,
675
                                  const char* name, int length) {
676
  JitCodeEvent event;
677
  memset(static_cast<void*>(&event), 0, sizeof(event));
678
  event.type = JitCodeEvent::CODE_ADDED;
679
  event.code_start = reinterpret_cast<void*>(code->InstructionStart());
680
  event.code_type =
681 682 683 684 685 686 687
      code->IsCode() ? JitCodeEvent::JIT_CODE : JitCodeEvent::BYTE_CODE;
  event.code_len = code->InstructionSize();
  Handle<SharedFunctionInfo> shared;
  if (maybe_shared.ToHandle(&shared) && shared->script().IsScript()) {
    event.script = ToApiHandle<v8::UnboundScript>(shared);
  } else {
    event.script = Local<v8::UnboundScript>();
688
  }
689 690
  event.name.str = name;
  event.name.len = length;
691
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
692 693 694
  code_event_handler_(&event);
}

695
void JitLogger::LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
696 697
                                  int length) {
  JitCodeEvent event;
698
  memset(static_cast<void*>(&event), 0, sizeof(event));
699
  event.type = JitCodeEvent::CODE_ADDED;
700
  event.code_type = JitCodeEvent::JIT_CODE;
701
  event.code_start = code->instructions().begin();
702 703 704
  event.code_len = code->instructions().length();
  event.name.str = name;
  event.name.len = length;
705
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

  wasm::WasmModuleSourceMap* source_map =
      code->native_module()->GetWasmSourceMap();
  wasm::WireBytesRef code_ref =
      code->native_module()->module()->functions[code->index()].code;
  uint32_t code_offset = code_ref.offset();
  uint32_t code_end_offset = code_ref.end_offset();

  std::vector<v8::JitCodeEvent::line_info_t> mapping_info;
  std::string filename;
  std::unique_ptr<JitCodeEvent::wasm_source_info_t> wasm_source_info;

  if (source_map && source_map->IsValid() &&
      source_map->HasSource(code_offset, code_end_offset)) {
    size_t last_line_number = 0;

    for (SourcePositionTableIterator iterator(code->source_positions());
         !iterator.done(); iterator.Advance()) {
      uint32_t offset = iterator.source_position().ScriptOffset() + code_offset;
      if (!source_map->HasValidEntry(code_offset, offset)) continue;
      if (filename.empty()) {
        filename = source_map->GetFilename(offset);
      }
      mapping_info.push_back({static_cast<size_t>(iterator.code_offset()),
                              last_line_number, JitCodeEvent::POSITION});
      last_line_number = source_map->GetSourceLine(offset) + 1;
    }

    wasm_source_info = std::make_unique<JitCodeEvent::wasm_source_info_t>();
    wasm_source_info->filename = filename.c_str();
    wasm_source_info->filename_size = filename.size();
    wasm_source_info->line_number_table_size = mapping_info.size();
    wasm_source_info->line_number_table = mapping_info.data();

    event.wasm_source_info = wasm_source_info.get();
  }
742 743 744
  code_event_handler_(&event);
}

745
void JitLogger::CodeMoveEvent(AbstractCode from, AbstractCode to) {
746
  base::MutexGuard guard(&logger_mutex_);
747 748 749

  JitCodeEvent event;
  event.type = JitCodeEvent::CODE_MOVED;
750
  event.code_type =
751 752 753 754
      from.IsCode() ? JitCodeEvent::JIT_CODE : JitCodeEvent::BYTE_CODE;
  event.code_start = reinterpret_cast<void*>(from.InstructionStart());
  event.code_len = from.InstructionSize();
  event.new_code_start = reinterpret_cast<void*>(to.InstructionStart());
755
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
756 757 758 759 760

  code_event_handler_(&event);
}

void JitLogger::AddCodeLinePosInfoEvent(
761
    void* jit_handler_data, int pc_offset, int position,
762 763
    JitCodeEvent::PositionType position_type) {
  JitCodeEvent event;
764
  memset(static_cast<void*>(&event), 0, sizeof(event));
765 766 767 768 769
  event.type = JitCodeEvent::CODE_ADD_LINE_POS_INFO;
  event.user_data = jit_handler_data;
  event.line_info.offset = pc_offset;
  event.line_info.pos = position;
  event.line_info.position_type = position_type;
770
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
771 772 773 774 775 776

  code_event_handler_(&event);
}

void* JitLogger::StartCodePosInfoEvent() {
  JitCodeEvent event;
777
  memset(static_cast<void*>(&event), 0, sizeof(event));
778
  event.type = JitCodeEvent::CODE_START_LINE_INFO_RECORDING;
779
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
780 781 782 783 784

  code_event_handler_(&event);
  return event.user_data;
}

785
void JitLogger::EndCodePosInfoEvent(Address start_address,
786
                                    void* jit_handler_data) {
787
  JitCodeEvent event;
788
  memset(static_cast<void*>(&event), 0, sizeof(event));
789
  event.type = JitCodeEvent::CODE_END_LINE_INFO_RECORDING;
790
  event.code_start = reinterpret_cast<void*>(start_address);
791
  event.user_data = jit_handler_data;
792
  event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
793 794 795 796

  code_event_handler_(&event);
}

797 798 799 800 801 802 803
// TODO(lpy): Keeping sampling thread inside V8 is a workaround currently,
// the reason is to reduce code duplication during migration to sampler library,
// sampling thread, as well as the sampler, will be moved to D8 eventually.
class SamplingThread : public base::Thread {
 public:
  static const int kSamplingThreadStackSize = 64 * KB;

804 805 806
  SamplingThread(sampler::Sampler* sampler, int interval_microseconds)
      : base::Thread(
            base::Thread::Options("SamplingThread", kSamplingThreadStackSize)),
807
        sampler_(sampler),
808
        interval_microseconds_(interval_microseconds) {}
809
  void Run() override {
810
    while (sampler_->IsActive()) {
811
      sampler_->DoSample();
812 813
      base::OS::Sleep(
          base::TimeDelta::FromMicroseconds(interval_microseconds_));
814 815 816 817 818
    }
  }

 private:
  sampler::Sampler* sampler_;
819
  const int interval_microseconds_;
820 821
};

822 823 824 825 826
// The Profiler samples pc and sp values for the main thread.
// Each sample is appended to a circular buffer.
// An independent thread removes data and writes it to the log.
// This design minimizes the time spent in the sampler.
//
827
class Profiler : public base::Thread {
828
 public:
829
  explicit Profiler(Isolate* isolate);
830 831 832 833
  void Engage();
  void Disengage();

  // Inserts collected profiling data into buffer.
834
  void Insert(TickSample* sample) {
835
    if (Succ(head_) == static_cast<int>(base::Relaxed_Load(&tail_))) {
836 837 838 839
      overflow_ = true;
    } else {
      buffer_[head_] = *sample;
      head_ = Succ(head_);
840
      buffer_semaphore_.Signal();  // Tell we have an element.
841 842 843
    }
  }

844
  void Run() override;
845 846

 private:
847
  // Waits for a signal and removes profiling data.
848
  bool Remove(TickSample* sample) {
849
    buffer_semaphore_.Wait();  // Wait for an element.
850
    *sample = buffer_[base::Relaxed_Load(&tail_)];
851
    bool result = overflow_;
852 853
    base::Relaxed_Store(
        &tail_, static_cast<base::Atomic32>(Succ(base::Relaxed_Load(&tail_))));
854 855 856 857 858 859 860
    overflow_ = false;
    return result;
  }

  // Returns the next index in the cyclic buffer.
  int Succ(int index) { return (index + 1) % kBufferSize; }

861
  Isolate* isolate_;
862 863 864
  // Cyclic buffer for communicating profiling samples
  // between the signal handler and the worker thread.
  static const int kBufferSize = 128;
865 866 867
  TickSample buffer_[kBufferSize];  // Buffer storage.
  int head_;                        // Index to the buffer head.
  base::Atomic32 tail_;             // Index to the buffer tail.
868
  bool overflow_;  // Tell whether a buffer overflow has occurred.
869
  // Semaphore used for buffer synchronization.
870
  base::Semaphore buffer_semaphore_;
871 872

  // Tells whether worker thread should continue running.
873
  base::Atomic32 running_;
874 875 876 877 878 879
};

//
// Ticker used to provide ticks to the profiler and the sliding state
// window.
//
880
class Ticker : public sampler::Sampler {
881
 public:
882
  Ticker(Isolate* isolate, int interval_microseconds)
883
      : sampler::Sampler(reinterpret_cast<v8::Isolate*>(isolate)),
884
        sampling_thread_(
885
            std::make_unique<SamplingThread>(this, interval_microseconds)) {}
886

887
  ~Ticker() override {
888
    if (IsActive()) Stop();
889 890 891
  }

  void SetProfiler(Profiler* profiler) {
892
    DCHECK_NULL(profiler_);
893
    profiler_ = profiler;
894
    if (!IsActive()) Start();
895
    sampling_thread_->StartSynchronously();
896 897 898
  }

  void ClearProfiler() {
899
    profiler_ = nullptr;
900
    if (IsActive()) Stop();
901 902 903 904
    sampling_thread_->Join();
  }

  void SampleStack(const v8::RegisterState& state) override {
lpy's avatar
lpy committed
905
    if (!profiler_) return;
906 907 908
    Isolate* isolate = reinterpret_cast<Isolate*>(this->isolate());
    TickSample sample;
    sample.Init(isolate, state, TickSample::kIncludeCEntryFrame, true);
lpy's avatar
lpy committed
909
    profiler_->Insert(&sample);
910 911 912
  }

 private:
913 914
  Profiler* profiler_ = nullptr;
  std::unique_ptr<SamplingThread> sampling_thread_;
915 916 917
};

//
918
// Profiler implementation when invoking with --prof.
919
//
920
Profiler::Profiler(Isolate* isolate)
921
    : base::Thread(Options("v8:Profiler")),
922
      isolate_(isolate),
923
      head_(0),
924
      overflow_(false),
925
      buffer_semaphore_(0) {
926 927
  base::Relaxed_Store(&tail_, 0);
  base::Relaxed_Store(&running_, 0);
928
}
929 930

void Profiler::Engage() {
931 932
  std::vector<base::OS::SharedLibraryAddress> addresses =
      base::OS::GetSharedLibraryAddresses();
933 934 935
  for (const auto& address : addresses) {
    LOG(isolate_, SharedLibraryEvent(address.library_path, address.start,
                                     address.end, address.aslr_slide));
936
  }
937 938

  // Start thread processing the profiler buffer.
939
  base::Relaxed_Store(&running_, 1);
940
  CHECK(Start());
941 942

  // Register to get ticks.
yurys@chromium.org's avatar
yurys@chromium.org committed
943 944
  Logger* logger = isolate_->logger();
  logger->ticker_->SetProfiler(this);
945

yurys@chromium.org's avatar
yurys@chromium.org committed
946
  logger->ProfilerBeginEvent();
947 948 949 950
}

void Profiler::Disengage() {
  // Stop receiving ticks.
951
  isolate_->logger()->ticker_->ClearProfiler();
952

953 954 955
  // Terminate the worker thread by setting running_ to false,
  // inserting a fake element in the queue and then wait for
  // the thread to terminate.
956
  base::Relaxed_Store(&running_, 0);
957
  TickSample sample;
958 959
  Insert(&sample);
  Join();
960

dcarney@chromium.org's avatar
dcarney@chromium.org committed
961
  LOG(isolate_, UncheckedStringEvent("profiler", "end"));
962 963
}

964
void Profiler::Run() {
965
  TickSample sample;
966
  bool overflow = Remove(&sample);
967
  while (base::Relaxed_Load(&running_)) {
968 969 970
    LOG(isolate_, TickEvent(&sample, overflow));
    overflow = Remove(&sample);
  }
971 972
}

973 974 975
//
// Logger class implementation.
//
976

977
Logger::Logger(Isolate* isolate)
978 979
    : isolate_(isolate),
      is_logging_(false),
980 981
      is_initialized_(false),
      existing_code_logger_(isolate) {}
982

983
Logger::~Logger() = default;
984

985 986
const LogSeparator Logger::kNext = LogSeparator::kSeparator;

987
void Logger::AddCodeEventListener(CodeEventListener* listener) {
988
  bool result = isolate_->code_event_dispatcher()->AddListener(listener);
989
  CHECK(result);
990 991
}

992
void Logger::RemoveCodeEventListener(CodeEventListener* listener) {
993
  isolate_->code_event_dispatcher()->RemoveListener(listener);
994 995
}

996
void Logger::ProfilerBeginEvent() {
997
  if (!log_->IsEnabled()) return;
998
  Log::MessageBuilder msg(log_.get());
999
  msg << "profiler" << kNext << "begin" << kNext << FLAG_prof_sampling_interval;
1000 1001 1002
  msg.WriteToLogFile();
}

1003
void Logger::StringEvent(const char* name, const char* value) {
1004 1005 1006 1007
  if (FLAG_log) UncheckedStringEvent(name, value);
}

void Logger::UncheckedStringEvent(const char* name, const char* value) {
1008
  if (!log_->IsEnabled()) return;
1009
  Log::MessageBuilder msg(log_.get());
1010
  msg << name << kNext << value;
1011
  msg.WriteToLogFile();
1012 1013
}

1014 1015 1016 1017 1018
void Logger::IntPtrTEvent(const char* name, intptr_t value) {
  if (FLAG_log) UncheckedIntPtrTEvent(name, value);
}

void Logger::UncheckedIntPtrTEvent(const char* name, intptr_t value) {
1019
  if (!log_->IsEnabled()) return;
1020
  Log::MessageBuilder msg(log_.get());
1021
  msg << name << kNext;
1022
  msg.AppendFormatString("%" V8PRIdPTR, value);
1023 1024 1025
  msg.WriteToLogFile();
}

1026
void Logger::HandleEvent(const char* name, Address* location) {
1027
  if (!log_->IsEnabled() || !FLAG_log_handles) return;
1028
  Log::MessageBuilder msg(log_.get());
1029
  msg << name << kNext << reinterpret_cast<void*>(location);
1030
  msg.WriteToLogFile();
1031 1032
}

1033
void Logger::ApiSecurityCheck() {
1034
  if (!log_->IsEnabled() || !FLAG_log_api) return;
1035
  Log::MessageBuilder msg(log_.get());
1036 1037
  msg << "api" << kNext << "check-security";
  msg.WriteToLogFile();
1038 1039
}

1040
void Logger::SharedLibraryEvent(const std::string& library_path,
1041 1042
                                uintptr_t start, uintptr_t end,
                                intptr_t aslr_slide) {
jkummerow's avatar
jkummerow committed
1043
  if (!log_->IsEnabled() || !FLAG_prof_cpp) return;
1044
  Log::MessageBuilder msg(log_.get());
1045 1046 1047
  msg << "shared-library" << kNext << library_path.c_str() << kNext
      << reinterpret_cast<void*>(start) << kNext << reinterpret_cast<void*>(end)
      << kNext << aslr_slide;
1048
  msg.WriteToLogFile();
1049 1050
}

1051 1052
void Logger::CurrentTimeEvent() {
  if (!log_->IsEnabled()) return;
1053
  DCHECK(FLAG_log_internal_timer_events);
1054
  Log::MessageBuilder msg(log_.get());
1055
  msg << "current-time" << kNext << timer_.Elapsed().InMicroseconds();
1056 1057 1058
  msg.WriteToLogFile();
}

1059
void Logger::TimerEvent(Logger::StartEnd se, const char* name) {
1060
  if (!log_->IsEnabled()) return;
1061
  Log::MessageBuilder msg(log_.get());
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  switch (se) {
    case START:
      msg << "timer-event-start";
      break;
    case END:
      msg << "timer-event-end";
      break;
    case STAMP:
      msg << "timer-event";
  }
1072
  msg << kNext << name << kNext << timer_.Elapsed().InMicroseconds();
1073 1074 1075
  msg.WriteToLogFile();
}

1076 1077 1078 1079 1080 1081
bool Logger::is_logging() {
  // Disable logging while the CPU profiler is running.
  if (isolate_->is_profiling()) return false;
  return is_logging_;
}

1082 1083 1084 1085 1086 1087
// Instantiate template methods.
#define V(TimerName, expose)                                           \
  template void TimerEventScope<TimerEvent##TimerName>::LogTimerEvent( \
      Logger::StartEnd se);
TIMER_EVENTS_LIST(V)
#undef V
1088

1089
void Logger::ApiNamedPropertyAccess(const char* tag, JSObject holder,
1090
                                    Object property_name) {
1091
  DCHECK(property_name.IsName());
1092
  if (!log_->IsEnabled() || !FLAG_log_api) return;
1093
  Log::MessageBuilder msg(log_.get());
1094
  msg << "api" << kNext << tag << kNext << holder.class_name() << kNext
1095 1096
      << Name::cast(property_name);
  msg.WriteToLogFile();
1097 1098
}

1099
void Logger::ApiIndexedPropertyAccess(const char* tag, JSObject holder,
1100
                                      uint32_t index) {
1101
  if (!log_->IsEnabled() || !FLAG_log_api) return;
1102
  Log::MessageBuilder msg(log_.get());
1103
  msg << "api" << kNext << tag << kNext << holder.class_name() << kNext
1104 1105
      << index;
  msg.WriteToLogFile();
1106 1107
}

1108
void Logger::ApiObjectAccess(const char* tag, JSObject object) {
1109
  if (!log_->IsEnabled() || !FLAG_log_api) return;
1110
  Log::MessageBuilder msg(log_.get());
1111
  msg << "api" << kNext << tag << kNext << object.class_name();
1112
  msg.WriteToLogFile();
1113 1114 1115
}

void Logger::ApiEntryCall(const char* name) {
1116
  if (!log_->IsEnabled() || !FLAG_log_api) return;
1117
  Log::MessageBuilder msg(log_.get());
1118 1119
  msg << "api" << kNext << name;
  msg.WriteToLogFile();
1120 1121 1122
}

void Logger::NewEvent(const char* name, void* object, size_t size) {
1123
  if (!log_->IsEnabled() || !FLAG_log) return;
1124
  Log::MessageBuilder msg(log_.get());
1125
  msg << "new" << kNext << name << kNext << object << kNext
1126
      << static_cast<unsigned int>(size);
1127
  msg.WriteToLogFile();
1128 1129 1130
}

void Logger::DeleteEvent(const char* name, void* object) {
1131
  if (!log_->IsEnabled() || !FLAG_log) return;
1132
  Log::MessageBuilder msg(log_.get());
1133
  msg << "delete" << kNext << name << kNext << object;
1134
  msg.WriteToLogFile();
1135 1136
}

1137 1138
namespace {

1139 1140 1141 1142
void AppendCodeCreateHeader(
    Log::MessageBuilder& msg,  // NOLINT(runtime/references)
    CodeEventListener::LogEventsAndTags tag, AbstractCode::Kind kind,
    uint8_t* address, int size, base::ElapsedTimer* timer) {
1143
  msg << kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT]
1144
      << Logger::kNext << kLogEventsNames[tag] << Logger::kNext << kind
1145
      << Logger::kNext << timer->Elapsed().InMicroseconds() << Logger::kNext
1146 1147 1148 1149
      << reinterpret_cast<void*>(address) << Logger::kNext << size
      << Logger::kNext;
}

1150 1151 1152 1153
void AppendCodeCreateHeader(
    Log::MessageBuilder& msg,  // NOLINT(runtime/references)
    CodeEventListener::LogEventsAndTags tag, AbstractCode code,
    base::ElapsedTimer* timer) {
1154 1155 1156
  AppendCodeCreateHeader(msg, tag, code.kind(),
                         reinterpret_cast<uint8_t*>(code.InstructionStart()),
                         code.InstructionSize(), timer);
1157 1158
}

1159 1160
}  // namespace

1161 1162
void Logger::CodeCreateEvent(LogEventsAndTags tag, Handle<AbstractCode> code,
                             const char* name) {
1163
  if (!is_listening_to_code_events()) return;
1164
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1165
  Log::MessageBuilder msg(log_.get());
1166 1167
  AppendCodeCreateHeader(msg, tag, *code, &timer_);
  msg << name;
1168
  msg.WriteToLogFile();
1169 1170
}

1171 1172
void Logger::CodeCreateEvent(LogEventsAndTags tag, Handle<AbstractCode> code,
                             Handle<Name> name) {
1173
  if (!is_listening_to_code_events()) return;
1174
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1175
  Log::MessageBuilder msg(log_.get());
1176 1177
  AppendCodeCreateHeader(msg, tag, *code, &timer_);
  msg << *name;
1178
  msg.WriteToLogFile();
1179 1180
}

1181 1182 1183
void Logger::CodeCreateEvent(LogEventsAndTags tag, Handle<AbstractCode> code,
                             Handle<SharedFunctionInfo> shared,
                             Handle<Name> script_name) {
1184
  if (!is_listening_to_code_events()) return;
1185
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1186 1187
  if (*code == AbstractCode::cast(
                   isolate_->builtins()->builtin(Builtins::kCompileLazy))) {
1188 1189
    return;
  }
1190

1191
  Log::MessageBuilder msg(log_.get());
1192 1193 1194
  AppendCodeCreateHeader(msg, tag, *code, &timer_);
  msg << *script_name << kNext << reinterpret_cast<void*>(shared->address())
      << kNext << ComputeMarker(*shared, *code);
1195 1196
  msg.WriteToLogFile();
}
1197

1198 1199 1200
// Although, it is possible to extract source and line from
// the SharedFunctionInfo object, we left it to caller
// to leave logging functions free from heap allocations.
1201 1202 1203
void Logger::CodeCreateEvent(LogEventsAndTags tag, Handle<AbstractCode> code,
                             Handle<SharedFunctionInfo> shared,
                             Handle<Name> script_name, int line, int column) {
1204
  if (!is_listening_to_code_events()) return;
1205
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1206
  {
1207
    Log::MessageBuilder msg(log_.get());
1208 1209 1210 1211
    AppendCodeCreateHeader(msg, tag, *code, &timer_);
    msg << shared->DebugName() << " " << *script_name << ":" << line << ":"
        << column << kNext << reinterpret_cast<void*>(shared->address())
        << kNext << ComputeMarker(*shared, *code);
1212 1213
    msg.WriteToLogFile();
  }
1214 1215

  if (!FLAG_log_source_code) return;
1216
  Object script_object = shared->script();
1217
  if (!script_object.IsScript()) return;
1218
  Script script = Script::cast(script_object);
1219
  if (!EnsureLogScriptSource(script)) return;
1220

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
  // We log source code information in the form:
  //
  // code-source-info <addr>,<script>,<start>,<end>,<pos>,<inline-pos>,<fns>
  //
  // where
  //   <addr> is code object address
  //   <script> is script id
  //   <start> is the starting position inside the script
  //   <end> is the end position inside the script
  //   <pos> is source position table encoded in the string,
  //      it is a sequence of C<code-offset>O<script-offset>[I<inlining-id>]
  //      where
  //        <code-offset> is the offset within the code object
  //        <script-offset> is the position within the script
  //        <inlining-id> is the offset in the <inlining> table
  //   <inlining> table is a sequence of strings of the form
1237
  //      F<function-id>O<script-offset>[I<inlining-id>]
1238 1239 1240 1241
  //      where
  //         <function-id> is an index into the <fns> function table
  //   <fns> is the function table encoded as a sequence of strings
  //      S<shared-function-info-address>
1242
  Log::MessageBuilder msg(log_.get());
1243
  msg << "code-source-info" << kNext
1244 1245 1246
      << reinterpret_cast<void*>(code->InstructionStart()) << kNext
      << script.id() << kNext << shared->StartPosition() << kNext
      << shared->EndPosition() << kNext;
1247

1248
  SourcePositionTableIterator iterator(code->source_position_table());
1249 1250 1251 1252 1253 1254 1255 1256 1257
  bool hasInlined = false;
  for (; !iterator.done(); iterator.Advance()) {
    SourcePosition pos = iterator.source_position();
    msg << "C" << iterator.code_offset() << "O" << pos.ScriptOffset();
    if (pos.isInlined()) {
      msg << "I" << pos.InliningId();
      hasInlined = true;
    }
  }
1258
  msg << kNext;
1259 1260
  int maxInlinedId = -1;
  if (hasInlined) {
1261
    PodArray<InliningPosition> inlining_positions =
1262 1263
        DeoptimizationData::cast(
            Handle<Code>::cast(code)->deoptimization_data())
1264 1265 1266
            .InliningPositions();
    for (int i = 0; i < inlining_positions.length(); i++) {
      InliningPosition inlining_pos = inlining_positions.get(i);
1267 1268 1269 1270 1271
      msg << "F";
      if (inlining_pos.inlined_function_id != -1) {
        msg << inlining_pos.inlined_function_id;
        if (inlining_pos.inlined_function_id > maxInlinedId) {
          maxInlinedId = inlining_pos.inlined_function_id;
1272 1273
        }
      }
1274 1275 1276 1277
      SourcePosition pos = inlining_pos.position;
      msg << "O" << pos.ScriptOffset();
      if (pos.isInlined()) {
        msg << "I" << pos.InliningId();
1278
      }
1279
    }
1280
  }
1281
  msg << kNext;
1282
  if (hasInlined) {
1283 1284
    DeoptimizationData deopt_data = DeoptimizationData::cast(
        Handle<Code>::cast(code)->deoptimization_data());
1285 1286 1287 1288

    msg << std::hex;
    for (int i = 0; i <= maxInlinedId; i++) {
      msg << "S"
1289
          << reinterpret_cast<void*>(
1290
                 deopt_data.GetInlinedFunction(i).address());
1291 1292 1293 1294
    }
    msg << std::dec;
  }
  msg.WriteToLogFile();
1295 1296
}

1297 1298
void Logger::CodeCreateEvent(LogEventsAndTags tag, const wasm::WasmCode* code,
                             wasm::WasmName name) {
1299
  if (!is_listening_to_code_events()) return;
1300
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1301
  Log::MessageBuilder msg(log_.get());
1302 1303 1304
  AppendCodeCreateHeader(msg, tag, AbstractCode::Kind::WASM_FUNCTION,
                         code->instructions().begin(),
                         code->instructions().length(), &timer_);
1305 1306 1307
  DCHECK(!name.empty());
  msg.AppendString(name);

1308 1309 1310 1311 1312 1313 1314 1315
  // We have to add two extra fields that allow the tick processor to group
  // events for the same wasm function, even if it gets compiled again. For
  // normal JS functions, we use the shared function info. For wasm, the pointer
  // to the native module + function index works well enough.
  // TODO(herhut) Clean up the tick processor code instead.
  void* tag_ptr =
      reinterpret_cast<byte*>(code->native_module()) + code->index();
  msg << kNext << tag_ptr << kNext << ComputeMarker(code);
1316 1317 1318
  msg.WriteToLogFile();
}

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
void Logger::CallbackEventInternal(const char* prefix, Handle<Name> name,
                                   Address entry_point) {
  if (!FLAG_log_code || !log_->IsEnabled()) return;
  Log::MessageBuilder msg(log_.get());
  msg << kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT] << kNext
      << kLogEventsNames[CodeEventListener::CALLBACK_TAG] << kNext << -2
      << kNext << timer_.Elapsed().InMicroseconds() << kNext
      << reinterpret_cast<void*>(entry_point) << kNext << 1 << kNext << prefix
      << *name;
  msg.WriteToLogFile();
}

void Logger::CallbackEvent(Handle<Name> name, Address entry_point) {
  CallbackEventInternal("", name, entry_point);
}

void Logger::GetterCallbackEvent(Handle<Name> name, Address entry_point) {
  CallbackEventInternal("get ", name, entry_point);
1337 1338
}

1339 1340 1341 1342 1343 1344
void Logger::SetterCallbackEvent(Handle<Name> name, Address entry_point) {
  CallbackEventInternal("set ", name, entry_point);
}

void Logger::RegExpCodeCreateEvent(Handle<AbstractCode> code,
                                   Handle<String> source) {
1345
  if (!is_listening_to_code_events()) return;
1346
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1347
  Log::MessageBuilder msg(log_.get());
1348 1349
  AppendCodeCreateHeader(msg, CodeEventListener::REG_EXP_TAG, *code, &timer_);
  msg << *source;
1350 1351 1352
  msg.WriteToLogFile();
}

1353
void Logger::CodeMoveEvent(AbstractCode from, AbstractCode to) {
1354
  if (!is_listening_to_code_events()) return;
1355 1356
  MoveEventInternal(CodeEventListener::CODE_MOVE_EVENT, from.InstructionStart(),
                    to.InstructionStart());
1357 1358
}

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
void Logger::SharedFunctionInfoMoveEvent(Address from, Address to) {
  if (!is_listening_to_code_events()) return;
  MoveEventInternal(CodeEventListener::SHARED_FUNC_MOVE_EVENT, from, to);
}

void Logger::CodeMovingGCEvent() {
  if (!is_listening_to_code_events()) return;
  if (!log_->IsEnabled() || !FLAG_ll_prof) return;
  base::OS::SignalCodeMovingGC();
}

void Logger::CodeDisableOptEvent(Handle<AbstractCode> code,
                                 Handle<SharedFunctionInfo> shared) {
  if (!is_listening_to_code_events()) return;
  if (!FLAG_log_code || !log_->IsEnabled()) return;
  Log::MessageBuilder msg(log_.get());
  msg << kLogEventsNames[CodeEventListener::CODE_DISABLE_OPT_EVENT] << kNext
      << shared->DebugName() << kNext
      << GetBailoutReason(shared->disable_optimization_reason());
  msg.WriteToLogFile();
}

void Logger::CodeDeoptEvent(Handle<Code> code, DeoptimizeKind kind, Address pc,
                            int fp_to_sp_delta) {
  if (!log_->IsEnabled()) return;
  Deoptimizer::DeoptInfo info = Deoptimizer::GetDeoptInfo(*code, pc);
  Log::MessageBuilder msg(log_.get());
  msg << "code-deopt" << kNext << timer_.Elapsed().InMicroseconds() << kNext
      << code->CodeSize() << kNext
      << reinterpret_cast<void*>(code->InstructionStart());

  // Deoptimization position.
  std::ostringstream deopt_location;
  int inlining_id = -1;
  int script_offset = -1;
  if (info.position.IsKnown()) {
    info.position.Print(deopt_location, *code);
    inlining_id = info.position.InliningId();
    script_offset = info.position.ScriptOffset();
  } else {
    deopt_location << "<unknown>";
  }
  msg << kNext << inlining_id << kNext << script_offset << kNext;
  msg << Deoptimizer::MessageFor(kind) << kNext;
  msg << deopt_location.str().c_str() << kNext
      << DeoptimizeReasonToString(info.deopt_reason);
  msg.WriteToLogFile();
}

1408 1409
namespace {

1410 1411 1412
void CodeLinePosEvent(
    JitLogger* jit_logger, Address code_start,
    SourcePositionTableIterator& iter) {  // NOLINT(runtime/references)
1413 1414 1415
  if (jit_logger) {
    void* jit_handler_data = jit_logger->StartCodePosInfoEvent();
    for (; !iter.done(); iter.Advance()) {
1416
      if (iter.is_statement()) {
1417
        jit_logger->AddCodeLinePosInfoEvent(
1418 1419
            jit_handler_data, iter.code_offset(),
            iter.source_position().ScriptOffset(),
1420 1421
            JitCodeEvent::STATEMENT_POSITION);
      }
1422 1423 1424
      jit_logger->AddCodeLinePosInfoEvent(jit_handler_data, iter.code_offset(),
                                          iter.source_position().ScriptOffset(),
                                          JitCodeEvent::POSITION);
1425
    }
1426
    jit_logger->EndCodePosInfoEvent(code_start, jit_handler_data);
1427
  }
1428
}
1429

1430 1431 1432
}  // namespace

void Logger::CodeLinePosInfoRecordEvent(Address code_start,
1433
                                        ByteArray source_position_table) {
1434
  SourcePositionTableIterator iter(source_position_table);
1435
  CodeLinePosEvent(jit_logger_.get(), code_start, iter);
1436 1437 1438 1439 1440
}

void Logger::CodeLinePosInfoRecordEvent(
    Address code_start, Vector<const byte> source_position_table) {
  SourcePositionTableIterator iter(source_position_table);
1441
  CodeLinePosEvent(jit_logger_.get(), code_start, iter);
1442 1443
}

1444
void Logger::CodeNameEvent(Address addr, int pos, const char* code_name) {
1445
  if (code_name == nullptr) return;  // Not a code object.
1446
  Log::MessageBuilder msg(log_.get());
1447 1448
  msg << kLogEventsNames[CodeEventListener::SNAPSHOT_CODE_NAME_EVENT] << kNext
      << pos << kNext << code_name;
1449 1450 1451
  msg.WriteToLogFile();
}

1452 1453
void Logger::MoveEventInternal(LogEventsAndTags event, Address from,
                               Address to) {
1454
  if (!FLAG_log_code || !log_->IsEnabled()) return;
1455
  Log::MessageBuilder msg(log_.get());
1456 1457
  msg << kLogEventsNames[event] << kNext << reinterpret_cast<void*>(from)
      << kNext << reinterpret_cast<void*>(to);
1458
  msg.WriteToLogFile();
1459 1460
}

1461
void Logger::ResourceEvent(const char* name, const char* tag) {
1462
  if (!log_->IsEnabled() || !FLAG_log) return;
1463
  Log::MessageBuilder msg(log_.get());
1464
  msg << name << kNext << tag << kNext;
1465 1466

  uint32_t sec, usec;
1467
  if (base::OS::GetUserTime(&sec, &usec) != -1) {
1468
    msg << sec << kNext << usec << kNext;
1469
  }
1470 1471
  msg.AppendFormatString("%.0f",
                         V8::GetCurrentPlatform()->CurrentClockTimeMillis());
1472
  msg.WriteToLogFile();
1473 1474
}

1475
void Logger::SuspectReadEvent(Name name, Object obj) {
1476
  if (!log_->IsEnabled() || !FLAG_log_suspect) return;
1477
  Log::MessageBuilder msg(log_.get());
1478 1479
  String class_name = obj.IsJSObject() ? JSObject::cast(obj).class_name()
                                       : ReadOnlyRoots(isolate_).empty_string();
1480
  msg << "suspect-read" << kNext << class_name << kNext << name;
1481
  msg.WriteToLogFile();
1482 1483
}

1484
namespace {
1485 1486 1487 1488
void AppendFunctionMessage(
    Log::MessageBuilder& msg,  // NOLINT(runtime/references)
    const char* reason, int script_id, double time_delta, int start_position,
    int end_position, base::ElapsedTimer* timer) {
1489 1490
  msg << "function" << Logger::kNext << reason << Logger::kNext << script_id
      << Logger::kNext << start_position << Logger::kNext << end_position
1491 1492 1493 1494 1495
      << Logger::kNext << time_delta << Logger::kNext
      << timer->Elapsed().InMicroseconds() << Logger::kNext;
}
}  // namespace

1496 1497
void Logger::FunctionEvent(const char* reason, int script_id, double time_delta,
                           int start_position, int end_position,
1498
                           String function_name) {
1499
  if (!log_->IsEnabled() || !FLAG_log_function_events) return;
1500
  Log::MessageBuilder msg(log_.get());
1501 1502
  AppendFunctionMessage(msg, reason, script_id, time_delta, start_position,
                        end_position, &timer_);
1503
  if (!function_name.is_null()) msg << function_name;
1504 1505 1506
  msg.WriteToLogFile();
}

1507 1508 1509
void Logger::FunctionEvent(const char* reason, int script_id, double time_delta,
                           int start_position, int end_position,
                           const char* function_name,
1510
                           size_t function_name_length) {
1511
  if (!log_->IsEnabled() || !FLAG_log_function_events) return;
1512
  Log::MessageBuilder msg(log_.get());
1513 1514
  AppendFunctionMessage(msg, reason, script_id, time_delta, start_position,
                        end_position, &timer_);
1515
  if (function_name_length > 0) {
1516
    msg.AppendString(function_name, function_name_length);
1517 1518 1519
  }
  msg.WriteToLogFile();
}
1520

1521
void Logger::CompilationCacheEvent(const char* action, const char* cache_type,
1522
                                   SharedFunctionInfo sfi) {
1523
  if (!log_->IsEnabled() || !FLAG_log_function_events) return;
1524
  Log::MessageBuilder msg(log_.get());
1525
  int script_id = -1;
1526 1527
  if (sfi.script().IsScript()) {
    script_id = Script::cast(sfi.script()).id();
1528 1529
  }
  msg << "compilation-cache" << Logger::kNext << action << Logger::kNext
1530
      << cache_type << Logger::kNext << script_id << Logger::kNext
1531
      << sfi.StartPosition() << Logger::kNext << sfi.EndPosition()
1532
      << Logger::kNext << timer_.Elapsed().InMicroseconds();
1533 1534 1535
  msg.WriteToLogFile();
}

1536
void Logger::ScriptEvent(ScriptEventType type, int script_id) {
1537
  if (!log_->IsEnabled() || !FLAG_log_function_events) return;
1538
  Log::MessageBuilder msg(log_.get());
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
  msg << "script" << Logger::kNext;
  switch (type) {
    case ScriptEventType::kReserveId:
      msg << "reserve-id";
      break;
    case ScriptEventType::kCreate:
      msg << "create";
      break;
    case ScriptEventType::kDeserialize:
      msg << "deserialize";
      break;
    case ScriptEventType::kBackgroundCompile:
      msg << "background-compile";
      break;
1553 1554 1555
    case ScriptEventType::kStreamingCompile:
      msg << "streaming-compile";
      break;
1556
  }
1557 1558
  msg << Logger::kNext << script_id << Logger::kNext
      << timer_.Elapsed().InMicroseconds();
1559 1560 1561
  msg.WriteToLogFile();
}

1562
void Logger::ScriptDetails(Script script) {
1563
  if (!log_->IsEnabled() || !FLAG_log_function_events) return;
1564
  {
1565
    Log::MessageBuilder msg(log_.get());
1566 1567 1568
    msg << "script-details" << Logger::kNext << script.id() << Logger::kNext;
    if (script.name().IsString()) {
      msg << String::cast(script.name());
1569
    }
1570 1571 1572 1573
    msg << Logger::kNext << script.line_offset() << Logger::kNext
        << script.column_offset() << Logger::kNext;
    if (script.source_mapping_url().IsString()) {
      msg << String::cast(script.source_mapping_url());
1574 1575
    }
    msg.WriteToLogFile();
1576
  }
1577
  EnsureLogScriptSource(script);
1578 1579
}

1580
bool Logger::EnsureLogScriptSource(Script script) {
1581
  if (!log_->IsEnabled()) return false;
1582
  Log::MessageBuilder msg(log_.get());
1583
  // Make sure the script is written to the log file.
1584
  int script_id = script.id();
1585
  if (logged_source_code_.find(script_id) != logged_source_code_.end()) {
1586
    return true;
1587 1588 1589
  }
  // This script has not been logged yet.
  logged_source_code_.insert(script_id);
1590 1591
  Object source_object = script.source();
  if (!source_object.IsString()) return false;
1592
  String source_code = String::cast(source_object);
1593 1594 1595
  msg << "script-source" << kNext << script_id << kNext;

  // Log the script name.
1596 1597
  if (script.name().IsString()) {
    msg << String::cast(script.name()) << kNext;
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
  } else {
    msg << "<unknown>" << kNext;
  }

  // Log the source code.
  msg << source_code;
  msg.WriteToLogFile();
  return true;
}

1608 1609
void Logger::RuntimeCallTimerEvent() {
  RuntimeCallStats* stats = isolate_->counters()->runtime_call_stats();
1610
  RuntimeCallCounter* counter = stats->current_counter();
1611
  if (counter == nullptr) return;
1612
  Log::MessageBuilder msg(log_.get());
1613
  msg << "active-runtime-timer" << kNext << counter->name();
1614 1615
  msg.WriteToLogFile();
}
1616

1617
void Logger::TickEvent(TickSample* sample, bool overflow) {
jkummerow's avatar
jkummerow committed
1618
  if (!log_->IsEnabled() || !FLAG_prof_cpp) return;
1619
  if (V8_UNLIKELY(TracingFlags::runtime_stats.load(std::memory_order_relaxed) ==
1620
                  v8::tracing::TracingCategoryObserver::ENABLED_BY_NATIVE)) {
1621 1622
    RuntimeCallTimerEvent();
  }
1623
  Log::MessageBuilder msg(log_.get());
1624 1625 1626
  msg << kLogEventsNames[CodeEventListener::TICK_EVENT] << kNext
      << reinterpret_cast<void*>(sample->pc) << kNext
      << timer_.Elapsed().InMicroseconds();
1627
  if (sample->has_external_callback) {
1628 1629
    msg << kNext << 1 << kNext
        << reinterpret_cast<void*>(sample->external_callback_entry);
1630
  } else {
1631
    msg << kNext << 0 << kNext << reinterpret_cast<void*>(sample->tos);
1632
  }
1633 1634
  msg << kNext << static_cast<int>(sample->state);
  if (overflow) msg << kNext << "overflow";
1635
  for (unsigned i = 0; i < sample->frames_count; ++i) {
1636
    msg << kNext << reinterpret_cast<void*>(sample->stack[i]);
1637
  }
1638
  msg.WriteToLogFile();
1639
}
1640

1641 1642 1643
void Logger::ICEvent(const char* type, bool keyed, Handle<Map> map,
                     Handle<Object> key, char old_state, char new_state,
                     const char* modifier, const char* slow_stub_reason) {
1644
  if (!log_->IsEnabled() || !FLAG_trace_ic) return;
1645
  Log::MessageBuilder msg(log_.get());
1646
  if (keyed) msg << "Keyed";
1647 1648 1649
  int line;
  int column;
  Address pc = isolate_->GetAbstractPC(&line, &column);
1650 1651
  msg << type << kNext << reinterpret_cast<void*>(pc) << kNext << line << kNext
      << column << kNext << old_state << kNext << new_state << kNext
1652 1653 1654 1655 1656 1657 1658
      << AsHex::Address(map.is_null() ? kNullAddress : map->ptr()) << kNext;
  if (key->IsSmi()) {
    msg << Smi::ToInt(*key);
  } else if (key->IsNumber()) {
    msg << key->Number();
  } else if (key->IsName()) {
    msg << Name::cast(*key);
1659
  }
1660
  msg << kNext << modifier << kNext;
1661
  if (slow_stub_reason != nullptr) {
1662
    msg << slow_stub_reason;
1663 1664 1665 1666
  }
  msg.WriteToLogFile();
}

1667 1668
void Logger::MapEvent(const char* type, Handle<Map> from, Handle<Map> to,
                      const char* reason, Handle<HeapObject> name_or_sfi) {
1669
  if (!log_->IsEnabled() || !FLAG_trace_maps) return;
1670
  if (!to.is_null()) MapDetails(*to);
1671 1672 1673
  int line = -1;
  int column = -1;
  Address pc = 0;
Camillo Bruni's avatar
Camillo Bruni committed
1674

1675 1676 1677
  if (!isolate_->bootstrapper()->IsActive()) {
    pc = isolate_->GetAbstractPC(&line, &column);
  }
1678
  Log::MessageBuilder msg(log_.get());
1679
  msg << "map" << kNext << type << kNext << timer_.Elapsed().InMicroseconds()
1680 1681 1682 1683
      << kNext << AsHex::Address(from.is_null() ? kNullAddress : from->ptr())
      << kNext << AsHex::Address(to.is_null() ? kNullAddress : to->ptr())
      << kNext << AsHex::Address(pc) << kNext << line << kNext << column
      << kNext << reason << kNext;
1684

1685
  if (!name_or_sfi.is_null()) {
1686 1687 1688 1689
    if (name_or_sfi->IsName()) {
      msg << Name::cast(*name_or_sfi);
    } else if (name_or_sfi->IsSharedFunctionInfo()) {
      SharedFunctionInfo sfi = SharedFunctionInfo::cast(*name_or_sfi);
1690
      msg << sfi.DebugName();
1691
#if V8_SFI_HAS_UNIQUE_ID
1692
      msg << " " << sfi.unique_id();
1693 1694 1695 1696 1697 1698
#endif  // V8_SFI_HAS_UNIQUE_ID
    }
  }
  msg.WriteToLogFile();
}

1699
void Logger::MapCreate(Map map) {
Camillo Bruni's avatar
Camillo Bruni committed
1700 1701
  if (!log_->IsEnabled() || !FLAG_trace_maps) return;
  DisallowHeapAllocation no_gc;
1702
  Log::MessageBuilder msg(log_.get());
Camillo Bruni's avatar
Camillo Bruni committed
1703
  msg << "map-create" << kNext << timer_.Elapsed().InMicroseconds() << kNext
1704
      << AsHex::Address(map.ptr());
Camillo Bruni's avatar
Camillo Bruni committed
1705 1706 1707
  msg.WriteToLogFile();
}

1708
void Logger::MapDetails(Map map) {
1709 1710
  if (!log_->IsEnabled() || !FLAG_trace_maps) return;
  DisallowHeapAllocation no_gc;
1711
  Log::MessageBuilder msg(log_.get());
1712
  msg << "map-details" << kNext << timer_.Elapsed().InMicroseconds() << kNext
1713
      << AsHex::Address(map.ptr()) << kNext;
Camillo Bruni's avatar
Camillo Bruni committed
1714 1715
  if (FLAG_trace_maps_details) {
    std::ostringstream buffer;
1716
    map.PrintMapDetails(buffer);
Camillo Bruni's avatar
Camillo Bruni committed
1717 1718
    msg << buffer.str().c_str();
  }
1719 1720 1721
  msg.WriteToLogFile();
}

1722
static void AddFunctionAndCode(SharedFunctionInfo sfi, AbstractCode code_object,
1723 1724
                               Handle<SharedFunctionInfo>* sfis,
                               Handle<AbstractCode>* code_objects, int offset) {
1725
  if (sfis != nullptr) {
1726
    sfis[offset] = Handle<SharedFunctionInfo>(sfi, sfi.GetIsolate());
1727
  }
1728
  if (code_objects != nullptr) {
1729
    code_objects[offset] = Handle<AbstractCode>(code_object, sfi.GetIsolate());
1730 1731
  }
}
1732

1733 1734
static int EnumerateCompiledFunctions(Heap* heap,
                                      Handle<SharedFunctionInfo>* sfis,
1735
                                      Handle<AbstractCode>* code_objects) {
1736
  HeapObjectIterator iterator(heap);
1737
  DisallowHeapAllocation no_gc;
1738
  int compiled_funcs_count = 0;
1739 1740 1741

  // Iterate the heap to find shared function info objects and record
  // the unoptimized code for them.
1742 1743
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
1744
    if (obj.IsSharedFunctionInfo()) {
1745
      SharedFunctionInfo sfi = SharedFunctionInfo::cast(obj);
1746 1747 1748
      if (sfi.is_compiled() && (!sfi.script().IsScript() ||
                                Script::cast(sfi.script()).HasValidSource())) {
        AddFunctionAndCode(sfi, AbstractCode::cast(sfi.abstract_code()), sfis,
1749 1750
                           code_objects, compiled_funcs_count);
        ++compiled_funcs_count;
1751
      }
1752
    } else if (obj.IsJSFunction()) {
1753 1754
      // Given that we no longer iterate over all optimized JSFunctions, we need
      // to take care of this here.
1755
      JSFunction function = JSFunction::cast(obj);
1756 1757 1758 1759
      SharedFunctionInfo sfi = SharedFunctionInfo::cast(function.shared());
      Object maybe_script = sfi.script();
      if (maybe_script.IsScript() &&
          !Script::cast(maybe_script).HasValidSource()) {
1760 1761
        continue;
      }
1762 1763 1764
      // TODO(jarin) This leaves out deoptimized code that might still be on the
      // stack. Also note that we will not log optimized code objects that are
      // only on a type feedback vector. We should make this mroe precise.
1765 1766
      if (function.IsOptimized()) {
        AddFunctionAndCode(sfi, AbstractCode::cast(function.code()), sfis,
1767 1768
                           code_objects, compiled_funcs_count);
        ++compiled_funcs_count;
1769
      }
1770
    }
1771 1772 1773
  }
  return compiled_funcs_count;
}
1774

1775 1776
static int EnumerateWasmModuleObjects(
    Heap* heap, Handle<WasmModuleObject>* module_objects) {
1777
  HeapObjectIterator iterator(heap);
1778
  DisallowHeapAllocation no_gc;
1779
  int module_objects_count = 0;
1780

1781 1782
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
1783
    if (obj.IsWasmModuleObject()) {
1784
      WasmModuleObject module = WasmModuleObject::cast(obj);
1785
      if (module_objects != nullptr) {
1786 1787
        module_objects[module_objects_count] =
            handle(module, Isolate::FromHeap(heap));
1788
      }
1789
      module_objects_count++;
1790 1791
    }
  }
1792
  return module_objects_count;
1793
}
1794

1795
void Logger::LogCodeObject(Object object) {
1796
  existing_code_logger_.LogCodeObject(object);
1797 1798
}

1799
void Logger::LogCodeObjects() { existing_code_logger_.LogCodeObjects(); }
1800

1801
void Logger::LogExistingFunction(Handle<SharedFunctionInfo> shared,
1802
                                 Handle<AbstractCode> code) {
1803
  existing_code_logger_.LogExistingFunction(shared, code);
1804 1805
}

1806
void Logger::LogCompiledFunctions() {
1807
  existing_code_logger_.LogCompiledFunctions();
1808
}
1809 1810

void Logger::LogAccessorCallbacks() {
1811
  Heap* heap = isolate_->heap();
1812
  HeapObjectIterator iterator(heap);
1813
  DisallowHeapAllocation no_gc;
1814 1815
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
1816
    if (!obj.IsAccessorInfo()) continue;
1817
    AccessorInfo ai = AccessorInfo::cast(obj);
1818 1819
    if (!ai.name().IsName()) continue;
    Address getter_entry = v8::ToCData<Address>(ai.getter());
1820 1821
    HandleScope scope(isolate_);
    Handle<Name> name(Name::cast(ai.name()), isolate_);
1822
    if (getter_entry != 0) {
1823 1824 1825
#if USES_FUNCTION_DESCRIPTORS
      getter_entry = *FUNCTION_ENTRYPOINT_ADDRESS(getter_entry);
#endif
1826
      PROFILE(isolate_, GetterCallbackEvent(name, getter_entry));
1827
    }
1828
    Address setter_entry = v8::ToCData<Address>(ai.setter());
1829
    if (setter_entry != 0) {
1830 1831 1832
#if USES_FUNCTION_DESCRIPTORS
      setter_entry = *FUNCTION_ENTRYPOINT_ADDRESS(setter_entry);
#endif
1833
      PROFILE(isolate_, SetterCallbackEvent(name, setter_entry));
1834 1835 1836 1837
    }
  }
}

1838 1839
void Logger::LogAllMaps() {
  DisallowHeapAllocation no_gc;
1840
  Heap* heap = isolate_->heap();
1841
  HeapObjectIterator iterator(heap);
1842 1843
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
1844
    if (!obj.IsMap()) continue;
1845 1846 1847
    Map map = Map::cast(obj);
    MapCreate(map);
    MapDetails(map);
1848 1849
  }
}
1850

1851
static void AddIsolateIdIfNeeded(std::ostream& os,  // NOLINT
1852
                                 Isolate* isolate) {
1853 1854 1855 1856
  if (FLAG_logfile_per_isolate) {
    os << "isolate-" << isolate << "-" << base::OS::GetCurrentProcessId()
       << "-";
  }
1857 1858
}

1859
static void PrepareLogFileName(std::ostream& os,  // NOLINT
1860
                               Isolate* isolate, const char* file_name) {
sejunho's avatar
sejunho committed
1861
  int dir_separator_count = 0;
1862
  for (const char* p = file_name; *p; p++) {
sejunho's avatar
sejunho committed
1863 1864 1865 1866 1867 1868 1869 1870
    if (base::OS::isDirectorySeparator(*p)) dir_separator_count++;
  }

  for (const char* p = file_name; *p; p++) {
    if (dir_separator_count == 0) {
      AddIsolateIdIfNeeded(os, isolate);
      dir_separator_count--;
    }
1871 1872 1873 1874 1875 1876 1877 1878 1879
    if (*p == '%') {
      p++;
      switch (*p) {
        case '\0':
          // If there's a % at the end of the string we back up
          // one character so we can escape the loop properly.
          p--;
          break;
        case 'p':
1880
          os << base::OS::GetCurrentProcessId();
1881
          break;
1882
        case 't':
1883
          // %t expands to the current time in milliseconds.
1884 1885
          os << static_cast<int64_t>(
              V8::GetCurrentPlatform()->CurrentClockTimeMillis());
1886 1887 1888
          break;
        case '%':
          // %% expands (contracts really) to %.
1889
          os << '%';
1890 1891 1892
          break;
        default:
          // All other %'s expand to themselves.
1893
          os << '%' << *p;
1894
          break;
1895
      }
1896
    } else {
sejunho's avatar
sejunho committed
1897
      if (base::OS::isDirectorySeparator(*p)) dir_separator_count--;
1898
      os << *p;
1899 1900 1901 1902
    }
  }
}

1903
bool Logger::SetUp(Isolate* isolate) {
1904 1905 1906
  // Tests and EnsureInitialize() can call this twice in a row. It's harmless.
  if (is_initialized_) return true;
  is_initialized_ = true;
1907

1908
  std::ostringstream log_file_name;
1909
  std::ostringstream source_log_file_name;
1910
  PrepareLogFileName(log_file_name, isolate, FLAG_logfile);
1911
  log_ = std::make_unique<Log>(this, log_file_name.str().c_str());
1912

1913
#if V8_OS_LINUX
1914
  if (FLAG_perf_basic_prof) {
1915
    perf_basic_logger_ = std::make_unique<PerfBasicLogger>(isolate);
1916
    AddCodeEventListener(perf_basic_logger_.get());
1917 1918
  }

1919
  if (FLAG_perf_prof) {
1920
    perf_jit_logger_ = std::make_unique<PerfJitLogger>(isolate);
1921
    AddCodeEventListener(perf_jit_logger_.get());
1922
  }
1923 1924 1925 1926
#else
  static_assert(
      !FLAG_perf_prof,
      "--perf-prof should be statically disabled on non-Linux platforms");
1927 1928 1929
  static_assert(
      !FLAG_perf_basic_prof,
      "--perf-basic-prof should be statically disabled on non-Linux platforms");
1930
#endif
1931

1932
  if (FLAG_ll_prof) {
1933 1934
    ll_logger_ =
        std::make_unique<LowLevelLogger>(isolate, log_file_name.str().c_str());
1935
    AddCodeEventListener(ll_logger_.get());
1936
  }
1937

1938
  ticker_ = std::make_unique<Ticker>(isolate, FLAG_prof_sampling_interval);
1939

1940
  if (Log::InitLogAtStart()) {
1941
    is_logging_ = true;
1942
  }
1943

1944
  timer_.Start();
1945

jkummerow's avatar
jkummerow committed
1946
  if (FLAG_prof_cpp) {
1947
    profiler_ = std::make_unique<Profiler>(isolate);
1948 1949
    is_logging_ = true;
    profiler_->Engage();
1950 1951
  }

1952
  if (is_logging_) {
1953
    AddCodeEventListener(this);
1954 1955
  }

1956 1957 1958
  return true;
}

1959 1960
void Logger::SetCodeEventHandler(uint32_t options,
                                 JitCodeEventHandler event_handler) {
1961
  if (jit_logger_) {
1962 1963
    RemoveCodeEventListener(jit_logger_.get());
    jit_logger_.reset();
1964
  }
1965

1966
  if (event_handler) {
1967 1968 1969
    if (isolate_->wasm_engine() != nullptr) {
      isolate_->wasm_engine()->EnableCodeLogging(isolate_);
    }
1970
    jit_logger_ = std::make_unique<JitLogger>(isolate_, event_handler);
1971
    AddCodeEventListener(jit_logger_.get());
1972 1973 1974 1975 1976
    if (options & kJitCodeEventEnumExisting) {
      HandleScope scope(isolate_);
      LogCodeObjects();
      LogCompiledFunctions();
    }
1977 1978 1979
  }
}

1980
sampler::Sampler* Logger::sampler() { return ticker_.get(); }
1981

1982
void Logger::StopProfilerThread() {
1983
  if (profiler_ != nullptr) {
1984
    profiler_->Disengage();
1985
    profiler_.reset();
1986
  }
1987 1988 1989 1990 1991 1992 1993 1994
}

FILE* Logger::TearDown() {
  if (!is_initialized_) return nullptr;
  is_initialized_ = false;

  // Stop the profiler thread before closing the file.
  StopProfilerThread();
1995

1996
  ticker_.reset();
1997

1998
#if V8_OS_LINUX
1999
  if (perf_basic_logger_) {
2000 2001
    RemoveCodeEventListener(perf_basic_logger_.get());
    perf_basic_logger_.reset();
2002 2003
  }

2004
  if (perf_jit_logger_) {
2005 2006
    RemoveCodeEventListener(perf_jit_logger_.get());
    perf_jit_logger_.reset();
2007
  }
2008
#endif
2009

2010
  if (ll_logger_) {
2011 2012
    RemoveCodeEventListener(ll_logger_.get());
    ll_logger_.reset();
2013 2014
  }

2015
  if (jit_logger_) {
2016 2017
    RemoveCodeEventListener(jit_logger_.get());
    jit_logger_.reset();
2018 2019
  }

2020
  return log_->Close();
2021 2022
}

2023
void ExistingCodeLogger::LogCodeObject(Object object) {
2024 2025
  HandleScope scope(isolate_);
  Handle<AbstractCode> abstract_code(AbstractCode::cast(object), isolate_);
2026 2027
  CodeEventListener::LogEventsAndTags tag = CodeEventListener::STUB_TAG;
  const char* description = "Unknown code from before profiling";
2028
  switch (abstract_code->kind()) {
2029 2030 2031 2032 2033 2034
    case AbstractCode::INTERPRETED_FUNCTION:
    case AbstractCode::OPTIMIZED_FUNCTION:
      return;  // We log this later using LogCompiledFunctions.
    case AbstractCode::BYTECODE_HANDLER:
      return;  // We log it later by walking the dispatch table.
    case AbstractCode::STUB:
2035
      description = "STUB code";
2036 2037 2038 2039 2040 2041 2042
      tag = CodeEventListener::STUB_TAG;
      break;
    case AbstractCode::REGEXP:
      description = "Regular expression code";
      tag = CodeEventListener::REG_EXP_TAG;
      break;
    case AbstractCode::BUILTIN:
2043
      if (Code::cast(object).is_interpreter_trampoline_builtin() &&
2044
          Code::cast(object) !=
2045 2046 2047
              *BUILTIN_CODE(isolate_, InterpreterEntryTrampoline)) {
        return;
      }
2048
      description =
2049
          isolate_->builtins()->name(abstract_code->GetCode().builtin_index());
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
      tag = CodeEventListener::BUILTIN_TAG;
      break;
    case AbstractCode::WASM_FUNCTION:
      description = "A Wasm function";
      tag = CodeEventListener::FUNCTION_TAG;
      break;
    case AbstractCode::JS_TO_WASM_FUNCTION:
      description = "A JavaScript to Wasm adapter";
      tag = CodeEventListener::STUB_TAG;
      break;
2060 2061 2062 2063
    case AbstractCode::JS_TO_JS_FUNCTION:
      description = "A WebAssembly.Function adapter";
      tag = CodeEventListener::STUB_TAG;
      break;
2064 2065 2066 2067
    case AbstractCode::WASM_TO_CAPI_FUNCTION:
      description = "A Wasm to C-API adapter";
      tag = CodeEventListener::STUB_TAG;
      break;
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
    case AbstractCode::WASM_TO_JS_FUNCTION:
      description = "A Wasm to JavaScript adapter";
      tag = CodeEventListener::STUB_TAG;
      break;
    case AbstractCode::WASM_INTERPRETER_ENTRY:
      description = "A Wasm to Interpreter adapter";
      tag = CodeEventListener::STUB_TAG;
      break;
    case AbstractCode::C_WASM_ENTRY:
      description = "A C to Wasm entry stub";
      tag = CodeEventListener::STUB_TAG;
      break;
    case AbstractCode::NUMBER_OF_KINDS:
      UNIMPLEMENTED();
  }
2083
  CALL_CODE_EVENT_HANDLER(CodeCreateEvent(tag, abstract_code, description))
2084 2085 2086 2087
}

void ExistingCodeLogger::LogCodeObjects() {
  Heap* heap = isolate_->heap();
2088
  HeapObjectIterator iterator(heap);
2089
  DisallowHeapAllocation no_gc;
2090 2091
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
2092 2093
    if (obj.IsCode()) LogCodeObject(obj);
    if (obj.IsBytecodeArray()) LogCodeObject(obj);
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
  }
}

void ExistingCodeLogger::LogCompiledFunctions() {
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);
  const int compiled_funcs_count =
      EnumerateCompiledFunctions(heap, nullptr, nullptr);
  ScopedVector<Handle<SharedFunctionInfo>> sfis(compiled_funcs_count);
  ScopedVector<Handle<AbstractCode>> code_objects(compiled_funcs_count);
2104
  EnumerateCompiledFunctions(heap, sfis.begin(), code_objects.begin());
2105 2106 2107 2108

  // During iteration, there can be heap allocation due to
  // GetScriptLineNumber call.
  for (int i = 0; i < compiled_funcs_count; ++i) {
2109
    SharedFunctionInfo::EnsureSourcePositionsAvailable(isolate_, sfis[i]);
2110
    if (sfis[i]->function_data().IsInterpreterData()) {
2111 2112 2113 2114 2115
      LogExistingFunction(
          sfis[i],
          Handle<AbstractCode>(
              AbstractCode::cast(sfis[i]->InterpreterTrampoline()), isolate_),
          CodeEventListener::INTERPRETED_FUNCTION_TAG);
2116
    }
2117 2118 2119 2120 2121
    if (code_objects[i].is_identical_to(BUILTIN_CODE(isolate_, CompileLazy)))
      continue;
    LogExistingFunction(sfis[i], code_objects[i]);
  }

2122 2123
  const int wasm_module_objects_count =
      EnumerateWasmModuleObjects(heap, nullptr);
2124 2125 2126
  ScopedVector<Handle<WasmModuleObject>> module_objects(
      wasm_module_objects_count);
  EnumerateWasmModuleObjects(heap, module_objects.begin());
2127 2128
  for (int i = 0; i < wasm_module_objects_count; ++i) {
    module_objects[i]->native_module()->LogWasmCodes(isolate_);
2129 2130 2131
  }
}

2132 2133 2134
void ExistingCodeLogger::LogExistingFunction(
    Handle<SharedFunctionInfo> shared, Handle<AbstractCode> code,
    CodeEventListener::LogEventsAndTags tag) {
2135
  if (shared->script().IsScript()) {
2136
    Handle<Script> script(Script::cast(shared->script()), isolate_);
2137 2138 2139
    int line_num = Script::GetLineNumber(script, shared->StartPosition()) + 1;
    int column_num =
        Script::GetColumnNumber(script, shared->StartPosition()) + 1;
2140
    if (script->name().IsString()) {
2141
      Handle<String> script_name(String::cast(script->name()), isolate_);
2142 2143
      if (line_num > 0) {
        CALL_CODE_EVENT_HANDLER(
2144 2145
            CodeCreateEvent(Logger::ToNativeByScript(tag, *script), code,
                            shared, script_name, line_num, column_num))
2146 2147 2148 2149
      } else {
        // Can't distinguish eval and script here, so always use Script.
        CALL_CODE_EVENT_HANDLER(CodeCreateEvent(
            Logger::ToNativeByScript(CodeEventListener::SCRIPT_TAG, *script),
2150
            code, shared, script_name))
2151 2152
      }
    } else {
2153
      CALL_CODE_EVENT_HANDLER(CodeCreateEvent(
2154 2155
          Logger::ToNativeByScript(tag, *script), code, shared,
          ReadOnlyRoots(isolate_).empty_string_handle(), line_num, column_num))
2156 2157 2158
    }
  } else if (shared->IsApiFunction()) {
    // API function.
2159
    FunctionTemplateInfo fun_data = shared->get_api_func_data();
2160 2161
    Object raw_call_data = fun_data.call_code();
    if (!raw_call_data.IsUndefined(isolate_)) {
2162
      CallHandlerInfo call_data = CallHandlerInfo::cast(raw_call_data);
2163
      Object callback_obj = call_data.callback();
2164 2165 2166 2167
      Address entry_point = v8::ToCData<Address>(callback_obj);
#if USES_FUNCTION_DESCRIPTORS
      entry_point = *FUNCTION_ENTRYPOINT_ADDRESS(entry_point);
#endif
2168 2169
      CALL_CODE_EVENT_HANDLER(
          CallbackEvent(handle(shared->DebugName(), isolate_), entry_point))
2170 2171 2172 2173 2174 2175
    }
  }
}

#undef CALL_CODE_EVENT_HANDLER

2176 2177
}  // namespace internal
}  // namespace v8