-
Notifications
You must be signed in to change notification settings - Fork 30k
/
log.cc
2194 lines (1899 loc) Β· 71.6 KB
/
log.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 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.
#include "src/log.h"
#include <cstdarg>
#include <memory>
#include <sstream>
#include "src/api-inl.h"
#include "src/bailout-reason.h"
#include "src/base/platform/platform.h"
#include "src/bootstrapper.h"
#include "src/code-stubs.h"
#include "src/counters.h"
#include "src/deoptimizer.h"
#include "src/global-handles.h"
#include "src/instruction-stream.h"
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter.h"
#include "src/libsampler/sampler.h"
#include "src/log-inl.h"
#include "src/macro-assembler.h"
#include "src/objects/api-callbacks.h"
#include "src/perf-jit.h"
#include "src/profiler/tick-sample.h"
#include "src/runtime-profiler.h"
#include "src/source-position-table.h"
#include "src/string-stream.h"
#include "src/tracing/tracing-category-observer.h"
#include "src/unicode-inl.h"
#include "src/vm-state-inl.h"
#include "src/wasm/wasm-code-manager.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/utils.h"
#include "src/version.h"
namespace v8 {
namespace internal {
#define DECLARE_EVENT(ignore1, name) #name,
static const char* kLogEventsNames[CodeEventListener::NUMBER_OF_LOG_EVENTS] = {
LOG_EVENTS_AND_TAGS_LIST(DECLARE_EVENT)};
#undef DECLARE_EVENT
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
}
// The execution should never pass here
UNREACHABLE();
// NOTE(mmarchini): Workaround to fix a compiler failure on GCC 4.9
return v8::CodeEventType::kUnknownType;
}
#define CALL_CODE_EVENT_HANDLER(Call) \
if (listener_) { \
listener_->Call; \
} else { \
PROFILE(isolate_, Call); \
}
static const char* ComputeMarker(SharedFunctionInfo* shared,
AbstractCode* code) {
switch (code->kind()) {
case AbstractCode::INTERPRETED_FUNCTION:
return shared->optimization_disabled() ? "" : "~";
case AbstractCode::OPTIMIZED_FUNCTION:
return "*";
default:
return "";
}
}
static const char* ComputeMarker(const wasm::WasmCode* code) {
switch (code->kind()) {
case wasm::WasmCode::kFunction:
return code->is_liftoff() ? "" : "*";
case wasm::WasmCode::kInterpreterEntry:
return "~";
default:
return "";
}
}
class CodeEventLogger::NameBuffer {
public:
NameBuffer() { Reset(); }
void Reset() {
utf8_pos_ = 0;
}
void Init(CodeEventListener::LogEventsAndTags tag) {
Reset();
AppendBytes(kLogEventsNames[tag]);
AppendByte(':');
}
void AppendName(Name* name) {
if (name->IsString()) {
AppendString(String::cast(name));
} else {
Symbol* symbol = Symbol::cast(name);
AppendBytes("symbol(");
if (!symbol->name()->IsUndefined()) {
AppendBytes("\"");
AppendString(String::cast(symbol->name()));
AppendBytes("\" ");
}
AppendBytes("hash ");
AppendHex(symbol->Hash());
AppendByte(')');
}
}
void AppendString(String* str) {
if (str == nullptr) return;
int length = 0;
std::unique_ptr<char[]> c_str =
str->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL, &length);
AppendBytes(c_str.get(), length);
}
void AppendBytes(const char* bytes, int size) {
size = Min(size, kUtf8BufferSize - utf8_pos_);
MemCopy(utf8_buffer_ + utf8_pos_, bytes, size);
utf8_pos_ += size;
}
void AppendBytes(const char* bytes) {
AppendBytes(bytes, StrLength(bytes));
}
void AppendByte(char c) {
if (utf8_pos_ >= kUtf8BufferSize) return;
utf8_buffer_[utf8_pos_++] = c;
}
void AppendInt(int n) {
int space = kUtf8BufferSize - utf8_pos_;
if (space <= 0) return;
Vector<char> buffer(utf8_buffer_ + utf8_pos_, space);
int size = SNPrintF(buffer, "%d", n);
if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) {
utf8_pos_ += size;
}
}
void AppendHex(uint32_t n) {
int space = kUtf8BufferSize - utf8_pos_;
if (space <= 0) return;
Vector<char> buffer(utf8_buffer_ + utf8_pos_, space);
int size = SNPrintF(buffer, "%x", n);
if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) {
utf8_pos_ += size;
}
}
const char* get() { return utf8_buffer_; }
int size() const { return utf8_pos_; }
private:
static const int kUtf8BufferSize = 512;
static const int kUtf16BufferSize = kUtf8BufferSize;
int utf8_pos_;
char utf8_buffer_[kUtf8BufferSize];
};
CodeEventLogger::CodeEventLogger(Isolate* isolate)
: isolate_(isolate), name_buffer_(new NameBuffer) {}
CodeEventLogger::~CodeEventLogger() { delete name_buffer_; }
void CodeEventLogger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, const char* comment) {
name_buffer_->Init(tag);
name_buffer_->AppendBytes(comment);
LogRecordedBuffer(code, nullptr, name_buffer_->get(), name_buffer_->size());
}
void CodeEventLogger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, Name* name) {
name_buffer_->Init(tag);
name_buffer_->AppendName(name);
LogRecordedBuffer(code, nullptr, name_buffer_->get(), name_buffer_->size());
}
void CodeEventLogger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code,
SharedFunctionInfo* shared, Name* name) {
name_buffer_->Init(tag);
name_buffer_->AppendBytes(ComputeMarker(shared, code));
name_buffer_->AppendName(name);
LogRecordedBuffer(code, shared, name_buffer_->get(), name_buffer_->size());
}
void CodeEventLogger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code,
SharedFunctionInfo* shared, Name* source,
int line, int column) {
name_buffer_->Init(tag);
name_buffer_->AppendBytes(ComputeMarker(shared, code));
name_buffer_->AppendString(shared->DebugName());
name_buffer_->AppendByte(' ');
if (source->IsString()) {
name_buffer_->AppendString(String::cast(source));
} else {
name_buffer_->AppendBytes("symbol(hash ");
name_buffer_->AppendHex(Name::cast(source)->Hash());
name_buffer_->AppendByte(')');
}
name_buffer_->AppendByte(':');
name_buffer_->AppendInt(line);
LogRecordedBuffer(code, shared, name_buffer_->get(), name_buffer_->size());
}
void CodeEventLogger::CodeCreateEvent(LogEventsAndTags tag,
const wasm::WasmCode* code,
wasm::WasmName name) {
name_buffer_->Init(tag);
if (name.is_empty()) {
name_buffer_->AppendBytes("<wasm-unknown>");
} else {
name_buffer_->AppendBytes(name.start(), name.length());
}
name_buffer_->AppendByte('-');
if (code->IsAnonymous()) {
name_buffer_->AppendBytes("<anonymous>");
} else {
name_buffer_->AppendInt(code->index());
}
LogRecordedBuffer(code, name_buffer_->get(), name_buffer_->size());
}
void CodeEventLogger::RegExpCodeCreateEvent(AbstractCode* code,
String* source) {
name_buffer_->Init(CodeEventListener::REG_EXP_TAG);
name_buffer_->AppendString(source);
LogRecordedBuffer(code, nullptr, name_buffer_->get(), name_buffer_->size());
}
// Linux perf tool logging support
class PerfBasicLogger : public CodeEventLogger {
public:
explicit PerfBasicLogger(Isolate* isolate);
~PerfBasicLogger() override;
void CodeMoveEvent(AbstractCode* from, AbstractCode* to) override {}
void CodeDisableOptEvent(AbstractCode* code,
SharedFunctionInfo* shared) override {}
private:
void LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo* shared,
const char* name, int length) override;
void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
int length) override;
void WriteLogRecordedBuffer(uintptr_t address, int size, const char* name,
int name_length);
// 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;
PerfBasicLogger::PerfBasicLogger(Isolate* isolate)
: CodeEventLogger(isolate), perf_output_handle_(nullptr) {
// Open the perf JIT dump file.
int bufferSize = sizeof(kFilenameFormatString) + kFilenameBufferPadding;
ScopedVector<char> perf_dump_name(bufferSize);
int size = SNPrintF(
perf_dump_name,
kFilenameFormatString,
base::OS::GetCurrentProcessId());
CHECK_NE(size, -1);
perf_output_handle_ =
base::OS::FOpen(perf_dump_name.start(), base::OS::LogFileOpenMode);
CHECK_NOT_NULL(perf_output_handle_);
setvbuf(perf_output_handle_, nullptr, _IOLBF, 0);
}
PerfBasicLogger::~PerfBasicLogger() {
fclose(perf_output_handle_);
perf_output_handle_ = nullptr;
}
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);
}
void PerfBasicLogger::LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo*,
const char* name, int length) {
if (FLAG_perf_basic_prof_only_functions &&
(code->kind() != AbstractCode::INTERPRETED_FUNCTION &&
code->kind() != AbstractCode::BUILTIN &&
code->kind() != AbstractCode::OPTIMIZED_FUNCTION)) {
return;
}
WriteLogRecordedBuffer(static_cast<uintptr_t>(code->InstructionStart()),
code->InstructionSize(), name, length);
}
void PerfBasicLogger::LogRecordedBuffer(const wasm::WasmCode* code,
const char* name, int length) {
WriteLogRecordedBuffer(static_cast<uintptr_t>(code->instruction_start()),
code->instructions().length(), name, length);
}
// 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();
}
}
void ExternalCodeEventListener::StopListening() {
if (!is_listening_) {
return;
}
isolate_->code_event_dispatcher()->RemoveListener(this);
is_listening_ = false;
}
void ExternalCodeEventListener::CodeCreateEvent(
CodeEventListener::LogEventsAndTags tag, AbstractCode* code,
const char* comment) {
CodeEvent code_event;
code_event.code_start_address =
static_cast<uintptr_t>(code->InstructionStart());
code_event.code_size = static_cast<size_t>(code->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 = GetCodeEventTypeForTag(tag);
code_event.comment = comment;
code_event_handler_->Handle(reinterpret_cast<v8::CodeEvent*>(&code_event));
}
void ExternalCodeEventListener::CodeCreateEvent(
CodeEventListener::LogEventsAndTags tag, AbstractCode* code, Name* name) {
Handle<String> name_string =
Name::ToFunctionName(isolate_, Handle<Name>(name, isolate_))
.ToHandleChecked();
CodeEvent code_event;
code_event.code_start_address =
static_cast<uintptr_t>(code->InstructionStart());
code_event.code_size = static_cast<size_t>(code->InstructionSize());
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(
CodeEventListener::LogEventsAndTags tag, AbstractCode* code,
SharedFunctionInfo* shared, Name* name) {
Handle<String> name_string =
Name::ToFunctionName(isolate_, Handle<Name>(name, isolate_))
.ToHandleChecked();
CodeEvent code_event;
code_event.code_start_address =
static_cast<uintptr_t>(code->InstructionStart());
code_event.code_size = static_cast<size_t>(code->InstructionSize());
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(
CodeEventListener::LogEventsAndTags tag, AbstractCode* code,
SharedFunctionInfo* shared, Name* source, int line, int column) {
Handle<String> name_string =
Name::ToFunctionName(isolate_, Handle<Name>(shared->Name(), isolate_))
.ToHandleChecked();
Handle<String> source_string =
Name::ToFunctionName(isolate_, Handle<Name>(source, isolate_))
.ToHandleChecked();
CodeEvent code_event;
code_event.code_start_address =
static_cast<uintptr_t>(code->InstructionStart());
code_event.code_size = static_cast<size_t>(code->InstructionSize());
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
}
void ExternalCodeEventListener::RegExpCodeCreateEvent(AbstractCode* code,
String* source) {
CodeEvent code_event;
code_event.code_start_address =
static_cast<uintptr_t>(code->InstructionStart());
code_event.code_size = static_cast<size_t>(code->InstructionSize());
code_event.function_name = Handle<String>(source, isolate_);
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));
}
// Low-level logging support.
class LowLevelLogger : public CodeEventLogger {
public:
LowLevelLogger(Isolate* isolate, const char* file_name);
~LowLevelLogger() override;
void CodeMoveEvent(AbstractCode* from, AbstractCode* to) override;
void CodeDisableOptEvent(AbstractCode* code,
SharedFunctionInfo* shared) override {}
void SnapshotPositionEvent(HeapObject* obj, int pos);
void CodeMovingGCEvent() override;
private:
void LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo* shared,
const char* name, int length) override;
void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
int length) override;
// Low-level profiling event structures.
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";
LowLevelLogger::LowLevelLogger(Isolate* isolate, const char* name)
: CodeEventLogger(isolate), ll_output_handle_(nullptr) {
// Open the low-level log file.
size_t len = strlen(name);
ScopedVector<char> ll_name(static_cast<int>(len + sizeof(kLogExt)));
MemCopy(ll_name.start(), name, len);
MemCopy(ll_name.start() + len, kLogExt, sizeof(kLogExt));
ll_output_handle_ =
base::OS::FOpen(ll_name.start(), base::OS::LogFileOpenMode);
setvbuf(ll_output_handle_, nullptr, _IOLBF, 0);
LogCodeInfo();
}
LowLevelLogger::~LowLevelLogger() {
fclose(ll_output_handle_);
ll_output_handle_ = nullptr;
}
void LowLevelLogger::LogCodeInfo() {
#if V8_TARGET_ARCH_IA32
const char arch[] = "ia32";
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT
const char arch[] = "x64";
#elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT
const char arch[] = "x32";
#elif V8_TARGET_ARCH_ARM
const char arch[] = "arm";
#elif V8_TARGET_ARCH_PPC
const char arch[] = "ppc";
#elif V8_TARGET_ARCH_MIPS
const char arch[] = "mips";
#elif V8_TARGET_ARCH_ARM64
const char arch[] = "arm64";
#elif V8_TARGET_ARCH_S390
const char arch[] = "s390";
#else
const char arch[] = "unknown";
#endif
LogWriteBytes(arch, sizeof(arch));
}
void LowLevelLogger::LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo*,
const char* name, int length) {
CodeCreateStruct event;
event.name_size = length;
event.code_address = code->InstructionStart();
event.code_size = code->InstructionSize();
LogWriteStruct(event);
LogWriteBytes(name, length);
LogWriteBytes(reinterpret_cast<const char*>(code->InstructionStart()),
code->InstructionSize());
}
void LowLevelLogger::LogRecordedBuffer(const wasm::WasmCode* code,
const char* name, int length) {
CodeCreateStruct event;
event.name_size = length;
event.code_address = code->instruction_start();
event.code_size = code->instructions().length();
LogWriteStruct(event);
LogWriteBytes(name, length);
LogWriteBytes(reinterpret_cast<const char*>(code->instruction_start()),
code->instructions().length());
}
void LowLevelLogger::CodeMoveEvent(AbstractCode* from, AbstractCode* to) {
CodeMoveStruct event;
event.from_address = from->InstructionStart();
event.to_address = to->InstructionStart();
LogWriteStruct(event);
}
void LowLevelLogger::LogWriteBytes(const char* bytes, int size) {
size_t rv = fwrite(bytes, 1, size, ll_output_handle_);
DCHECK(static_cast<size_t>(size) == rv);
USE(rv);
}
void LowLevelLogger::CodeMovingGCEvent() {
const char tag = kCodeMovingGCTag;
LogWriteBytes(&tag, sizeof(tag));
}
class JitLogger : public CodeEventLogger {
public:
JitLogger(Isolate* isolate, JitCodeEventHandler code_event_handler);
void CodeMoveEvent(AbstractCode* from, AbstractCode* to) override;
void CodeDisableOptEvent(AbstractCode* code,
SharedFunctionInfo* shared) override {}
void AddCodeLinePosInfoEvent(void* jit_handler_data, int pc_offset,
int position,
JitCodeEvent::PositionType position_type);
void* StartCodePosInfoEvent();
void EndCodePosInfoEvent(Address start_address, void* jit_handler_data);
private:
void LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo* shared,
const char* name, int length) override;
void LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
int length) override;
JitCodeEventHandler code_event_handler_;
base::Mutex logger_mutex_;
};
JitLogger::JitLogger(Isolate* isolate, JitCodeEventHandler code_event_handler)
: CodeEventLogger(isolate), code_event_handler_(code_event_handler) {}
void JitLogger::LogRecordedBuffer(AbstractCode* code,
SharedFunctionInfo* shared, const char* name,
int length) {
JitCodeEvent event;
memset(static_cast<void*>(&event), 0, sizeof(event));
event.type = JitCodeEvent::CODE_ADDED;
event.code_start = reinterpret_cast<void*>(code->InstructionStart());
event.code_type =
code->IsCode() ? JitCodeEvent::JIT_CODE : JitCodeEvent::BYTE_CODE;
event.code_len = code->InstructionSize();
Handle<SharedFunctionInfo> shared_function_handle;
if (shared && shared->script()->IsScript()) {
shared_function_handle =
Handle<SharedFunctionInfo>(shared, shared->GetIsolate());
}
event.script = ToApiHandle<v8::UnboundScript>(shared_function_handle);
event.name.str = name;
event.name.len = length;
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
}
void JitLogger::LogRecordedBuffer(const wasm::WasmCode* code, const char* name,
int length) {
JitCodeEvent event;
memset(static_cast<void*>(&event), 0, sizeof(event));
event.type = JitCodeEvent::CODE_ADDED;
event.code_type = JitCodeEvent::JIT_CODE;
event.code_start = code->instructions().start();
event.code_len = code->instructions().length();
event.name.str = name;
event.name.len = length;
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
}
void JitLogger::CodeMoveEvent(AbstractCode* from, AbstractCode* to) {
base::LockGuard<base::Mutex> guard(&logger_mutex_);
JitCodeEvent event;
event.type = JitCodeEvent::CODE_MOVED;
event.code_type =
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());
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
}
void JitLogger::AddCodeLinePosInfoEvent(
void* jit_handler_data,
int pc_offset,
int position,
JitCodeEvent::PositionType position_type) {
JitCodeEvent event;
memset(static_cast<void*>(&event), 0, sizeof(event));
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;
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
}
void* JitLogger::StartCodePosInfoEvent() {
JitCodeEvent event;
memset(static_cast<void*>(&event), 0, sizeof(event));
event.type = JitCodeEvent::CODE_START_LINE_INFO_RECORDING;
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
return event.user_data;
}
void JitLogger::EndCodePosInfoEvent(Address start_address,
void* jit_handler_data) {
JitCodeEvent event;
memset(static_cast<void*>(&event), 0, sizeof(event));
event.type = JitCodeEvent::CODE_END_LINE_INFO_RECORDING;
event.code_start = reinterpret_cast<void*>(start_address);
event.user_data = jit_handler_data;
event.isolate = reinterpret_cast<v8::Isolate*>(isolate_);
code_event_handler_(&event);
}
// 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;
SamplingThread(sampler::Sampler* sampler, int interval_microseconds)
: base::Thread(
base::Thread::Options("SamplingThread", kSamplingThreadStackSize)),
sampler_(sampler),
interval_microseconds_(interval_microseconds) {}
void Run() override {
while (sampler_->IsProfiling()) {
sampler_->DoSample();
base::OS::Sleep(
base::TimeDelta::FromMicroseconds(interval_microseconds_));
}
}
private:
sampler::Sampler* sampler_;
const int interval_microseconds_;
};
// 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.
//
class Profiler: public base::Thread {
public:
explicit Profiler(Isolate* isolate);
void Engage();
void Disengage();
// Inserts collected profiling data into buffer.
void Insert(v8::TickSample* sample) {
if (paused_)
return;
if (Succ(head_) == static_cast<int>(base::Relaxed_Load(&tail_))) {
overflow_ = true;
} else {
buffer_[head_] = *sample;
head_ = Succ(head_);
buffer_semaphore_.Signal(); // Tell we have an element.
}
}
void Run() override;
// Pause and Resume TickSample data collection.
void Pause() { paused_ = true; }
void Resume() { paused_ = false; }
private:
// Waits for a signal and removes profiling data.
bool Remove(v8::TickSample* sample) {
buffer_semaphore_.Wait(); // Wait for an element.
*sample = buffer_[base::Relaxed_Load(&tail_)];
bool result = overflow_;
base::Relaxed_Store(
&tail_, static_cast<base::Atomic32>(Succ(base::Relaxed_Load(&tail_))));
overflow_ = false;
return result;
}
// Returns the next index in the cyclic buffer.
int Succ(int index) { return (index + 1) % kBufferSize; }
Isolate* isolate_;
// Cyclic buffer for communicating profiling samples
// between the signal handler and the worker thread.
static const int kBufferSize = 128;
v8::TickSample buffer_[kBufferSize]; // Buffer storage.
int head_; // Index to the buffer head.
base::Atomic32 tail_; // Index to the buffer tail.
bool overflow_; // Tell whether a buffer overflow has occurred.
// Semaphore used for buffer synchronization.
base::Semaphore buffer_semaphore_;
// Tells whether profiler is engaged, that is, processing thread is stated.
bool engaged_;
// Tells whether worker thread should continue running.
base::Atomic32 running_;
// Tells whether we are currently recording tick samples.
bool paused_;
};
//
// Ticker used to provide ticks to the profiler and the sliding state
// window.
//
class Ticker: public sampler::Sampler {
public:
Ticker(Isolate* isolate, int interval_microseconds)
: sampler::Sampler(reinterpret_cast<v8::Isolate*>(isolate)),
profiler_(nullptr),
sampling_thread_(new SamplingThread(this, interval_microseconds)) {}
~Ticker() override {
if (IsActive()) Stop();
delete sampling_thread_;
}
void SetProfiler(Profiler* profiler) {
DCHECK_NULL(profiler_);
profiler_ = profiler;
IncreaseProfilingDepth();
if (!IsActive()) Start();
sampling_thread_->StartSynchronously();
}
void ClearProfiler() {
profiler_ = nullptr;
if (IsActive()) Stop();
DecreaseProfilingDepth();
sampling_thread_->Join();
}
void SampleStack(const v8::RegisterState& state) override {
if (!profiler_) return;
Isolate* isolate = reinterpret_cast<Isolate*>(this->isolate());
TickSample sample;
sample.Init(isolate, state, TickSample::kIncludeCEntryFrame, true);
profiler_->Insert(&sample);
}
private:
Profiler* profiler_;
SamplingThread* sampling_thread_;
};
//
// Profiler implementation when invoking with --prof.
//
Profiler::Profiler(Isolate* isolate)
: base::Thread(Options("v8:Profiler")),
isolate_(isolate),
head_(0),
overflow_(false),
buffer_semaphore_(0),
engaged_(false),
paused_(false) {
base::Relaxed_Store(&tail_, 0);
base::Relaxed_Store(&running_, 0);
}
void Profiler::Engage() {
if (engaged_) return;
engaged_ = true;
std::vector<base::OS::SharedLibraryAddress> addresses =
base::OS::GetSharedLibraryAddresses();
for (const auto& address : addresses) {
LOG(isolate_, SharedLibraryEvent(address.library_path, address.start,
address.end, address.aslr_slide));
}
// Start thread processing the profiler buffer.
base::Relaxed_Store(&running_, 1);
Start();
// Register to get ticks.
Logger* logger = isolate_->logger();
logger->ticker_->SetProfiler(this);
logger->ProfilerBeginEvent();
}
void Profiler::Disengage() {
if (!engaged_) return;
// Stop receiving ticks.
isolate_->logger()->ticker_->ClearProfiler();
// Terminate the worker thread by setting running_ to false,
// inserting a fake element in the queue and then wait for
// the thread to terminate.
base::Relaxed_Store(&running_, 0);
v8::TickSample sample;
// Reset 'paused_' flag, otherwise semaphore may not be signalled.
Resume();
Insert(&sample);
Join();
LOG(isolate_, UncheckedStringEvent("profiler", "end"));
}
void Profiler::Run() {
v8::TickSample sample;
bool overflow = Remove(&sample);
while (base::Relaxed_Load(&running_)) {
LOG(isolate_, TickEvent(&sample, overflow));
overflow = Remove(&sample);
}
}
//
// Logger class implementation.
//
Logger::Logger(Isolate* isolate)
: isolate_(isolate),
ticker_(nullptr),
profiler_(nullptr),
log_events_(nullptr),
is_logging_(false),
log_(nullptr),
perf_basic_logger_(nullptr),
perf_jit_logger_(nullptr),
ll_logger_(nullptr),
jit_logger_(nullptr),
is_initialized_(false),
existing_code_logger_(isolate) {}
Logger::~Logger() {
delete log_;
}
void Logger::AddCodeEventListener(CodeEventListener* listener) {
bool result = isolate_->code_event_dispatcher()->AddListener(listener);
CHECK(result);
}
void Logger::RemoveCodeEventListener(CodeEventListener* listener) {
isolate_->code_event_dispatcher()->RemoveListener(listener);
}
void Logger::ProfilerBeginEvent() {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg << "profiler" << kNext << "begin" << kNext << FLAG_prof_sampling_interval;
msg.WriteToLogFile();
}
void Logger::StringEvent(const char* name, const char* value) {
if (FLAG_log) UncheckedStringEvent(name, value);
}
void Logger::UncheckedStringEvent(const char* name, const char* value) {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg << name << kNext << value;
msg.WriteToLogFile();