1 /*
2  * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
3  * Copyright (c) 2019, Google and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.
9  *
10  * This code is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * version 2 for more details (a copy is included in the LICENSE file that
14  * accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License version
17  * 2 along with this work; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21  * or visit www.oracle.com if you need additional information or have any
22  * questions.
23  */
24 
25 #include <assert.h>
26 #include <dlfcn.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include "jvmti.h"
31 
32 static jvmtiEnv* jvmti;
33 
34 template <class T>
35 class JvmtiDeallocator {
36  public:
JvmtiDeallocator()37   JvmtiDeallocator() {
38     elem_ = NULL;
39   }
40 
~JvmtiDeallocator()41   ~JvmtiDeallocator() {
42     jvmti->Deallocate(reinterpret_cast<unsigned char*>(elem_));
43   }
44 
get_addr()45   T* get_addr() {
46     return &elem_;
47   }
48 
get()49   T get() {
50     return elem_;
51   }
52 
53  private:
54   T elem_;
55 };
56 
GetJMethodIDs(jclass klass)57 static void GetJMethodIDs(jclass klass) {
58   jint method_count = 0;
59   JvmtiDeallocator<jmethodID*> methods;
60   jvmtiError err = jvmti->GetClassMethods(klass, &method_count, methods.get_addr());
61 
62   // If ever the GetClassMethods fails, just ignore it, it was worth a try.
63   if (err != JVMTI_ERROR_NONE) {
64     fprintf(stderr, "GetJMethodIDs: Error in GetClassMethods: %d\n", err);
65   }
66 }
67 
68 // AsyncGetCallTrace needs class loading events to be turned on!
OnClassLoad(jvmtiEnv * jvmti,JNIEnv * jni_env,jthread thread,jclass klass)69 static void JNICALL OnClassLoad(jvmtiEnv *jvmti, JNIEnv *jni_env,
70                                 jthread thread, jclass klass) {
71 }
72 
OnClassPrepare(jvmtiEnv * jvmti,JNIEnv * jni_env,jthread thread,jclass klass)73 static void JNICALL OnClassPrepare(jvmtiEnv *jvmti, JNIEnv *jni_env,
74                                    jthread thread, jclass klass) {
75   // We need to do this to "prime the pump" and get jmethodIDs primed.
76   GetJMethodIDs(klass);
77 }
78 
OnVMInit(jvmtiEnv * jvmti,JNIEnv * jni_env,jthread thread)79 static void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) {
80   jint class_count = 0;
81 
82   // Get any previously loaded classes that won't have gone through the
83   // OnClassPrepare callback to prime the jmethods for AsyncGetCallTrace.
84   JvmtiDeallocator<jclass*> classes;
85   jvmtiError err = jvmti->GetLoadedClasses(&class_count, classes.get_addr());
86   if (err != JVMTI_ERROR_NONE) {
87     fprintf(stderr, "OnVMInit: Error in GetLoadedClasses: %d\n", err);
88     return;
89   }
90 
91   // Prime any class already loaded and try to get the jmethodIDs set up.
92   jclass *classList = classes.get();
93   for (int i = 0; i < class_count; ++i) {
94     GetJMethodIDs(classList[i]);
95   }
96 }
97 
98 extern "C" {
99 
100 static
Agent_Initialize(JavaVM * jvm,char * options,void * reserved)101 jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
102   jint res = jvm->GetEnv((void **) &jvmti, JVMTI_VERSION);
103   if (res != JNI_OK || jvmti == NULL) {
104     fprintf(stderr, "Error: wrong result of a valid call to GetEnv!\n");
105     return JNI_ERR;
106   }
107 
108   jvmtiError err;
109   jvmtiCapabilities caps;
110   memset(&caps, 0, sizeof(caps));
111   caps.can_get_line_numbers = 1;
112   caps.can_get_source_file_name = 1;
113 
114   err = jvmti->AddCapabilities(&caps);
115   if (err != JVMTI_ERROR_NONE) {
116     fprintf(stderr, "AgentInitialize: Error in AddCapabilities: %d\n", err);
117     return JNI_ERR;
118   }
119 
120   jvmtiEventCallbacks callbacks;
121   memset(&callbacks, 0, sizeof(callbacks));
122   callbacks.ClassLoad = &OnClassLoad;
123   callbacks.VMInit = &OnVMInit;
124   callbacks.ClassPrepare = &OnClassPrepare;
125 
126   err = jvmti->SetEventCallbacks(&callbacks, sizeof(jvmtiEventCallbacks));
127   if (err != JVMTI_ERROR_NONE) {
128     fprintf(stderr, "AgentInitialize: Error in SetEventCallbacks: %d\n", err);
129     return JNI_ERR;
130   }
131 
132   err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
133   if (err != JVMTI_ERROR_NONE) {
134     fprintf(stderr, "AgentInitialize: Error in SetEventNotificationMode for CLASS_LOAD: %d\n", err);
135     return JNI_ERR;
136   }
137 
138   err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
139   if (err != JVMTI_ERROR_NONE) {
140     fprintf(stderr,
141             "AgentInitialize: Error in SetEventNotificationMode for CLASS_PREPARE: %d\n",
142             err);
143     return JNI_ERR;
144   }
145 
146   err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
147   if (err != JVMTI_ERROR_NONE) {
148     fprintf(
149         stderr, "AgentInitialize: Error in SetEventNotificationMode for VM_INIT: %d\n",
150         err);
151     return JNI_ERR;
152   }
153 
154   return JNI_OK;
155 }
156 
157 JNIEXPORT
Agent_OnLoad(JavaVM * jvm,char * options,void * reserved)158 jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
159   return Agent_Initialize(jvm, options, reserved);
160 }
161 
162 JNIEXPORT
Agent_OnAttach(JavaVM * jvm,char * options,void * reserved)163 jint JNICALL Agent_OnAttach(JavaVM *jvm, char *options, void *reserved) {
164   return Agent_Initialize(jvm, options, reserved);
165 }
166 
167 JNIEXPORT
JNI_OnLoad(JavaVM * jvm,void * reserved)168 jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
169   return JNI_VERSION_1_8;
170 }
171 
172 // A copy of the ASGCT data structures.
173 typedef struct {
174     jint lineno;                      // line number in the source file
175     jmethodID method_id;              // method executed in this frame
176 } ASGCT_CallFrame;
177 
178 typedef struct {
179     JNIEnv *env_id;                   // Env where trace was recorded
180     jint num_frames;                  // number of frames in this trace
181     ASGCT_CallFrame *frames;          // frames
182 } ASGCT_CallTrace;
183 
184 typedef void (*ASGCTType)(ASGCT_CallTrace *, jint, void *);
185 
186 JNIEXPORT jboolean JNICALL
Java_MyPackage_ASGCTBaseTest_checkAsyncGetCallTraceCall(JNIEnv * env,jclass cls)187 Java_MyPackage_ASGCTBaseTest_checkAsyncGetCallTraceCall(JNIEnv* env, jclass cls) {
188   ASGCTType agct = reinterpret_cast<ASGCTType>(dlsym(RTLD_DEFAULT, "AsyncGetCallTrace"));
189 
190   const int MAX_DEPTH = 16;
191   ASGCT_CallTrace trace;
192   ASGCT_CallFrame frames[MAX_DEPTH];
193   trace.frames = frames;
194   trace.env_id = env;
195   trace.num_frames = 0;
196 
197   if (agct == NULL) {
198     fprintf(stderr, "AsyncGetCallTrace not found.\n");
199     return false;
200   }
201 
202   agct(&trace, MAX_DEPTH, NULL);
203 
204   // For now, just check that the first frame is (-3, checkAsyncGetCallTraceCall).
205   if (trace.num_frames <= 0) {
206     fprintf(stderr, "The num_frames must be positive: %d\n", trace.num_frames);
207     return false;
208   }
209 
210   // AsyncGetCallTrace returns -3 as line number for a native frame.
211   if (trace.frames[0].lineno != -3) {
212     fprintf(stderr, "lineno is not -3 as expected: %d\n", trace.frames[0].lineno);
213     return false;
214   }
215 
216   JvmtiDeallocator<char*> name;
217   if (trace.frames[0].method_id == NULL) {
218     fprintf(stderr, "First frame method_id is NULL\n");
219     return false;
220   }
221 
222   jvmtiError err = jvmti->GetMethodName(trace.frames[0].method_id, name.get_addr(), NULL, NULL);
223   if (err != JVMTI_ERROR_NONE) {
224     fprintf(stderr, "checkAsyncGetCallTrace: Error in GetMethodName: %d\n", err);
225     return false;
226   }
227 
228   if (name.get() == NULL) {
229     fprintf(stderr, "Name is NULL\n");
230     return false;
231   }
232 
233   return strcmp(name.get(), "checkAsyncGetCallTraceCall") == 0;
234 }
235 
236 }
237