-
Notifications
You must be signed in to change notification settings - Fork 747
/
Copy pathtrcengine.c
1436 lines (1248 loc) · 49.2 KB
/
trcengine.c
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 IBM Corp. and others 1991
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] https://openjdk.org/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0
*******************************************************************************/
#include "j9protos.h"
#include "jvminit.h"
#include "j9rastrace.h"
#include "rastrace_internal.h"
#include "ute.h"
#define _UTE_STATIC_
#include "jvmri.h"
#include "j9trcnls.h"
#include "ut_j9trc.h"
#undef UT_MODULE_LOADED
#undef UT_MODULE_UNLOADED
#include "ut_mt.h"
#undef UT_MODULE_LOADED
#undef UT_MODULE_UNLOADED
#include "ut_j9trc_aux.h"
#include "j2sever.h"
#include <string.h>
#define UT_MAX_OPTS 55
#define DUMP_CALLER_NAME "-Xtrace:trigger"
static void displayTraceHelp (J9JavaVM *vm);
static IDATA initializeTraceOptions(J9JavaVM *vm, J9VMInitArgs *vmArgs, char *opts[]);
static UtInterface *initializeUtInterface(void);
jint JNICALL JVM_OnUnload(JavaVM *vm, void *reserved);
static void requestTraceCleanup(J9JavaVM* vm, J9VMThread * vmThread);
static void reportVMTermination (J9JavaVM* vm, J9VMThread * vmThread);
jint JNICALL JVM_OnLoad(JavaVM *vm, char *options, void *reserved);
static IDATA parseTraceOptions (J9JavaVM *vm,const char *optionString, IDATA optionsLength);
static omr_error_t runtimeSetTraceOptions(J9VMThread * thr,const char * traceOptions);
#if defined(J9VM_OPT_CRIU_SUPPORT)
static BOOLEAN criuRestoreInitializeTrace(J9VMThread *thr);
#endif /* defined(J9VM_OPT_CRIU_SUPPORT) */
static void hookThreadAboutToStart (J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData);
static void hookVmInitialized (J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData);
static char *threadName(OMR_VMThread* vmThread);
static omr_error_t populateTraceHeaderInfo(J9JavaVM *vm);
static BOOLEAN checkAndSetL2EnabledFlag(void);
static void hookThreadEnd (J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData);
static omr_error_t reportTraceEvent(J9JavaVM *vm, J9VMThread *self, UDATA eventFlags);
static IDATA splitCommandLineOption(J9JavaVM *vm, const char *optionString, IDATA optionLength, char *opt[]);
static omr_error_t setJ9VMTraceOption(const OMR_VM *omr_vm, const char *optName, const char* optValue, BOOLEAN atRuntime);
static void reportJ9VMCommandLineError(J9PortLibrary* portLibrary, const char* detailStr, va_list args);
static void printTraceWhat(J9PortLibrary* portLibrary);
static void doTriggerActionJavadump(OMR_VMThread *);
static void doTriggerActionCoredump(OMR_VMThread *);
static void doTriggerActionHeapdump(OMR_VMThread *);
static void doTriggerActionSnap(OMR_VMThread *);
static void doTriggerActionCeedump(OMR_VMThread *);
static void doTriggerActionAssertDumpEvent(OMR_VMThread *omrThr);
static void trcStartupComplete(J9VMThread* thr);
/* Trace functions for Java version of UtModuleInterface
* Used by modules that declare Environment=Java at the top of
* their TDF files.
*/
static void javaTrace(void *env, UtModuleInfo *modInfo, U_32 traceId, const char *spec, ...);
static void javaTraceMem (void *env, UtModuleInfo *modInfo, U_32 traceId, UDATA length, void *memptr);
static void javaTraceState (void *env, UtModuleInfo *modInfo, U_32 traceId, const char *spec, ...);
static void javaTraceInit (void* env, UtModuleInfo *modInfo);
static void javaTraceTerm (void* env, UtModuleInfo *modInfo);
typedef omr_error_t (*traceOptionFunction)(J9JavaVM *vm,const char * value,BOOLEAN atRuntime);
/**
* Structure representing a trace option such as stackdepth
* or trigger
*/
struct traceOption {
const char * name;
const BOOLEAN runtimeModifiable;
const traceOptionFunction optionFunction;
};
/**
* Additional trace options supported by the Java layer to
* supply method trace functionality.
* (Set the methods to be traced, set the depth and the compression options
* for the stacks produced by the jstacktrace trigger action.)
*/
const struct traceOption TRACE_OPTIONS[] =
{
/* Name, Can be modified at runtime, option function */
{RAS_METHODS_KEYWORD, FALSE, setMethod},
{RAS_STACKDEPTH_KEYWORD, TRUE, setStackDepth},
{RAS_COMPRESSION_LEVEL_KEYWORD, TRUE, setStackCompressionLevel},
{RAS_MAX_STRING_LENGTH_KEYWORD, FALSE, setMaxStringLength},
};
#define NUMBER_OF_TRACE_OPTIONS (sizeof(TRACE_OPTIONS) / sizeof(struct traceOption))
/**
* The list of trigger actions defined by J9VM passed to the
* OMR trace engine so that non-Java trace events (like a basic
* trace point hit) can fire Java dependent events (like creating
* a javacore).
*/
static struct RasTriggerAction j9vmTriggerActions[] =
{
{ "jstacktrace", AFTER_TRACEPOINT, doTriggerActionJstacktrace},
{ "javadump", AFTER_TRACEPOINT, doTriggerActionJavadump},
{ "coredump", AFTER_TRACEPOINT, doTriggerActionCoredump},
{ "sysdump", AFTER_TRACEPOINT, doTriggerActionCoredump},
{ "heapdump", AFTER_TRACEPOINT, doTriggerActionHeapdump},
{ "snap", AFTER_TRACEPOINT, doTriggerActionSnap},
{ "ceedump", AFTER_TRACEPOINT, doTriggerActionCeedump},
/*
* Temporary action to allow asserts to trigger the assert
* dump event without the OMR'd trace code being able to
* access the dump code.
* Will be removed when the dump code moves to OMR.
* * See work item: 64106
*/
{ "assert", AFTER_TRACEPOINT, doTriggerActionAssertDumpEvent},
};
#define NUM_J9VM_TRIGGER_ACTIONS (sizeof(j9vmTriggerActions) / sizeof(j9vmTriggerActions[0]))
static const struct RasTriggerType methodTriggerType = {"method", processTriggerMethodClause,
#if defined(J9VM_OPT_CRIU_SUPPORT)
TRUE};
#else /* defined(J9VM_OPT_CRIU_SUPPORT) */
FALSE};
#endif /* defined(J9VM_OPT_CRIU_SUPPORT) */
/* Global lock for J9VM trace operations. */
omrthread_monitor_t j9TraceLock = NULL;
/* Structures for trace interfaces. */
static J9UtServerInterface javaUtServerIntfS;
static UtModuleInterface javaUtModuleIntfS;
static UtModuleInterface omrUtModuleIntfS;
/* Required to look up the current thread if we are passed a null current thread on a trace point.
* (NoEnv trace points always pass null.)
*/
J9JavaVM* globalVM;
/**
* A helper method for VM startup initialization and CRIU restore using an options file.
*
* @param[in] vm pointer to the J9JavaVM
* @param[in] tempThr pointer to UtThreadData
* @param[in] vmArgs a J9VMInitArgs
* @param[in] isCRIURestore if it is VM startup initialization or CRIU restore
*
* @return return J9VMDLLMAIN_OK if success, otherwise failures
*/
static IDATA
traceInitializationHelper(J9JavaVM *vm, UtThreadData **tempThr, J9VMInitArgs *vmArgs, BOOLEAN isCRIURestore)
{
IDATA returnVal = J9VMDLLMAIN_OK;
char *opts[UT_MAX_OPTS] = {0};
int i = 0;
PORT_ACCESS_FROM_JAVAVM(vm);
returnVal = initializeTraceOptions(vm, vmArgs, opts);
if (J9VMDLLMAIN_OK != returnVal) {
goto done;
}
for (i = 0; NULL != opts[i]; i += 2) {
if (0 == j9_cmdla_stricmp(opts[i], "HELP")) {
displayTraceHelp(vm);
returnVal = J9VMDLLMAIN_SILENT_EXIT_VM;
goto done;
}
}
if (!isCRIURestore) {
registerj9trc_auxWithTrace(((RasGlobalStorage *)vm->j9rasGlobalStorage)->utIntf, NULL);
if (NULL == j9trc_aux_UtModuleInfo.intf) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to register j9trc_aux module, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
returnVal = J9VMDLLMAIN_FAILED;
goto done;
}
}
if (OMR_ERROR_NONE != setOptions(tempThr, (const char **)opts, FALSE)) {
displayTraceHelp(vm);
returnVal = J9VMDLLMAIN_SILENT_EXIT_VM;
goto done;
}
/* needs to occur after setOptions because setOptions sets the default opts */
for (i = 0; NULL != opts[i]; i += 2) {
if (0 == j9_cmdla_stricmp(opts[i], "WHAT")) {
printTraceWhat(PORTLIB);
/* just print this out once then carry on, do not exit vm */
break;
}
}
done:
/* free up allocated options */
for (i = 0; NULL != opts[i]; i++) {
j9mem_free_memory(opts[i]);
}
return returnVal;
}
IDATA
J9VMDllMain(J9JavaVM *vm, IDATA stage, void *reserved)
{
IDATA returnVal = J9VMDLLMAIN_OK;
omr_error_t rc = OMR_ERROR_NONE;
char *ignore[] = {"INITIALIZATION", "METHODS", "WHAT", "STACKDEPTH", "STACKCOMPRESSIONLEVEL", NULL};
char *opts[UT_MAX_OPTS] = {0};
int i = 0;
UtThreadData **tempThr = NULL;
J9VMThread *thr = NULL;
RasGlobalStorage *tempRasGbl = (RasGlobalStorage *)vm->j9rasGlobalStorage;
void **tempGbl = NULL;
char tempPath[MAX_IMAGE_PATH_LENGTH] = {0};
char *javahome = NULL;
J9VMSystemProperty *javaHomeProperty = NULL;
UDATA getPropertyResult = 0;
J9InternalVMFunctions *vmFuncs = vm->internalVMFunctions;
J9HookInterface **hook = vmFuncs->getVMHookInterface(vm);
OMRTraceLanguageInterface languageIntf = {0};
PORT_ACCESS_FROM_JAVAVM( vm );
switch(stage) {
case ALL_LIBRARIES_LOADED:
if (NULL == tempRasGbl) {
/* RAS init may happen in either dump or trace */
vm->j9rasGlobalStorage = j9mem_allocate_memory(sizeof(RasGlobalStorage), OMRMEM_CATEGORY_TRACE);
tempRasGbl = (RasGlobalStorage *)vm->j9rasGlobalStorage;
if (NULL != tempRasGbl) {
memset(tempRasGbl, '\0', sizeof(RasGlobalStorage));
}
}
if (NULL != tempRasGbl) {
vm->runtimeFlags |= J9_RUNTIME_EXTENDED_METHOD_BLOCK;
RAS_GLOBAL_FROM_JAVAVM(stackdepth,vm) = -1;
tempRasGbl->configureTraceEngine = (ConfigureTraceFunction)runtimeSetTraceOptions;
#if defined(J9VM_OPT_CRIU_SUPPORT)
tempRasGbl->criuRestoreInitializeTrace = (CRIURestoreInitializeTrace)criuRestoreInitializeTrace;
#endif /* defined(J9VM_OPT_CRIU_SUPPORT) */
}
break;
case TRACE_ENGINE_INITIALIZED:
if (NULL == tempRasGbl) {
/* Storage for RasGlobalStorage not available, trace not enabled */
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_RAS_GLOBAL_STORAGE);
return J9VMDLLMAIN_FAILED;
}
/*
* Ensure that method entry and exit hooks are honoured
*/
vm->globalEventFlags |= J9_METHOD_ENTER_RASTRACE;
thr = vm->mainThread;
do {
thr->eventFlags |= J9_METHOD_ENTER_RASTRACE;
thr = thr->linkNext;
} while (thr != vm->mainThread);
if (0 != omrthread_monitor_init_with_name(&j9TraceLock, 0, "J9VM Trace Lock")) {
dbg_err_printf(1, PORTLIB, "<UT> Initialization of j9TraceLock failed\n");
return J9VMDLLMAIN_FAILED;
}
/*
* Find the java.home property
*/
getPropertyResult = vmFuncs->getSystemProperty(vm, "java.home", &javaHomeProperty);
if ((J9SYSPROP_ERROR_NOT_FOUND != getPropertyResult)
&& (NULL != javaHomeProperty)
&& (NULL != javaHomeProperty->value)
) {
javahome = javaHomeProperty->value;
} else {
javahome = ".";
}
/*
* Setup the interfaces, any functions we wish to substitute can be done here before assigning
* utIntf to our global pointer.
*/
globalVM = vm;
tempRasGbl->utIntf = initializeUtInterface();
/*
* Set up the early options
* These will be copied when the options
* are processed so it's Ok to use stack space.
*/
opts[0] = UT_FORMAT_KEYWORD;
j9str_printf(tempPath, sizeof(tempPath), "%s" DIR_SEPARATOR_STR "lib;.", javahome);
opts[1] = tempPath;
opts[2] = NULL;
/*
* Find UTE thread slot inside VM thread structure
*/
tempThr = UT_THREAD_FROM_VM_THREAD(vm->mainThread);
tempGbl = &tempRasGbl->utGlobalData;
/* Add Java trace trigger types to the default OMR set */
rc = addTriggerType(thr->omrVMThread, &methodTriggerType);
if (OMR_ERROR_NONE != rc) {
/* Trace engine failed to initialize properly, RC = %d */
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED_RC, returnVal);
return J9VMDLLMAIN_FAILED;
}
/* Add Java trace trigger actions to the default OMR set */
for (i = 0; i < NUM_J9VM_TRIGGER_ACTIONS; i++ ) {
rc = addTriggerAction(thr->omrVMThread, &j9vmTriggerActions[i]);
if (OMR_ERROR_NONE != rc) {
/* Trace engine failed to initialize properly, RC = %d */
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED_RC, returnVal);
return J9VMDLLMAIN_FAILED;
}
}
/* init the language interface */
languageIntf.AttachCurrentThreadToLanguageVM = OMR_Glue_BindCurrentThread;
languageIntf.DetachCurrentThreadFromLanguageVM = OMR_Glue_UnbindCurrentThread;
languageIntf.SetLanguageTraceOption = setJ9VMTraceOption;
languageIntf.ReportCommandLineError = reportJ9VMCommandLineError;
/* UT_DEBUG option parsed in here. UT_DEBUG can be used from here onwards. */
rc = initializeTrace(tempThr, tempGbl, (const char **)opts, vm->omrVM, (const char **)ignore, &languageIntf);
if (OMR_ERROR_NONE != rc) {
/* Trace engine failed to initialize properly, RC = %d */
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED_RC, returnVal);
return J9VMDLLMAIN_FAILED;
}
if (OMR_ERROR_NONE != (threadStart(tempThr, vm->mainThread, "Initialization thread", vm->mainThread->osThread, vm->mainThread->omrVMThread))) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to register initialization thread, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
returnVal = traceInitializationHelper(vm, tempThr, vm->vmArgsArray, FALSE);
if (J9VMDLLMAIN_OK != returnVal) {
return returnVal;
}
if (NULL == tempRasGbl->jvmriInterface) {
/* JVMRI init may happen in either dump or trace */
tempRasGbl->jvmriInterface = j9mem_allocate_memory(sizeof(DgRasInterface), OMRMEM_CATEGORY_TRACE);
if (NULL == tempRasGbl->jvmriInterface) {
dbg_err_printf(1, PORTLIB, "<UT> Storage for jvmri interface not available, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
if (JNI_OK != vmFuncs->fillInDgRasInterface(tempRasGbl->jvmriInterface )) {
dbg_err_printf(1, PORTLIB, "<UT> Error initializing jvmri interface not available, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
}
if (JNI_OK != vmFuncs->initJVMRI(vm)) {
dbg_err_printf(1, PORTLIB, "<UT> Error initializing jvmri interface, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
registerj9trcWithTrace(tempRasGbl->utIntf, NULL);
if (NULL == j9trc_UtModuleInfo.intf) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to register main module, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
Trc_trcengine_J9VMDllMain_Event1(vm);
registermtWithTrace(tempRasGbl->utIntf, NULL);
if (NULL == mt_UtModuleInfo.intf) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to register method trace module, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
/* new hook interface */
if ((*hook)->J9HookRegisterWithCallSite(hook, J9HOOK_VM_INITIALIZED, hookVmInitialized, OMR_GET_CALLSITE(), NULL)) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to hook VM initialized event, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
if ((*hook)->J9HookRegisterWithCallSite(hook, J9HOOK_THREAD_ABOUT_TO_START, hookThreadAboutToStart, OMR_GET_CALLSITE(), NULL)) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to hook VM thread start event, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
if ((*hook)->J9HookRegisterWithCallSite(hook, J9HOOK_VM_THREAD_END, hookThreadEnd, OMR_GET_CALLSITE(), NULL)) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to hook VM thread end event, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
if ((NULL != tempRasGbl->traceMethodTable)
|| (NULL != tempRasGbl->triggerOnMethods)
) {
if (OMR_ERROR_INTERNAL == enableMethodTraceHooks(vm)) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine failed to hook VM Method events, trace not enabled\n");
j9nls_printf(PORTLIB, J9NLS_ERROR | J9NLS_STDERR, J9NLS_TRC_TRACE_INIT_FAILED);
return J9VMDLLMAIN_FAILED;
}
}
/*
* Set up an early version of trace header info
*/
if (OMR_ERROR_NONE != populateTraceHeaderInfo(vm)) {
return J9VMDLLMAIN_FAILED;
}
/* initialize tracing in the port library as soon as possible */
j9port_control(J9PORT_CTLDATA_TRACE_START, (UDATA)tempRasGbl->utIntf);
/* initialize tracing in the thread library */
omrthread_lib_control(J9THREAD_LIB_CONTROL_TRACE_START, (UDATA)tempRasGbl->utIntf);
/* Load module for hookable library tracepoints */
omrhook_lib_control(J9HOOK_LIB_CONTROL_TRACE_START, (UDATA)tempRasGbl->utIntf);
break;
case VM_INITIALIZATION_COMPLETE:
{
/* Force loading of the Trace class. See defect 162723, this is required because of some nuance
* in the early initialization of DB/2 (which uses the Trace class).
*/
JNIEnv *env = (JNIEnv *)vm->mainThread;
(*env)->FindClass(env, "com/ibm/jvm/Trace");
/* fail silently if can't load - probably a small platform */
(*env)->ExceptionClear(env);
}
/* overwrite the header settings now that we have full vm->j2seVersion info */
if (OMR_ERROR_NONE != populateTraceHeaderInfo(vm)) {
return J9VMDLLMAIN_FAILED;
}
/* now force the main thread to start */
reportTraceEvent(vm, vm->mainThread, J9RAS_TRACE_ON_THREAD_CREATE);
break;
case JVM_EXIT_STAGE:
/* CMVC 108664 - do not free trace resources on System.exit() */
if (NULL != tempRasGbl->utIntf) {
thr = vmFuncs->currentVMThread(vm);
/* stop tracing the portlib */
j9port_control(J9PORT_CTLDATA_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
/* stop tracing in the thread library */
omrthread_lib_control(J9THREAD_LIB_CONTROL_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
/* stop tracing in the hookable library */
omrhook_lib_control(J9HOOK_LIB_CONTROL_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
reportVMTermination(vm, thr);
}
break;
case INTERPRETER_SHUTDOWN:
thr = vmFuncs->currentVMThread(vm);
/* if command line argument parsing failed we don't want to try to use an uninitialized trace engine */
if ((NULL != tempRasGbl)
&& (NULL != tempRasGbl->utIntf)
) {
/* stop tracing the portlib */
j9port_control(J9PORT_CTLDATA_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
/* stop tracing in the thread library */
omrthread_lib_control(J9THREAD_LIB_CONTROL_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
/* stop tracing in the hookable library */
omrhook_lib_control(J9HOOK_LIB_CONTROL_TRACE_STOP, (UDATA)tempRasGbl->utIntf);
reportVMTermination(vm, thr);
requestTraceCleanup(vm, thr);
}
{
J9VMDllLoadInfo *loadInfo = FIND_DLL_TABLE_ENTRY(J9_RAS_TRACE_DLL_NAME);
if ((NULL != loadInfo)
&& IS_STAGE_COMPLETED(loadInfo->completedBits, VM_INITIALIZATION_COMPLETE)
) {
/* now force the main thread to end */
reportTraceEvent(vm, thr, J9RAS_TRACE_ON_THREAD_END);
}
}
/* Normal exit - its not safe to free this stuff if we are ab'ending.
* Blank global pointer before freeing struct (safer?)
*/
if (NULL != tempRasGbl) {
vm->j9rasGlobalStorage = NULL;
if (NULL != tempRasGbl->jvmriInterface) {
j9mem_free_memory(tempRasGbl->jvmriInterface);
}
j9mem_free_memory(tempRasGbl);
}
if (NULL != j9TraceLock) {
omrthread_monitor_destroy(j9TraceLock);
}
vmFuncs->shutdownJVMRI(vm);
break;
case LIBRARIES_ONUNLOAD:
/*
* Unhook thread events before terminating trace
*/
(*hook)->J9HookUnregister(hook, J9HOOK_THREAD_ABOUT_TO_START, hookThreadAboutToStart, NULL);
(*hook)->J9HookUnregister(hook, J9HOOK_VM_THREAD_END, hookThreadEnd, NULL);
/* Disable tracing for thread library since the tracing engine will be unloaded. */
omrthread_lib_clear_flags(J9THREAD_LIB_FLAG_TRACING_ENABLED);
break;
}
return returnVal;
}
jint JNICALL JVM_OnLoad(JavaVM *vm, char *options, void *reserved)
{
return JNI_OK;
}
jint JNICALL JVM_OnUnload(JavaVM *vm, void *reserved)
{
return JNI_OK;
}
/**
* Initializes and returns the UtInterface.
*
* @return The external UtInterface. UtModuleInterface APIs expect J9VMThread* as the "env" parameter.
*/
static UtInterface *
initializeUtInterface(void)
{
UtInterface *retVal = NULL;
omr_error_t rc = OMR_ERROR_NONE;
/* initialize OMR layer */
rc = fillInUTInterfaces(&retVal, (UtServerInterface *)&javaUtServerIntfS, &javaUtModuleIntfS);
/* Update the interface we want to present to the Java side with extra calls on UtServerInterface
* and Trace functions that use J9VMThread for the env parameter.
*/
if (OMR_ERROR_NONE == rc) {
/* Back up the original OMR interface so we can access it later if we need to call through. */
memcpy( &omrUtModuleIntfS, &javaUtModuleIntfS, sizeof( UtModuleInterface) );
/* initialize Java layer */
javaUtServerIntfS.TraceMethodEnter = trcTraceMethodEnter;
javaUtServerIntfS.TraceMethodExit = trcTraceMethodExit;
javaUtServerIntfS.StartupComplete = trcStartupComplete;
/*
* Initialize the direct module interface, these
* are versions of the trace functions that expect
* a J9VMThread as their env parameter rather than
* an OMRVMThread.
*/
javaUtModuleIntfS.Trace = javaTrace;
javaUtModuleIntfS.TraceMem = javaTraceMem;
javaUtModuleIntfS.TraceState = javaTraceState;
javaUtModuleIntfS.TraceInit = javaTraceInit;
javaUtModuleIntfS.TraceTerm = javaTraceTerm;
}
return retVal;
}
static IDATA
processTraceOptionString(J9JavaVM *vm, char * opts[], IDATA * optIndex, const char *option, IDATA n)
{
IDATA rc = J9VMDLLMAIN_OK;
const char *optionString = option;
IDATA optionsLength = n;
while (optionsLength > 0 && rc == J9VMDLLMAIN_OK) {
IDATA thisOptionLength = parseTraceOptions(vm, optionString, optionsLength);
if (thisOptionLength < 0) {
PORT_ACCESS_FROM_JAVAVM(vm);
vaReportJ9VMCommandLineError(PORTLIB, "Unmatched braces encountered in trace options");
rc = J9VMDLLMAIN_FAILED;
} else if (thisOptionLength == 0) {
PORT_ACCESS_FROM_JAVAVM(vm);
vaReportJ9VMCommandLineError(PORTLIB, "Null option encountered in trace options");
rc = J9VMDLLMAIN_FAILED;
} else {
rc = splitCommandLineOption(vm, optionString, thisOptionLength, opts + *optIndex);
if (rc == J9VMDLLMAIN_OK) {
optionString += ++thisOptionLength;
optionsLength -= thisOptionLength;
*optIndex += 2;
if (*optIndex >= UT_MAX_OPTS - 1) {
PORT_ACCESS_FROM_JAVAVM(vm);
vaReportJ9VMCommandLineError(PORTLIB, "Maximum number of trace options exceeded - use a trace properties file");
rc = J9VMDLLMAIN_FAILED;
}
}
}
}
return rc;
}
/**
* Initialize the trace options from the defaults for the J9VM and any
* options that were passed through the incoming J9VMInitArgs.
*
* Returns them as newly allocated string key/value pairs in the even/odd elements of opts.
* The strings in opts will need to be freed.
*
* @param[in] vm pointer to the J9JavaVM
* @param[in] vmArgs a J9VMInitArgs
* @param[in,out] opts string key/value pairs
*
* @return return J9VMDLLMAIN_OK if success, otherwise failures
*/
static IDATA
initializeTraceOptions(J9JavaVM *vm, J9VMInitArgs *vmArgs, char *opts[])
{
IDATA xtraceIndex = 0;
char *optionString = NULL;
IDATA i = 0;
IDATA optionsLength = 0;
IDATA rc = J9VMDLLMAIN_OK;
JavaVMOption *options = vmArgs->actualVMArgs->options;
#define trace_option_helper(option) \
splitCommandLineOption(vm, option, LITERAL_STRLEN(option), opts + i)
/* set up the default options */
rc = trace_option_helper(UT_MAXIMAL_KEYWORD "=all{level1}");
i += 2;
if (J9VMDLLMAIN_FAILED != rc) {
rc = trace_option_helper(UT_EXCEPTION_KEYWORD "=j9mm{gclogger}");
i += 2;
}
/*
* Find all the trace options specified in the command line and pass
* them to the trace engine. Note that trace args are formatted forwards
* (left to right) so as to be consistent with dump.
*/
xtraceIndex = FIND_AND_CONSUME_ARG_FORWARD(vmArgs, OPTIONAL_LIST_MATCH, VMOPT_XTRACE, NULL);
/* A trace option has been set. We need to check if the level 2 trace points have been
* enabled yet and if not enable them *before* processing the users trace options.
* (If we switch on level 2 after doing the users options then they won't get the
* trace they selected but their selection + level 2.)
*/
if( xtraceIndex >= 0 && !checkAndSetL2EnabledFlag() ) {
rc = trace_option_helper(UT_MAXIMAL_KEYWORD "=all{level2}");
i += 2;
}
while (xtraceIndex >= 0) {
optionString = options[xtraceIndex].optionString;
optionsLength = strlen(optionString) - strlen(VMOPT_XTRACE);
if (optionsLength > 0) {
if (optionString[strlen(VMOPT_XTRACE)] == ':') {
if (--optionsLength > 0) {
optionString += strlen(VMOPT_XTRACE) + 1;
rc = processTraceOptionString(vm,opts,&i,optionString,optionsLength);
}
} else {
PORT_ACCESS_FROM_JAVAVM(vm);
vaReportJ9VMCommandLineError(PORTLIB, "Syntax error in -Xtrace, expecting \":\"; received \"%c\"", optionString[strlen(VMOPT_XTRACE)]);
rc = J9VMDLLMAIN_FAILED;
}
}
xtraceIndex = FIND_AND_CONSUME_NEXT_ARG_FORWARD(vmArgs, OPTIONAL_LIST_MATCH, VMOPT_XTRACE, NULL, xtraceIndex);
}
opts[i++] = NULL;
return rc;
#undef trace_option_helper
}
/*
* Utility function to split trace options strings into two parts and put them in
* the option name in opt[0] and the option value in opt[1]
* If there is no value to go with the name opt[1] will be null.
*/
static IDATA
splitCommandLineOption(J9JavaVM *vm, const char *optionString, IDATA optionLength, char *opt[])
{
PORT_ACCESS_FROM_JAVAVM(vm);
IDATA length;
/* Split option and copy into opt array */
for (length = 0; length < optionLength; length++) {
if (optionString[length] == '=') {
break;
}
}
opt[0] = j9mem_allocate_memory(length + 1, OMRMEM_CATEGORY_TRACE);
if (opt[0] == NULL) {
return J9VMDLLMAIN_FAILED;
}
memcpy(opt[0], optionString, length);
opt[0][length] = '\0';
if (length < optionLength &&
optionString[length + 1] != '\0' &&
optionString[length + 1] != ',') {
opt[1] = j9mem_allocate_memory(optionLength - length, OMRMEM_CATEGORY_TRACE);
if (opt[1] == NULL) {
return J9VMDLLMAIN_FAILED;
}
memcpy(opt[1], optionString + length + 1, optionLength - length - 1);
opt[1][optionLength - length - 1] = '\0';
} else {
opt[1] = NULL;
}
return J9VMDLLMAIN_OK;
}
/*
* Call back for OMR to set J9VM specific trace options.
*/
static omr_error_t
setJ9VMTraceOption(const OMR_VM *omr_vm, const char *optName, const char* optValue, BOOLEAN atRuntime)
{
int i = 0;
J9JavaVM* vm = (J9JavaVM*) omr_vm->_language_vm;
omr_error_t rc = OMR_ERROR_NONE;
IDATA optionNameLength = 0;
PORT_ACCESS_FROM_JAVAVM(vm);
optionNameLength = strlen(optName);
for (i=0; i!=NUMBER_OF_TRACE_OPTIONS; i++) {
if (optionNameLength == strlen(TRACE_OPTIONS[i].name) && j9_cmdla_stricmp(optName, (char *)TRACE_OPTIONS[i].name) == 0) {
if (atRuntime && ! TRACE_OPTIONS[i].runtimeModifiable) {
dbg_err_printf(1, PORTLIB, "<UT> Trace option %s cannot be configured at run-time."
" Configure it at start-up with the command-line or a properties file\n",optName);
rc = OMR_ERROR_ILLEGAL_ARGUMENT;
} else {
rc = TRACE_OPTIONS[i].optionFunction(vm,optValue,atRuntime);
}
break;
}
}
return rc;
}
static omr_error_t
reportTraceEvent(J9JavaVM *vm, J9VMThread *self, UDATA eventFlags)
{
PORT_ACCESS_FROM_JAVAVM(vm);
char * name = NULL;
UtThreadData **tempThr = NULL;
/*
* No global storage! - probably shutting down...
*/
if (vm->j9rasGlobalStorage == NULL) {
return OMR_ERROR_INTERNAL;
}
/*
* Find UTE thread slot inside VM thread structure
*/
tempThr = UT_THREAD_FROM_VM_THREAD(self);
switch (eventFlags) {
case J9RAS_TRACE_ON_THREAD_CREATE:
/*
* If this is the main thread initializing again, stop the initialization pseudo thread
*/
if ((self == vm->mainThread) && (*tempThr != NULL)) {
/* let trace engine know that threading is started up so it is safe to create it's trace write thread */
if (OMR_ERROR_NONE != startTraceWorkerThread(tempThr)) {
dbg_err_printf(1, PORTLIB, "<UT> Trace engine can't start trace thread\n");
return OMR_ERROR_INTERNAL;
}
if (OMR_ERROR_NONE != threadStop(tempThr)) {
dbg_err_printf(1, PORTLIB, "<UT> UTE thread stop failed for thread %p\n", self);
}
}
name = threadName(self->omrVMThread);
if (OMR_ERROR_NONE != threadStart(tempThr, self, name, self->osThread, self->omrVMThread)) {
dbg_err_printf(1, PORTLIB, "<UT> UTE thread start failed for thread %p\n", self);
}
Trc_trcengine_reportThreadStart(self, self, name, self->osThread);
if (name != NULL) {
j9mem_free_memory(name);
}
break;
case J9RAS_TRACE_ON_THREAD_END:
if (self == NULL || *tempThr == NULL) {
/* no point even trying - main thread probably encountered early problem */
break;
}
/*
* Use UTE cached name (don't de-allocate it!)
*/
name = (char *)(*tempThr)->name;
Trc_trcengine_reportThreadEnd(self, self, name, self->osThread);
if (OMR_ERROR_NONE != threadStop(tempThr)) {
dbg_err_printf(1, PORTLIB, "<UT> UTE thread stop failed for thread %p\n", self);
}
break;
default:
dbg_err_printf(1, PORTLIB, "<UT> Trace engine received an unknown trace event: [0x%04X]\n", eventFlags);
}
return OMR_ERROR_NONE;
}
static IDATA
parseTraceOptions(J9JavaVM *vm, const char *optionString, IDATA optionsLength)
{
IDATA length;
IDATA inBraces = 0;
for (length = 0; length < optionsLength; length++) {
if (optionString[length] == '{') {
inBraces++;
continue;
}
if (optionString[length] == '}') {
if (--inBraces < 0) {
break;
}
continue;
}
if (inBraces == 0 &&
optionString[length] == ',') {
break;
}
}
return inBraces == 0 ? length : -1;
}
static char *
threadName(OMR_VMThread* vmThread)
{
OMRPORT_ACCESS_FROM_OMRVMTHREAD(vmThread);
size_t nameLength = 0;
char *name = NULL;
char* allocatedName;
name = getOMRVMThreadName(vmThread);
nameLength = strlen(name);
allocatedName = omrmem_allocate_memory(nameLength + 1, OMRMEM_CATEGORY_TRACE);
if (allocatedName != NULL) {
strncpy(allocatedName, name, nameLength + 1);
}
releaseOMRVMThreadName(vmThread);
return allocatedName;
}
static void displayTraceHelp(J9JavaVM *vm)
{
PORT_ACCESS_FROM_JAVAVM(vm);
j9tty_err_printf("\nUsage:\n\n");
j9tty_err_printf(" java -Xtrace[:option,...]\n\n");
j9tty_err_printf(" Valid options are:\n\n");
j9tty_err_printf(" help Print general trace help\n");
j9tty_err_printf(" what Print current trace configuration\n");
j9tty_err_printf(" none[=tp_spec[,...]] Ignore all previous/default trace options\n");
j9tty_err_printf(" properties[=filespec] Use file for trace options\n");
j9tty_err_printf(" buffers=nnk|nnm|dynamic|nodynamic[,...] Buffer size and nature\n\n");
j9tty_err_printf(" minimal=[!]tp_spec[,...] Minimal trace data (time and id)\n");
j9tty_err_printf(" maximal=[!]tp_spec[,...] Time,id and parameters traced\n");
j9tty_err_printf(" count=[!]tp_spec[,...] Count tracepoints\n");
j9tty_err_printf(" print=[!]tp_spec[,...] Direct unindented trace data to stderr\n");
j9tty_err_printf(" iprint=[!]tp_spec[,...] Indented version of print option\n");
j9tty_err_printf(" external=[!]tp_spec[,...] Direct trace data to a JVMRI listener\n");
j9tty_err_printf(" exception=[!]tp_spec[,...] Use reserved in-core buffer\n");
j9tty_err_printf(" methods=method_spec[,..] Trace specified class(es) and methods\n\n");
j9tty_err_printf(" trigger=[!]clause[,clause]... Enables triggering events (including dumps) on tracepoints\n");
j9tty_err_printf(" suspend Global trace suspend used with trigger\n");
j9tty_err_printf(" resume Global trace resume used with trigger\n");
j9tty_err_printf(" suspendcount=nn Trigger count for \"trace suspend\"\n");
j9tty_err_printf(" resumecount=nn Trigger count for \"trace resume\"\n");
j9tty_err_printf(" output=filespec[,nnm[,generations]] Sends maximal and minimal trace to a file\n");
j9tty_err_printf(" exception.output=filespec[,nnnm] Sends exception trace to a file\n");
j9tty_err_printf(" maxstringlength=nn Limit length of string values to capture\n");
j9tty_err_printf(" "
"Maximum " J9_STR(RAS_MAX_STRING_LENGTH_LIMIT)
", use 0 to disable."
" Default: " J9_STR(RAS_MAX_STRING_LENGTH_DEFAULT) "\n");
j9tty_err_printf(" stackdepth=nn Set number of frames output by jstacktrace trigger action\n");
j9tty_err_printf(" sleeptime=nnt Time delay for sleep trigger action\n");
j9tty_err_printf(" Recognised suffixes: ms (milliseconds), s (seconds). Default: ms\n");
j9tty_err_printf("\n where tp_spec is, for example, j9vm.111 or {j9vm.111-114,j9trc.5}\n");
j9tty_err_printf("\n IMPORTANT: Where an option value contains one or more commas, it must\n");
j9tty_err_printf(" be enclosed in curly braces, for example:\n\n");
j9tty_err_printf(" -Xtrace:maximal={j9vm,mt},methods={*.*,!java/lang/*},output=trace\n");
j9tty_err_printf("\n You may need to enclose options in quotation marks to prevent the shell\n");
j9tty_err_printf(" intercepting and fragmenting comma-separated command lines, for example:\n\n");
j9tty_err_printf(" \"-Xtrace:methods={java/lang/*,java/util/*},print=mt\"\n\n");
}
static void
hookThreadAboutToStart(J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData)
{
J9VMThread* vmThread = ((J9ThreadAboutToStartEvent *)eventData)->vmThread;
reportTraceEvent(vmThread->javaVM, vmThread, J9RAS_TRACE_ON_THREAD_CREATE);
}
static void
hookThreadEnd(J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData)
{
J9VMThreadEndEvent* event = eventData;
J9VMThread* vmThread = event->currentThread;
if (event->destroyingJavaVM) {
/* don't report this event. We want this thread to survive in UTE until the VM has finished shutting down */
} else {
reportTraceEvent(vmThread->javaVM, vmThread, J9RAS_TRACE_ON_THREAD_END);
}
}
static void
hookVmInitialized(J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData)
{
J9VMThread* vmThread = ((J9VMInitEvent *)eventData)->vmThread;
vmThread->javaVM->internalVMFunctions->rasStartDeferredThreads(vmThread->javaVM);
}
static void
reportVMTermination(J9JavaVM* vm, J9VMThread * vmThread)
{
UtThreadData ** traceThread = UT_THREAD_FROM_VM_THREAD(vmThread);
if (traceThread && *traceThread) {
/* Threads that should be ignored when deciding if all tracing has finished. */
char *ignoreThreads[] = { "Finalizer", "Signal dispatcher", "JIT PProfiler thread", "Reference Handler", NULL };
utTerminateTrace(traceThread, ignoreThreads);
}
}
static void
requestTraceCleanup(J9JavaVM* vm, J9VMThread * vmThread)
{
UtThreadData ** traceThread = UT_THREAD_FROM_VM_THREAD(vmThread);