-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathprofiler.cpp
1510 lines (1331 loc) · 46.3 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 2016 Andrei Pangin
* Copyright 2024 Datadog, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "profiler.h"
#include "asyncSampleMutex.h"
#include "context.h"
#include "counters.h"
#include "ctimer.h"
#include "dwarf.h"
#include "flightRecorder.h"
#include "itimer.h"
#include "j9Ext.h"
#include "j9WallClock.h"
#include "objectSampler.h"
#include "os.h"
#include "perfEvents.h"
#include "safeAccess.h"
#include "stackFrame.h"
#include "stackWalker.h"
#include "symbols.h"
#include "thread.h"
#include "vmStructs.h"
#include "wallClock.h"
#include <algorithm>
#include <dlfcn.h>
#include <fstream>
#include <memory>
#include <set>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.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();
volatile bool Profiler::_signals_initialized = false;
static void (*orig_trapHandler)(int signo, siginfo_t *siginfo, void *ucontext);
static void (*orig_segvHandler)(int signo, siginfo_t *siginfo, void *ucontext);
static void (*orig_busHandler)(int signo, siginfo_t *siginfo, void *ucontext);
static Engine noop_engine;
static PerfEvents perf_events;
static WallClockASGCT wall_asgct_engine;
static WallClockJVMTI wall_jvmti_engine;
static J9WallClock j9_engine;
static ITimer itimer;
static CTimer ctimer;
// Stack recovery techniques used to workaround AsyncGetCallTrace flaws.
// Can be disabled with 'safemode' option.
enum StackRecovery {
UNKNOWN_JAVA = (1 << 0),
POP_STUB = (1 << 1),
POP_METHOD = (1 << 2),
UNWIND_NATIVE = (1 << 3),
LAST_JAVA_PC = (1 << 4),
GC_TRACES = (1 << 5),
PROBE_SP = 0x100,
};
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);
}
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) {
ProfiledThread::initCurrentThread();
int tid = ProfiledThread::currentTid();
if (_thread_filter.enabled()) {
_thread_filter.remove(tid);
}
updateThreadName(jvmti, jni, thread, true);
_cpu_engine->registerThread(tid);
_wall_engine->registerThread(tid);
}
void Profiler::onThreadEnd(jvmtiEnv *jvmti, JNIEnv *jni, jthread thread) {
int tid = ProfiledThread::currentTid();
if (_thread_filter.enabled()) {
_thread_filter.remove(tid);
}
updateThreadName(jvmti, jni, thread, true);
_cpu_engine->unregisterThread(tid);
// unregister here because JNI callers generally don't know about thread exits
_wall_engine->unregisterThread(tid);
ProfiledThread::release();
}
int Profiler::registerThread(int tid) {
return _instance->_cpu_engine->registerThread(tid) |
_instance->_wall_engine->registerThread(tid);
}
void Profiler::unregisterThread(int tid) {
_instance->_cpu_engine->unregisterThread(tid);
_instance->_wall_engine->unregisterThread(tid);
}
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::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) {
int n = snprintf(buf, buf_end - buf, "%d", (int)(c - name));
if (n < 0 || n >= buf_end - buf) {
if (n < 0) {
Log::debug("Error in snprintf.");
}
goto end;
}
buf += n;
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);
}
end:
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;
}
const char *Profiler::findNativeMethod(const void *address) {
CodeCache *lib = _libs->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 _libs->findLibraryByAddress(pc) != NULL;
}
}
int Profiler::getNativeTrace(void *ucontext, ASGCT_CallFrame *frames,
int event_type, int tid, StackContext *java_ctx,
bool *truncated) {
if (_cstack == CSTACK_NO ||
(event_type == BCI_ALLOC || event_type == BCI_ALLOC_OUTSIDE_TLAB) ||
(event_type != BCI_CPU && event_type != BCI_WALL &&
_cstack == CSTACK_DEFAULT)) {
return 0;
}
const void *callchain[MAX_NATIVE_FRAMES];
int native_frames = 0;
if (event_type == BCI_CPU && _cpu_engine == &perf_events) {
native_frames +=
PerfEvents::walkKernel(tid, callchain + native_frames,
MAX_NATIVE_FRAMES - native_frames, java_ctx);
}
if (_cstack == CSTACK_VM) {
return 0;
} else if (_cstack == CSTACK_DWARF) {
native_frames += StackWalker::walkDwarf(ucontext, callchain + native_frames,
MAX_NATIVE_FRAMES - native_frames,
java_ctx, truncated);
} else {
native_frames += StackWalker::walkFP(ucontext, callchain + native_frames,
MAX_NATIVE_FRAMES - native_frames,
java_ctx, truncated);
}
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]);
if (current_method_name != NULL &&
NativeFunc::isMarked(current_method_name)) {
// This is C++ interpreter frame, this and later frames should be reported
// as Java frames returned by AGCT. Terminate the scan here.
return 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,
bool *truncated) {
// 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) {
Counters::increment(AGCT_NOT_REGISTERED_IN_TLS);
return 0;
}
JNIEnv *jni = VM::jni();
if (jni == NULL) {
// Not a Java thread
Counters::increment(AGCT_NOT_JAVA);
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 (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 (!VMStructs::isSafeToWalk(saved_pc)) {
frames->bci = BCI_NATIVE_FRAME;
CodeBlob *codeBlob =
VMStructs::libjvm()->findBlobByAddress((const void *)saved_pc);
if (codeBlob) {
frames->method_id = (jmethodID)codeBlob->_name;
} else {
frames->method_id = (jmethodID) "unknown_unwalkable";
}
return 1;
}
} else {
return 0;
}
int state = vm_thread->state();
// from OpenJDK
// https://github.com/openjdk/jdk/blob/7455bb23c1d18224e48e91aae4f11fe114d04fab/src/hotspot/share/utilities/globalDefinitions.hpp#L1030
/*
enum JavaThreadState {
_thread_uninitialized = 0, // should never happen (missing
initialization) _thread_new = 2, // just starting up, i.e., in
process of being initialized _thread_new_trans = 3, // corresponding
transition state (not used, included for completeness) _thread_in_native = 4,
// running in native code _thread_in_native_trans = 5, // corresponding
transition state _thread_in_vm = 6, // running in VM
_thread_in_vm_trans = 7, // corresponding transition state
_thread_in_Java = 8, // running in Java or in stub code
_thread_in_Java_trans = 9, // corresponding transition state (not
used, included for completeness) _thread_blocked = 10, // blocked in
vm _thread_blocked_trans = 11, // corresponding transition state
_thread_max_state = 12 // maximum thread state+1 - used for
statistics allocation
};
*/
bool in_java = (state == 8 || state == 9);
if (in_java && java_ctx->sp != 0) {
// skip ahead to the Java frames before calling AGCT
frame.restore((uintptr_t)java_ctx->pc, java_ctx->sp, java_ctx->fp);
} else if (state != 0 && vm_thread->lastJavaSP() == 0) {
// we haven't found the top Java frame ourselves, and the lastJavaSP wasn't
// recorded either when not in the Java state, lastJava ucontext will be
// used by AGCT
Counters::increment(AGCT_NATIVE_NO_JAVA_CONTEXT);
return 0;
}
bool blocked_in_vm = (state == 10 || state == 11);
// avoid unwinding during deoptimization
if (blocked_in_vm && vm_thread->osThreadState() == ThreadState::RUNNABLE) {
Counters::increment(AGCT_BLOCKED_IN_VM);
return 0;
}
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) &&
!(_safe_mode & 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) {
max_depth -= makeFrame(trace.frames++, BCI_NATIVE_FRAME, stub->_name);
}
if (!(_safe_mode & POP_STUB) &&
frame.unwindStub((instruction_t *)stub->_start, stub->_name) &&
isAddressInCode((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 (!(_safe_mode & POP_METHOD) && frame.unwindCompiled(nmethod) &&
isAddressInCode((const void *)frame.pc())) {
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
if ((_safe_mode & 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 (!(_safe_mode & POP_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 &&
!(_safe_mode & LAST_JAVA_PC)) {
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 (_libs->findLibraryByAddress((const void *)pc) != NULL) {
VM::_asyncGetCallTrace(&trace, max_depth, ucontext);
}
pc = 0;
}
} else if (trace.num_frames == ticks_not_walkable_not_Java &&
!(_safe_mode & LAST_JAVA_PC)) {
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 && !(_safe_mode & 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/jvm-profiling-tools/java-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;
}
// 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;
}
}
}
}
void Profiler::recordExternalSample(u64 counter, int tid,
jvmtiFrameInfo *jvmti_frames,
jint num_jvmti_frames, bool truncated,
jint event_type, Event *event) {
atomicInc(_total_samples);
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 == BCI_CPU && _cpu_engine == &perf_events) {
// Need to reset PerfEvents ring buffer, even though we discard the
// collected trace
PerfEvents::resetBuffer(tid);
}
return;
}
u32 call_trace_id = 0;
if (!_omit_stacktraces && jvmti_frames != nullptr) {
ASGCT_CallFrame *frames = _calltrace_buffer[lock_index]->_asgct_frames;
int num_frames = 0;
if (!_jfr.active() && BCI_ALLOC >= event_type && event_type >= BCI_PARK &&
event->_id) {
num_frames = makeFrame(frames, event_type, event->_id);
}
num_frames +=
convertFrames(jvmti_frames, frames + num_frames, num_jvmti_frames);
call_trace_id =
_call_trace_storage.put(num_frames, frames, truncated, counter);
}
_jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event);
_locks[lock_index].unlock();
}
void Profiler::recordSample(void *ucontext, u64 counter, int tid,
jint event_type, u32 call_trace_id, Event *event) {
atomicInc(_total_samples);
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 == BCI_CPU && _cpu_engine == &perf_events) {
// Need to reset PerfEvents ring buffer, even though we discard the
// collected trace
PerfEvents::resetBuffer(tid);
}
return;
}
bool truncated = false;
// in lightweight mode we're just sampling the the context associated with the
// passage of CPU or wall time, we use the same event definitions but we
// record a null stacktrace we can skip the unwind if we've got a
// call_trace_id determined to be reusable at a higher level
if (!_omit_stacktraces && call_trace_id == 0) {
ASGCT_CallFrame *frames = _calltrace_buffer[lock_index]->_asgct_frames;
int num_frames = 0;
StackContext java_ctx = {0};
ASGCT_CallFrame *native_stop = frames + num_frames;
num_frames += getNativeTrace(ucontext, native_stop, event_type, tid,
&java_ctx, &truncated);
if (_cstack == CSTACK_VM) {
num_frames +=
StackWalker::walkVM(ucontext, frames + num_frames, _max_stack_depth,
_call_stub_begin, _call_stub_end);
} else if (event_type == BCI_CPU || event_type == BCI_WALL) {
int java_frames = 0;
{
// Async events
AsyncSampleMutex mutex(ProfiledThread::current());
if (mutex.acquired()) {
java_frames =
getJavaTraceAsync(ucontext, frames + num_frames, _max_stack_depth,
&java_ctx, &truncated);
}
}
if (java_frames > 0 && java_ctx.pc != NULL) {
NMethod *nmethod = CodeHeap::findNMethod(java_ctx.pc);
if (nmethod != NULL) {
fillFrameTypes(frames + num_frames, java_frames, nmethod);
}
}
num_frames += java_frames;
}
if (num_frames == 0) {
num_frames += makeFrame(frames + num_frames, BCI_ERROR, "no_Java_frame");
}
call_trace_id =
_call_trace_storage.put(num_frames, frames, truncated, counter);
ProfiledThread *thread = ProfiledThread::current();
if (thread != nullptr) {
thread->recordCallTraceId(call_trace_id);
}
}
_jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event);
_locks[lock_index].unlock();
}
void Profiler::recordWallClockEpoch(int tid, WallClockEpochEvent *event) {
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.wallClockEpoch(lock_index, event);
_locks[lock_index].unlock();
}
void Profiler::recordTraceRoot(int tid, TraceRootEvent *event) {
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.recordTraceRoot(lock_index, tid, event);
_locks[lock_index].unlock();
}
void Profiler::recordQueueTime(int tid, QueueTimeEvent *event) {
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.recordQueueTime(lock_index, tid, event);
_locks[lock_index].unlock();
}
void Profiler::recordExternalSample(u64 weight, int tid, int num_frames,
ASGCT_CallFrame *frames, bool truncated,
jint event_type, Event *event) {
atomicInc(_total_samples);
u32 call_trace_id =
_call_trace_storage.put(num_frames, frames, truncated, weight);
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::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::writeDatadogProfilerSetting(int tid, int length,
const char *name, const char *value,
const char *unit) {
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.recordDatadogSetting(lock_index, length, name, value, unit);
_locks[lock_index].unlock();
}
void Profiler::writeHeapUsage(long value, bool live) {
int tid = ProfiledThread::currentTid();
if (tid < 0) {
return;
}
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.recordHeapUsage(lock_index, value, live);
_locks[lock_index].unlock();
}
void *Profiler::dlopen_hook(const char *filename, int flags) {
void *result = dlopen(filename, flags);
if (result != NULL) {
// Static function of Profiler -> can not use the instance variable _libs
// Since Libraries is a singleton, this does not matter
Libraries::instance()->updateSymbols(false);
}
return result;
}
void Profiler::switchLibraryTrap(bool enable) {
void *impl = enable ? (void *)dlopen_hook : (void *)dlopen;
__atomic_store_n(_dlopen_entry, impl, __ATOMIC_RELEASE);
}
void Profiler::enableEngines() {
_cpu_engine->enableEvents(true);
_wall_engine->enableEvents(true);
}
void Profiler::disableEngines() {
_cpu_engine->enableEvents(false);
_wall_engine->enableEvents(false);
}
void Profiler::segvHandler(int signo, siginfo_t *siginfo, void *ucontext) {
if (!crashHandler(signo, siginfo, ucontext)) {
orig_segvHandler(signo, siginfo, ucontext);
}
}
void Profiler::busHandler(int signo, siginfo_t *siginfo, void *ucontext) {
if (!crashHandler(signo, siginfo, ucontext)) {
orig_busHandler(signo, siginfo, ucontext);
}
}
bool Profiler::crashHandler(int signo, siginfo_t *siginfo, void *ucontext) {
ProfiledThread* thrd = ProfiledThread::current();
if (thrd != nullptr && !thrd->enterCrashHandler()) {
// we are already in a crash handler; don't recurse!
return false;
}
uintptr_t fault_address = (uintptr_t)siginfo->si_addr;
StackFrame frame(ucontext);
uintptr_t pc = frame.pc();
if (pc == fault_address) {
// it is 'pc' that is causing the fault; can not access it safely
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return false;
}
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;
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return true;
}
length = SafeAccess::skipLoadArg(pc);
if (length > 0) {
// Act as if the load returned default_value argument
frame.pc() += length;
frame.retval() = frame.arg1();
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return true;
}
if (WX_MEMORY && Trap::isFaultInstruction(pc)) {
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return true;
}
if (VM::isHotspot()) {
// the following checks require vmstructs and therefore HotSpot
StackWalker::checkFault(thrd);
// Workaround for JDK-8313796. Setting cstack=dwarf also helps
if (VMStructs::isInterpretedFrameValidFunc((const void *)pc) &&
frame.skipFaultInstruction()) {
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return true;
}
}
if (thrd != nullptr) {
thrd->exitCrashHandler();
}
return false;
}
void Profiler::setupSignalHandlers() {
// do not re-run the signal setup (run only when VM has not been loaded yet)
if (__sync_bool_compare_and_swap(&_signals_initialized, false, true)) {
if (VM::isHotspot() || VM::isOpenJ9()) {
// HotSpot and J9 tolerate interposed SIGSEGV/SIGBUS handler; other JVMs
// probably not
orig_segvHandler = OS::replaceSigsegvHandler(segvHandler);
orig_busHandler = OS::replaceSigbusHandler(busHandler);
}
}
}
/**
* Update thread name for the given thread
*/
void Profiler::updateThreadName(jvmtiEnv *jvmti, JNIEnv *jni, jthread thread,
bool self) {
JitWriteProtection jit(true); // workaround for JDK-8262896
jvmtiThreadInfo thread_info;
int native_thread_id = VMThread::nativeThreadId(jni, thread);
if (native_thread_id < 0 && self) {
// if updating the current thread, use the native thread id from the
// ProfilerThread
native_thread_id = ProfiledThread::currentTid();
}
if (native_thread_id >= 0 &&
jvmti->GetThreadInfo(thread, &thread_info) == 0) {
jlong java_thread_id = VMThread::javaThreadId(jni, thread);
_thread_info.set(native_thread_id, thread_info.name, java_thread_id);
jvmti->Deallocate((unsigned char *)thread_info.name);
}
}
void Profiler::updateJavaThreadNames() {
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() {
ThreadList *thread_list = OS::listThreads();
constexpr size_t buffer_size = 64;
char name_buf[buffer_size]; // Stack-allocated buffer
for (int tid; (tid = thread_list->next()) != -1;) {