/
profiler.cpp
1804 lines (1548 loc) · 58.8 KB
/
profiler.cpp
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 The async-profiler authors
* SPDX-License-Identifier: Apache-2.0
*/
#include <algorithm>
#include <dlfcn.h>
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include "profiler.h"
#include "perfEvents.h"
#include "ctimer.h"
#include "allocTracer.h"
#include "lockTracer.h"
#include "wallClock.h"
#include "j9ObjectSampler.h"
#include "j9StackTraces.h"
#include "j9WallClock.h"
#include "instrument.h"
#include "itimer.h"
#include "dwarf.h"
#include "flameGraph.h"
#include "flightRecorder.h"
#include "fdtransferClient.h"
#include "frameName.h"
#include "os.h"
#include "safeAccess.h"
#include "stackFrame.h"
#include "stackWalker.h"
#include "symbols.h"
#include "tsc.h"
#include "vmStructs.h"
// The instance is not deleted on purpose, since profiler structures
// can be still accessed concurrently during VM termination
Profiler* const Profiler::_instance = new Profiler();
static SigAction orig_trapHandler = NULL;
static SigAction orig_segvHandler = NULL;
static Engine noop_engine;
static PerfEvents perf_events;
static AllocTracer alloc_tracer;
static LockTracer lock_tracer;
static ObjectSampler object_sampler;
static J9ObjectSampler j9_object_sampler;
static WallClock wall_clock;
static J9WallClock j9_wall_clock;
static CTimer ctimer;
static ITimer itimer;
static Instrument instrument;
static ProfilingWindow profiling_window;
// The same constants are used in JfrSync
enum EventMask {
EM_CPU = 1,
EM_ALLOC = 2,
EM_LOCK = 4,
EM_WALL = 8
};
struct MethodSample {
u64 samples;
u64 counter;
void add(u64 add_samples, u64 add_counter) {
samples += add_samples;
counter += add_counter;
}
};
typedef std::pair<std::string, MethodSample> NamedMethodSample;
static bool sortByCounter(const NamedMethodSample& a, const NamedMethodSample& b) {
return a.second.counter > b.second.counter;
}
static inline bool isVTableStub(const char* name) {
return name[0] && strcmp(name + 1, "table stub") == 0;
}
static inline int makeFrame(ASGCT_CallFrame* frames, jint type, jmethodID id) {
frames[0].bci = type;
frames[0].method_id = id;
return 1;
}
static inline int makeFrame(ASGCT_CallFrame* frames, jint type, uintptr_t id) {
return makeFrame(frames, type, (jmethodID)id);
}
static inline int makeFrame(ASGCT_CallFrame* frames, jint type, const char* id) {
return makeFrame(frames, type, (jmethodID)id);
}
// Avoid syscall when possible
static inline int fastThreadId() {
VMThread* vm_thread;
if (VMStructs::hasNativeThreadId() && (vm_thread = VMThread::current()) != NULL) {
int thread_id = vm_thread->osThreadId();
if (thread_id > 0) {
return thread_id;
}
}
return OS::threadId();
}
void Profiler::addJavaMethod(const void* address, int length, jmethodID method) {
CodeHeap::updateBounds(address, (const char*)address + length);
}
void Profiler::addRuntimeStub(const void* address, int length, const char* name) {
_stubs_lock.lock();
_runtime_stubs.add(address, length, name, true);
_stubs_lock.unlock();
if (strcmp(name, "call_stub") == 0) {
_call_stub_begin = address;
_call_stub_end = (const char*)address + length;
}
CodeHeap::updateBounds(address, (const char*)address + length);
}
void Profiler::onThreadStart(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) {
if (_thread_filter.enabled()) {
_thread_filter.remove(OS::threadId());
}
updateThreadName(jvmti, jni, thread);
}
void Profiler::onThreadEnd(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) {
if (_thread_filter.enabled()) {
_thread_filter.remove(OS::threadId());
}
updateThreadName(jvmti, jni, thread);
}
void Profiler::onGarbageCollectionFinish() {
// Called during GC pause, do not use JNI
__sync_fetch_and_add(&_gc_id, 1);
}
const char* Profiler::asgctError(int code) {
switch (code) {
case ticks_no_Java_frame:
case ticks_unknown_not_Java:
// Not in Java context at all; this is not an error
return NULL;
case ticks_thread_exit:
// The last Java frame has been popped off, only native frames left
return NULL;
case ticks_GC_active:
return "GC_active";
case ticks_unknown_Java:
return "unknown_Java";
case ticks_not_walkable_Java:
return "not_walkable_Java";
case ticks_not_walkable_not_Java:
return "not_walkable_not_Java";
case ticks_deopt:
return "deoptimization";
case ticks_safepoint:
return "safepoint";
case ticks_skipped:
return "skipped";
case ticks_unknown_state:
// Zing sometimes returns it
return "unknown_state";
default:
// Should not happen
return "unexpected_state";
}
}
inline u32 Profiler::getLockIndex(int tid) {
u32 lock_index = tid;
lock_index ^= lock_index >> 8;
lock_index ^= lock_index >> 4;
return lock_index % CONCURRENCY_LEVEL;
}
void Profiler::updateSymbols(bool kernel_symbols) {
Symbols::parseLibraries(&_native_libs, kernel_symbols);
}
void Profiler::mangle(const char* name, char* buf, size_t size) {
char* buf_end = buf + size;
strcpy(buf, "_ZN");
buf += 3;
const char* c;
while ((c = strstr(name, "::")) != NULL && buf + (c - name) + 4 < buf_end) {
buf += snprintf(buf, buf_end - buf, "%d", (int)(c - name));
memcpy(buf, name, c - name);
buf += c - name;
name = c + 2;
}
if (buf < buf_end) {
snprintf(buf, buf_end - buf, "%d%sE*", (int)strlen(name), name);
}
buf_end[-1] = 0;
}
const void* Profiler::resolveSymbol(const char* name) {
char mangled_name[256];
if (strstr(name, "::") != NULL) {
mangle(name, mangled_name, sizeof(mangled_name));
name = mangled_name;
}
size_t len = strlen(name);
int native_lib_count = _native_libs.count();
if (len > 0 && name[len - 1] == '*') {
for (int i = 0; i < native_lib_count; i++) {
const void* address = _native_libs[i]->findSymbolByPrefix(name, len - 1);
if (address != NULL) {
return address;
}
}
} else {
for (int i = 0; i < native_lib_count; i++) {
const void* address = _native_libs[i]->findSymbol(name);
if (address != NULL) {
return address;
}
}
}
return NULL;
}
// For BCI_NATIVE_FRAME, library index is encoded ahead of the symbol name
const char* Profiler::getLibraryName(const char* native_symbol) {
short lib_index = NativeFunc::libIndex(native_symbol);
if (lib_index >= 0 && lib_index < _native_libs.count()) {
const char* s = _native_libs[lib_index]->name();
if (s != NULL) {
const char* p = strrchr(s, '/');
return p != NULL ? p + 1 : s;
}
}
return NULL;
}
CodeCache* Profiler::findJvmLibrary(const char* lib_name) {
return VM::isOpenJ9() ? findLibraryByName(lib_name) : VMStructs::libjvm();
}
CodeCache* Profiler::findLibraryByName(const char* lib_name) {
const size_t lib_name_len = strlen(lib_name);
const int native_lib_count = _native_libs.count();
for (int i = 0; i < native_lib_count; i++) {
const char* s = _native_libs[i]->name();
if (s != NULL) {
const char* p = strrchr(s, '/');
if (p != NULL && strncmp(p + 1, lib_name, lib_name_len) == 0) {
return _native_libs[i];
}
}
}
return NULL;
}
CodeCache* Profiler::findLibraryByAddress(const void* address) {
const int native_lib_count = _native_libs.count();
for (int i = 0; i < native_lib_count; i++) {
if (_native_libs[i]->contains(address)) {
return _native_libs[i];
}
}
return NULL;
}
const char* Profiler::findNativeMethod(const void* address) {
CodeCache* lib = findLibraryByAddress(address);
return lib == NULL ? NULL : lib->binarySearch(address);
}
CodeBlob* Profiler::findRuntimeStub(const void* address) {
return _runtime_stubs.findBlobByAddress(address);
}
bool Profiler::isAddressInCode(const void* pc) {
if (CodeHeap::contains(pc)) {
return CodeHeap::findNMethod(pc) != NULL && !(pc >= _call_stub_begin && pc < _call_stub_end);
} else {
return findLibraryByAddress(pc) != NULL;
}
}
jmethodID Profiler::getCurrentCompileTask() {
VMThread* vm_thread = VMThread::current();
if (vm_thread != NULL) {
VMMethod* method = vm_thread->compiledMethod();
if (method != NULL) {
return method->id();
}
}
return NULL;
}
int Profiler::getNativeTrace(void* ucontext, ASGCT_CallFrame* frames, EventType event_type, int tid, StackContext* java_ctx) {
const void* callchain[MAX_NATIVE_FRAMES];
int native_frames;
if (_cstack == CSTACK_NO || (event_type > EXECUTION_SAMPLE && _cstack == CSTACK_DEFAULT)) {
return 0;
}
// Use PerfEvents stack walker for execution samples, or basic stack walker for other events
if (event_type == PERF_SAMPLE) {
native_frames = PerfEvents::walk(tid, ucontext, callchain, MAX_NATIVE_FRAMES, java_ctx);
} else if (_cstack == CSTACK_VM) {
return 0;
} else if (_cstack == CSTACK_DWARF) {
native_frames = StackWalker::walkDwarf(ucontext, callchain, MAX_NATIVE_FRAMES, java_ctx);
} else {
native_frames = StackWalker::walkFP(ucontext, callchain, MAX_NATIVE_FRAMES, java_ctx);
}
return convertNativeTrace(native_frames, callchain, frames);
}
int Profiler::convertNativeTrace(int native_frames, const void** callchain, ASGCT_CallFrame* frames) {
int depth = 0;
jmethodID prev_method = NULL;
for (int i = 0; i < native_frames; i++) {
const char* current_method_name = findNativeMethod(callchain[i]);
char mark;
if (current_method_name != NULL && (mark = NativeFunc::mark(current_method_name)) != 0) {
if (mark == MARK_INTERPRETER) {
// This is C++ interpreter frame, this and later frames should be reported
// as Java frames returned by AGCT. Terminate the scan here.
return depth;
} else if (mark == MARK_COMPILER_ENTRY && _features.comp_task) {
// Insert current compile task as a pseudo Java frame
jmethodID compile_task = getCurrentCompileTask();
if (compile_task != NULL) {
frames[depth].bci = 0;
frames[depth].method_id = compile_task;
depth++;
}
}
}
jmethodID current_method = (jmethodID)current_method_name;
if (current_method == prev_method && _cstack == CSTACK_LBR) {
// Skip duplicates in LBR stack, where branch_stack[N].from == branch_stack[N+1].to
prev_method = NULL;
} else {
frames[depth].bci = BCI_NATIVE_FRAME;
frames[depth].method_id = prev_method = current_method;
depth++;
}
}
return depth;
}
int Profiler::getJavaTraceAsync(void* ucontext, ASGCT_CallFrame* frames, int max_depth, StackContext* java_ctx) {
// Workaround for JDK-8132510: it's not safe to call GetEnv() inside a signal handler
// since JDK 9, so we do it only for threads already registered in ThreadLocalStorage
VMThread* vm_thread = VMThread::current();
if (vm_thread == NULL) {
return 0;
}
JNIEnv* jni = VM::jni();
if (jni == NULL) {
// Not a Java thread
return 0;
}
StackFrame frame(ucontext);
uintptr_t saved_pc, saved_sp, saved_fp;
if (ucontext != NULL) {
saved_pc = frame.pc();
saved_sp = frame.sp();
saved_fp = frame.fp();
}
if (_features.unwind_native && vm_thread->inJava()) {
if (saved_pc >= (uintptr_t)_call_stub_begin && saved_pc < (uintptr_t)_call_stub_end) {
// call_stub is unsafe to walk
frames->bci = BCI_ERROR;
frames->method_id = (jmethodID)"call_stub";
return 1;
}
if (DWARF_SUPPORTED && java_ctx->sp != 0) {
// If a thread is in Java state, unwind manually to the last known Java frame,
// since JVM does not always correctly unwind native frames
frame.restore((uintptr_t)java_ctx->pc, java_ctx->sp, java_ctx->fp);
}
}
JitWriteProtection jit(false);
ASGCT_CallTrace trace = {jni, 0, frames};
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
if (trace.num_frames > 0) {
frame.restore(saved_pc, saved_sp, saved_fp);
return trace.num_frames;
}
if ((trace.num_frames == ticks_unknown_Java || trace.num_frames == ticks_not_walkable_Java) && _features.unknown_java && ucontext != NULL) {
CodeBlob* stub = NULL;
_stubs_lock.lockShared();
if (_runtime_stubs.contains((const void*)frame.pc())) {
stub = findRuntimeStub((const void*)frame.pc());
}
_stubs_lock.unlockShared();
if (stub != NULL) {
if (_cstack != CSTACK_NO) {
if (_features.vtable_target && isVTableStub(stub->_name)) {
uintptr_t receiver = frame.jarg0();
if (receiver != 0) {
VMSymbol* symbol = VMKlass::fromOop(receiver)->name();
u32 class_id = classMap()->lookup(symbol->body(), symbol->length());
max_depth -= makeFrame(trace.frames++, BCI_ALLOC, class_id);
}
}
max_depth -= makeFrame(trace.frames++, BCI_NATIVE_FRAME, stub->_name);
}
if (_features.unwind_stub && frame.unwindStub((instruction_t*)stub->_start, stub->_name)
&& isAddressInCode((const void*)frame.pc())) {
java_ctx->pc = (const void*)frame.pc();
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
} else if (VMStructs::hasMethodStructs()) {
NMethod* nmethod = CodeHeap::findNMethod((const void*)frame.pc());
if (nmethod != NULL && nmethod->isNMethod() && nmethod->isAlive()) {
VMMethod* method = nmethod->method();
if (method != NULL) {
jmethodID method_id = method->id();
if (method_id != NULL) {
max_depth -= makeFrame(trace.frames++, 0, method_id);
}
if (_features.unwind_comp && frame.unwindCompiled(nmethod)
&& isAddressInCode((const void*)frame.pc())) {
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
if (_features.probe_sp && trace.num_frames < 0) {
if (method_id != NULL) {
trace.frames--;
}
for (int i = 0; trace.num_frames < 0 && i < PROBE_SP_LIMIT; i++) {
frame.sp() += sizeof(void*);
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
}
}
} else if (nmethod != NULL) {
if (_cstack != CSTACK_NO) {
max_depth -= makeFrame(trace.frames++, BCI_NATIVE_FRAME, nmethod->name());
}
if (_features.unwind_stub && frame.unwindStub(NULL, nmethod->name())
&& isAddressInCode((const void*)frame.pc())) {
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
}
}
} else if (trace.num_frames == ticks_unknown_not_Java && _features.java_anchor) {
uintptr_t& sp = vm_thread->lastJavaSP();
uintptr_t& pc = vm_thread->lastJavaPC();
if (sp != 0 && pc == 0) {
// We have the last Java frame anchor, but it is not marked as walkable.
// Make it walkable here
pc = ((uintptr_t*)sp)[-1];
NMethod* m = CodeHeap::findNMethod((const void*)pc);
if (m != NULL) {
// AGCT fails if the last Java frame is a Runtime Stub with an invalid _frame_complete_offset.
// In this case we patch _frame_complete_offset manually
if (!m->isNMethod() && m->frameSize() > 0 && m->frameCompleteOffset() == -1) {
m->setFrameCompleteOffset(0);
}
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
} else if (findLibraryByAddress((const void*)pc) != NULL) {
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
pc = 0;
}
} else if (trace.num_frames == ticks_not_walkable_not_Java && _features.java_anchor) {
uintptr_t& sp = vm_thread->lastJavaSP();
uintptr_t& pc = vm_thread->lastJavaPC();
if (sp != 0 && pc != 0) {
// Similar to the above: last Java frame is set,
// but points to a Runtime Stub with an invalid _frame_complete_offset
NMethod* m = CodeHeap::findNMethod((const void*)pc);
if (m != NULL && !m->isNMethod() && m->frameSize() > 0 && m->frameCompleteOffset() == -1) {
m->setFrameCompleteOffset(0);
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
}
} else if (trace.num_frames == ticks_GC_active && _features.gc_traces) {
if (vm_thread->lastJavaSP() == 0) {
// Do not add 'GC_active' for threads with no Java frames, e.g. Compiler threads
frame.restore(saved_pc, saved_sp, saved_fp);
return 0;
}
}
frame.restore(saved_pc, saved_sp, saved_fp);
if (trace.num_frames > 0) {
return trace.num_frames + (trace.frames - frames);
}
const char* err_string = asgctError(trace.num_frames);
if (err_string == NULL) {
// No Java stack, because thread is not in Java context
return 0;
}
atomicInc(_failures[-trace.num_frames]);
trace.frames->bci = BCI_ERROR;
trace.frames->method_id = (jmethodID)err_string;
return trace.frames - frames + 1;
}
int Profiler::getJavaTraceJvmti(jvmtiFrameInfo* jvmti_frames, ASGCT_CallFrame* frames, int start_depth, int max_depth) {
int num_frames;
if (VM::jvmti()->GetStackTrace(NULL, start_depth, _max_stack_depth, jvmti_frames, &num_frames) == 0 && num_frames > 0) {
return convertFrames(jvmti_frames, frames, num_frames);
}
return 0;
}
int Profiler::getJavaTraceInternal(jvmtiFrameInfo* jvmti_frames, ASGCT_CallFrame* frames, int max_depth) {
// We cannot call pure JVM TI here, because it assumes _thread_in_native state,
// but allocation events happen in _thread_in_vm state,
// see https://github.com/async-profiler/async-profiler/issues/64
JNIEnv* jni = VM::jni();
if (jni == NULL) {
return 0;
}
JitWriteProtection jit(false);
VMThread* vm_thread = VMThread::fromEnv(jni);
int num_frames;
if (VMStructs::_get_stack_trace(NULL, vm_thread, 0, max_depth, jvmti_frames, &num_frames) == 0 && num_frames > 0) {
return convertFrames(jvmti_frames, frames, num_frames);
}
return 0;
}
inline int Profiler::convertFrames(jvmtiFrameInfo* jvmti_frames, ASGCT_CallFrame* frames, int num_frames) {
// Convert to AsyncGetCallTrace format.
// Note: jvmti_frames and frames may overlap.
for (int i = 0; i < num_frames; i++) {
jint bci = jvmti_frames[i].location;
frames[i].method_id = jvmti_frames[i].method;
frames[i].bci = bci;
}
return num_frames;
}
void Profiler::fillFrameTypes(ASGCT_CallFrame* frames, int num_frames, NMethod* nmethod) {
if (nmethod->isNMethod() && nmethod->isAlive()) {
VMMethod* method = nmethod->method();
if (method == NULL) {
return;
}
jmethodID current_method_id = method->id();
if (current_method_id == NULL) {
return;
}
// If the top frame is a runtime stub, skip it
if (num_frames > 0 && frames[0].bci == BCI_NATIVE_FRAME) {
frames++;
num_frames--;
}
// Mark current_method as COMPILED and frames above current_method as INLINED
for (int i = 0; i < num_frames; i++) {
if (frames[i].method_id == NULL || frames[i].bci <= BCI_NATIVE_FRAME) {
break;
}
if (frames[i].method_id == current_method_id) {
int level = nmethod->level();
frames[i].bci = FrameType::encode(level >= 1 && level <= 3 ? FRAME_C1_COMPILED : FRAME_JIT_COMPILED, frames[i].bci);
for (int j = 0; j < i; j++) {
frames[j].bci = FrameType::encode(FRAME_INLINED, frames[j].bci);
}
break;
}
}
} else if (nmethod->isInterpreter()) {
// Mark the first Java frame as INTERPRETED
for (int i = 0; i < num_frames; i++) {
if (frames[i].bci > BCI_NATIVE_FRAME) {
frames[i].bci = FrameType::encode(FRAME_INTERPRETED, frames[i].bci);
break;
}
}
}
}
u64 Profiler::recordSample(void* ucontext, u64 counter, EventType event_type, Event* event) {
atomicInc(_total_samples);
int tid = fastThreadId();
u32 lock_index = getLockIndex(tid);
if (!_locks[lock_index].tryLock() &&
!_locks[lock_index = (lock_index + 1) % CONCURRENCY_LEVEL].tryLock() &&
!_locks[lock_index = (lock_index + 2) % CONCURRENCY_LEVEL].tryLock())
{
// Too many concurrent signals already
atomicInc(_failures[-ticks_skipped]);
if (event_type == PERF_SAMPLE) {
// Need to reset PerfEvents ring buffer, even though we discard the collected trace
PerfEvents::resetBuffer(tid);
}
return 0;
}
ASGCT_CallFrame* frames = _calltrace_buffer[lock_index]->_asgct_frames;
jvmtiFrameInfo* jvmti_frames = _calltrace_buffer[lock_index]->_jvmti_frames;
int num_frames = 0;
if (_add_event_frame && event_type >= ALLOC_SAMPLE && event_type <= PARK_SAMPLE) {
u32 class_id = ((EventWithClassId*)event)->_class_id;
if (class_id != 0) {
// Convert event_type to frame_type, e.g. ALLOC_SAMPLE -> BCI_ALLOC
jint frame_type = BCI_ALLOC - (event_type - ALLOC_SAMPLE);
num_frames = makeFrame(frames, frame_type, class_id);
}
}
StackContext java_ctx = {0};
num_frames += getNativeTrace(ucontext, frames + num_frames, event_type, tid, &java_ctx);
if (_cstack == CSTACK_VM) {
num_frames += StackWalker::walkVM(ucontext, frames + num_frames, _max_stack_depth);
} else if (event_type <= EXECUTION_SAMPLE) {
// Async events
int java_frames = getJavaTraceAsync(ucontext, frames + num_frames, _max_stack_depth, &java_ctx);
if (java_frames > 0 && java_ctx.pc != NULL && VMStructs::hasMethodStructs()) {
NMethod* nmethod = CodeHeap::findNMethod(java_ctx.pc);
if (nmethod != NULL) {
fillFrameTypes(frames + num_frames, java_frames, nmethod);
}
}
num_frames += java_frames;
} else if (event_type >= ALLOC_SAMPLE && event_type <= ALLOC_OUTSIDE_TLAB && _alloc_engine == &alloc_tracer) {
if (VMStructs::_get_stack_trace != NULL) {
// Object allocation in HotSpot happens at known places where it is safe to call JVM TI,
// but not directly, since the thread is in_vm rather than in_native
num_frames += getJavaTraceInternal(jvmti_frames + num_frames, frames + num_frames, _max_stack_depth);
} else {
num_frames += getJavaTraceAsync(ucontext, frames + num_frames, _max_stack_depth, &java_ctx);
}
} else {
// Lock events and instrumentation events can safely call synchronous JVM TI stack walker.
// Skip Instrument.recordSample() method
int start_depth = event_type == INSTRUMENTED_METHOD ? 1 : 0;
num_frames += getJavaTraceJvmti(jvmti_frames + num_frames, frames + num_frames, start_depth, _max_stack_depth);
}
if (num_frames == 0) {
num_frames += makeFrame(frames + num_frames, BCI_ERROR, "no_Java_frame");
}
if (_add_thread_frame) {
num_frames += makeFrame(frames + num_frames, BCI_THREAD_ID, tid);
}
if (_add_sched_frame) {
num_frames += makeFrame(frames + num_frames, BCI_ERROR, OS::schedPolicy(0));
}
u32 call_trace_id = _call_trace_storage.put(num_frames, frames, counter);
_jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event);
_locks[lock_index].unlock();
return (u64)tid << 32 | call_trace_id;
}
void Profiler::recordExternalSample(u64 counter, int tid, EventType event_type, Event* event, int num_frames, ASGCT_CallFrame* frames) {
atomicInc(_total_samples);
if (_add_thread_frame) {
num_frames += makeFrame(frames + num_frames, BCI_THREAD_ID, tid);
}
if (_add_sched_frame) {
num_frames += makeFrame(frames + num_frames, BCI_ERROR, OS::schedPolicy(tid));
}
u32 call_trace_id = _call_trace_storage.put(num_frames, frames, counter);
u32 lock_index = getLockIndex(tid);
if (!_locks[lock_index].tryLock() &&
!_locks[lock_index = (lock_index + 1) % CONCURRENCY_LEVEL].tryLock() &&
!_locks[lock_index = (lock_index + 2) % CONCURRENCY_LEVEL].tryLock())
{
// Too many concurrent signals already
atomicInc(_failures[-ticks_skipped]);
return;
}
_jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event);
_locks[lock_index].unlock();
}
void Profiler::recordExternalSample(u64 counter, int tid, EventType event_type, Event* event, u32 call_trace_id) {
_call_trace_storage.add(call_trace_id, counter);
u32 lock_index = getLockIndex(tid);
if (!_locks[lock_index].tryLock() &&
!_locks[lock_index = (lock_index + 1) % CONCURRENCY_LEVEL].tryLock() &&
!_locks[lock_index = (lock_index + 2) % CONCURRENCY_LEVEL].tryLock())
{
return;
}
_jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event);
_locks[lock_index].unlock();
}
void Profiler::recordEventOnly(EventType event_type, Event* event) {
if (!_jfr.active()) {
return;
}
int tid = fastThreadId();
u32 lock_index = getLockIndex(tid);
if (!_locks[lock_index].tryLock() &&
!_locks[lock_index = (lock_index + 1) % CONCURRENCY_LEVEL].tryLock() &&
!_locks[lock_index = (lock_index + 2) % CONCURRENCY_LEVEL].tryLock())
{
return;
}
_jfr.recordEvent(lock_index, tid, 0, event_type, event);
_locks[lock_index].unlock();
}
void Profiler::writeLog(LogLevel level, const char* message) {
_jfr.recordLog(level, message, strlen(message));
}
void Profiler::writeLog(LogLevel level, const char* message, size_t len) {
_jfr.recordLog(level, message, len);
}
void* Profiler::dlopen_hook(const char* filename, int flags) {
void* result = dlopen(filename, flags);
if (result != NULL) {
instance()->updateSymbols(false);
}
return result;
}
void Profiler::switchLibraryTrap(bool enable) {
if (_dlopen_entry != NULL) {
void* impl = enable ? (void*)dlopen_hook : (void*)dlopen;
__atomic_store_n(_dlopen_entry, impl, __ATOMIC_RELEASE);
}
}
Error Profiler::installTraps(const char* begin, const char* end) {
const void* begin_addr = NULL;
if (begin != NULL && (begin_addr = resolveSymbol(begin)) == NULL) {
return Error("Begin address not found");
}
const void* end_addr = NULL;
if (end != NULL && (end_addr = resolveSymbol(end)) == NULL) {
return Error("End address not found");
}
_begin_trap.assign(begin_addr);
_end_trap.assign(end_addr);
if (_begin_trap.entry() == 0) {
_engine->enableEvents(true);
} else {
_engine->enableEvents(false);
if (!_begin_trap.install()) {
return Error("Cannot install begin breakpoint");
}
}
return Error::OK;
}
void Profiler::uninstallTraps() {
_begin_trap.uninstall();
_end_trap.uninstall();
_engine->enableEvents(false);
}
void Profiler::trapHandler(int signo, siginfo_t* siginfo, void* ucontext) {
StackFrame frame(ucontext);
if (_begin_trap.covers(frame.pc())) {
profiling_window._start_time = TSC::ticks();
_engine->enableEvents(true);
_begin_trap.uninstall();
_end_trap.install();
frame.pc() = _begin_trap.entry();
} else if (_end_trap.covers(frame.pc())) {
_engine->enableEvents(false);
_end_trap.uninstall();
profiling_window._end_time = TSC::ticks();
recordEventOnly(PROFILING_WINDOW, &profiling_window);
_begin_trap.install();
frame.pc() = _end_trap.entry();
} else if (orig_trapHandler != NULL) {
orig_trapHandler(signo, siginfo, ucontext);
}
}
void Profiler::segvHandler(int signo, siginfo_t* siginfo, void* ucontext) {
StackFrame frame(ucontext);
uintptr_t pc = frame.pc();
uintptr_t length = SafeAccess::skipLoad(pc);
if (length > 0) {
// Skip the fault instruction, as if it successfully loaded NULL
frame.pc() += length;
frame.retval() = 0;
return;
}
length = SafeAccess::skipLoadArg(pc);
if (length > 0) {
// Act as if the load returned default_value argument
frame.pc() += length;
frame.retval() = frame.arg1();
return;
}
StackWalker::checkFault();
// Workaround for JDK-8313796. Setting cstack=dwarf also helps
if (VMStructs::isInterpretedFrameValidFunc((const void*)pc) && frame.skipFaultInstruction()) {
return;
}
if (WX_MEMORY && Trap::isFaultInstruction(pc)) {
return;
}
orig_segvHandler(signo, siginfo, ucontext);
}
void Profiler::wakeupHandler(int signo) {
// Dummy handler for interrupting syscalls
}
void Profiler::setupSignalHandlers() {
SigAction prev_handler = OS::installSignalHandler(SIGTRAP, AllocTracer::trapHandler);
if (prev_handler == AllocTracer::trapHandler) {
// Handlers already configured
return;
} else if (prev_handler != (void*)SIG_DFL && prev_handler != (void*)SIG_IGN) {
orig_trapHandler = prev_handler;
}
if (VM::hotspot_version() > 0 || !VM::loaded()) {
// HotSpot tolerates interposed SIGSEGV/SIGBUS handler; other JVMs probably not
orig_segvHandler = OS::replaceCrashHandler(segvHandler);
}
OS::installSignalHandler(WAKEUP_SIGNAL, NULL, wakeupHandler);
}
void Profiler::setThreadInfo(int tid, const char* name, jlong java_thread_id) {
MutexLocker ml(_thread_names_lock);
_thread_names[tid] = name;
_thread_ids[tid] = java_thread_id;
}
void Profiler::updateThreadName(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) {
if (_update_thread_names) {
JitWriteProtection jit(true); // workaround for JDK-8262896
jvmtiThreadInfo thread_info;
int native_thread_id = VMThread::nativeThreadId(jni, thread);
if (native_thread_id >= 0 && jvmti->GetThreadInfo(thread, &thread_info) == 0) {
jlong java_thread_id = VMThread::javaThreadId(jni, thread);
setThreadInfo(native_thread_id, thread_info.name, java_thread_id);
jvmti->Deallocate((unsigned char*)thread_info.name);
}
}
}
void Profiler::updateJavaThreadNames() {
if (_update_thread_names && VM::loaded()) {
jvmtiEnv* jvmti = VM::jvmti();
jint thread_count;
jthread* thread_objects;
if (jvmti->GetAllThreads(&thread_count, &thread_objects) != 0) {
return;
}
JNIEnv* jni = VM::jni();
for (int i = 0; i < thread_count; i++) {
updateThreadName(jvmti, jni, thread_objects[i]);
}
jvmti->Deallocate((unsigned char*)thread_objects);
}
}
void Profiler::updateNativeThreadNames() {
if (_update_thread_names) {
ThreadList* thread_list = OS::listThreads();
char name_buf[64];
for (int tid; (tid = thread_list->next()) != -1; ) {
MutexLocker ml(_thread_names_lock);
std::map<int, std::string>::iterator it = _thread_names.lower_bound(tid);
if (it == _thread_names.end() || it->first != tid) {
if (OS::threadName(tid, name_buf, sizeof(name_buf))) {
_thread_names.insert(it, std::map<int, std::string>::value_type(tid, name_buf));
}
}
}
delete thread_list;
}
}
bool Profiler::excludeTrace(FrameName* fn, CallTrace* trace) {
bool checkInclude = fn->hasIncludeList();
bool checkExclude = fn->hasExcludeList();
if (!(checkInclude || checkExclude)) {
return false;
}
for (int i = 0; i < trace->num_frames; i++) {
const char* frame_name = fn->name(trace->frames[i], true);
if (checkExclude && fn->exclude(frame_name)) {
return true;
}
if (checkInclude && fn->include(frame_name)) {
checkInclude = false;
if (!checkExclude) break;
}
}
return checkInclude;
}
Engine* Profiler::selectEngine(const char* event_name) {
if (event_name == NULL) {
return &noop_engine;
} else if (strcmp(event_name, EVENT_CPU) == 0) {
return PerfEvents::supported() ? (Engine*)&perf_events : (Engine*)&wall_clock;
} else if (strcmp(event_name, EVENT_WALL) == 0) {
return VM::isOpenJ9() ? (Engine*)&j9_wall_clock : (Engine*)&wall_clock;
} else if (strcmp(event_name, EVENT_CTIMER) == 0) {
return &ctimer;
} else if (strcmp(event_name, EVENT_ITIMER) == 0) {
return &itimer;
} else if (strchr(event_name, '.') != NULL && strchr(event_name, ':') == NULL) {
return &instrument;
} else {
return &perf_events;
}
}
Engine* Profiler::selectAllocEngine(long alloc_interval, bool live) {
if (VM::canSampleObjects()) {
return &object_sampler;
} else if (VM::isOpenJ9()) {
return &j9_object_sampler;
} else {
return &alloc_tracer;
}
}
Engine* Profiler::activeEngine() {
switch (_event_mask) {
case EM_ALLOC:
return _alloc_engine;
case EM_LOCK:
return &lock_tracer;