1 /*
2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 #include <string.h>
25 #include "jvmti.h"
26 #include "agent_common.h"
27 #include "jni_tools.h"
28 #include "jvmti_tools.h"
29 
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33 
34 /* ============================================================================= */
35 
36 /* scaffold objects */
37 static JNIEnv* jni = NULL;
38 static jvmtiEnv *jvmti = NULL;
39 static jlong timeout = 0;
40 
41 /* constants */
42 #define THREADS_COUNT   6
43 #define MAX_NAME_LENGTH 100
44 #define MAX_STACK_SIZE  100
45 
46 /* thread description structure */
47 typedef struct {
48     char threadName[MAX_NAME_LENGTH];
49     char methodName[MAX_NAME_LENGTH];
50     char methodSig[MAX_NAME_LENGTH];
51     jthread thread;
52     jclass cls;
53     jmethodID method;
54     jlocation location;
55 } ThreadDesc;
56 
57 /* descriptions of tested threads */
58 static ThreadDesc threadsDesc[THREADS_COUNT] = {
59     {"threadRunning", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION},
60     {"threadEntering", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION},
61     {"threadWaiting", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION},
62     {"threadSleeping", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION},
63     {"threadRunningInterrupted", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION},
64     {"threadRunningNative", "testedMethod", "()V", NULL, NULL, NULL, NSK_JVMTI_INVALID_JLOCATION}
65 };
66 
67 /* indexes of known threads */
68 static const int interruptedThreadIndex = THREADS_COUNT - 2;
69 static const int nativeThreadIndex = THREADS_COUNT - 1;
70 
71 /* ============================================================================= */
72 
73 /* testcase(s) */
74 static int prepare();
75 static int checkThreads(int suspended, const char* kind);
76 static int suspendThreadsIndividually(int suspend);
77 static int clean();
78 
79 /* ============================================================================= */
80 
81 /** Agent algorithm. */
82 static void JNICALL
agentProc(jvmtiEnv * jvmti,JNIEnv * agentJNI,void * arg)83 agentProc(jvmtiEnv* jvmti, JNIEnv* agentJNI, void* arg) {
84     jni = agentJNI;
85 
86     /* wait for initial sync */
87     if (!nsk_jvmti_waitForSync(timeout))
88         return;
89 
90     /* perform testcase(s) */
91     {
92         /* prepare data: find threads */
93         NSK_DISPLAY0("Prepare data\n");
94         if (!prepare()) {
95             nsk_jvmti_setFailStatus();
96             return;
97         }
98 
99         /* testcase #1: check not suspended threads */
100         NSK_DISPLAY0("Testcase #1: check stack frames of not suspended threads\n");
101         if (!checkThreads(NSK_FALSE, "not suspended"))
102             return;
103 
104         /* suspend threads */
105         NSK_DISPLAY0("Suspend each thread\n");
106         if (!suspendThreadsIndividually(NSK_TRUE))
107             return;
108 
109         /* testcase #2: check suspended threads */
110         NSK_DISPLAY0("Testcase #2: check stack frames of suspended threads\n");
111         if (!checkThreads(NSK_TRUE, "suspended"))
112             return;
113 
114         /* resume threads */
115         NSK_DISPLAY0("Resume each thread\n");
116         if (!suspendThreadsIndividually(NSK_FALSE))
117             return;
118 
119         /* testcase #3: check resumed threads */
120         NSK_DISPLAY0("Testcase #3: check stack frames of resumed threads\n");
121         if (!checkThreads(NSK_FALSE, "resumed"))
122             return;
123 
124         /* clean date: delete threads references */
125         NSK_DISPLAY0("Clean data\n");
126         if (!clean()) {
127             nsk_jvmti_setFailStatus();
128             return;
129         }
130     }
131 
132     /* resume debugee after last sync */
133     if (!nsk_jvmti_resumeSync())
134         return;
135 }
136 
137 /* ============================================================================= */
138 
139 /**
140  * Prepare data:
141  *    - clean threads list
142  *    - get all live threads
143  *    - get threads name
144  *    - find tested threads
145  *    - make global refs
146  */
prepare()147 static int prepare() {
148     jthread *allThreadsList = NULL;
149     jint allThreadsCount = 0;
150     int found = 0;
151     int i;
152 
153     NSK_DISPLAY1("Find tested threads: %d\n", THREADS_COUNT);
154 
155     /* clean threads list */
156     for (i = 0; i < THREADS_COUNT; i++) {
157         threadsDesc[i].thread = (jthread)NULL;
158         threadsDesc[i].method = (jmethodID)NULL;
159         threadsDesc[i].location = NSK_JVMTI_INVALID_JLOCATION;
160     }
161 
162     /* get all live threads */
163     if (!NSK_JVMTI_VERIFY(
164             NSK_CPP_STUB3(GetAllThreads, jvmti, &allThreadsCount, &allThreadsList)))
165         return NSK_FALSE;
166 
167     if (!NSK_VERIFY(allThreadsCount > 0 && allThreadsList != NULL))
168         return NSK_FALSE;
169 
170     /* find tested threads */
171     for (i = 0; i < allThreadsCount; i++) {
172         jvmtiThreadInfo threadInfo;
173 
174         if (!NSK_VERIFY(allThreadsList[i] != NULL))
175             return NSK_FALSE;
176 
177         /* get thread name (info) */
178         if (!NSK_JVMTI_VERIFY(
179                 NSK_CPP_STUB3(GetThreadInfo, jvmti, allThreadsList[i], &threadInfo)))
180             return NSK_FALSE;
181 
182         /* find by name */
183         if (threadInfo.name != NULL) {
184             int j;
185 
186             for (j = 0; j < THREADS_COUNT; j++) {
187                 if (strcmp(threadInfo.name, threadsDesc[j].threadName) == 0) {
188                     threadsDesc[j].thread = allThreadsList[i];
189                     NSK_DISPLAY3("    thread #%d (%s): %p\n",
190                                             j, threadInfo.name, (void*)threadsDesc[j].thread);
191                 }
192             }
193         }
194     }
195 
196     /* deallocate all threads list */
197     if (!NSK_JVMTI_VERIFY(
198             NSK_CPP_STUB2(Deallocate, jvmti, (unsigned char*)allThreadsList)))
199         return NSK_FALSE;
200 
201     /* check if all tested threads found */
202     found = 0;
203     for (i = 0; i < THREADS_COUNT; i++) {
204         if (threadsDesc[i].thread == NULL) {
205             NSK_COMPLAIN2("Not found tested thread #%d (%s)\n", i, threadsDesc[i].threadName);
206         } else {
207             found++;
208         }
209     }
210 
211     if (found < THREADS_COUNT)
212         return NSK_FALSE;
213 
214     /* get threads class and frame method */
215     NSK_DISPLAY0("Find tested methods:\n");
216     for (i = 0; i < THREADS_COUNT; i++) {
217         /* get thread class */
218         if (!NSK_JNI_VERIFY(jni, (threadsDesc[i].cls =
219                 NSK_CPP_STUB2(GetObjectClass, jni, threadsDesc[i].thread)) != NULL))
220             return NSK_FALSE;
221         /* get frame method */
222         if (!NSK_JNI_VERIFY(jni, (threadsDesc[i].method =
223                 NSK_CPP_STUB4(GetMethodID, jni, threadsDesc[i].cls,
224                             threadsDesc[i].methodName, threadsDesc[i].methodSig)) != NULL))
225             return NSK_FALSE;
226 
227         NSK_DISPLAY4("    thread #%d (%s): %p (%s)\n",
228                                 i, threadsDesc[i].threadName,
229                                 (void*)threadsDesc[i].method,
230                                 threadsDesc[i].methodName);
231     }
232 
233     /* make global refs */
234     for (i = 0; i < THREADS_COUNT; i++) {
235         if (!NSK_JNI_VERIFY(jni, (threadsDesc[i].thread = (jthread)
236                 NSK_CPP_STUB2(NewGlobalRef, jni, threadsDesc[i].thread)) != NULL))
237             return NSK_FALSE;
238         if (!NSK_JNI_VERIFY(jni, (threadsDesc[i].cls = (jclass)
239                 NSK_CPP_STUB2(NewGlobalRef, jni, threadsDesc[i].cls)) != NULL))
240             return NSK_FALSE;
241     }
242 
243     return NSK_TRUE;
244 }
245 
246 /**
247  * Suspend or resume tested threads.
248  */
suspendThreadsIndividually(int suspend)249 static int suspendThreadsIndividually(int suspend) {
250     int i;
251 
252     for (i = 0; i < THREADS_COUNT; i++) {
253         if (suspend) {
254             NSK_DISPLAY2("    suspend thread #%d (%s)\n", i, threadsDesc[i].threadName);
255             if (!NSK_JVMTI_VERIFY(
256                     NSK_CPP_STUB2(SuspendThread, jvmti, threadsDesc[i].thread)))
257                 nsk_jvmti_setFailStatus();
258         } else {
259             NSK_DISPLAY2("    resume thread #%d (%s)\n", i, threadsDesc[i].threadName);
260             if (!NSK_JVMTI_VERIFY(
261                     NSK_CPP_STUB2(ResumeThread, jvmti, threadsDesc[i].thread)))
262                 nsk_jvmti_setFailStatus();
263         }
264     }
265     return NSK_TRUE;
266 }
267 
268 /**
269  * Testcase: check tested threads
270  *    - call GetFrameCount() and getStackTrace()
271  *    - compare numbers of stack frame returned
272  *    - find stck frane with expected methodID
273  *
274  * Returns NSK_TRUE if test may continue; or NSK_FALSE for test break.
275  */
checkThreads(int suspended,const char * kind)276 static int checkThreads(int suspended, const char* kind) {
277     int i;
278 
279     /* check each thread */
280     for (i = 0; i < THREADS_COUNT; i++) {
281         jint frameCount = 0;
282         jint frameStackSize = 0;
283         jvmtiFrameInfo frameStack[MAX_STACK_SIZE];
284         int found = 0;
285         int j;
286 
287         NSK_DISPLAY2("  thread #%d (%s):\n", i, threadsDesc[i].threadName);
288 
289         /* get frame count */
290         if (!NSK_JVMTI_VERIFY(
291                 NSK_CPP_STUB3(GetFrameCount, jvmti,
292                                     threadsDesc[i].thread, &frameCount))) {
293             nsk_jvmti_setFailStatus();
294             return NSK_TRUE;
295         }
296 
297         NSK_DISPLAY1("    frameCount:  %d\n", (int)frameCount);
298 
299         /* get stack trace */
300         if (!NSK_JVMTI_VERIFY(
301                 NSK_CPP_STUB6(GetStackTrace, jvmti, threadsDesc[i].thread,
302                                     0, MAX_STACK_SIZE, frameStack, &frameStackSize))) {
303             nsk_jvmti_setFailStatus();
304             return NSK_TRUE;
305         }
306 
307         NSK_DISPLAY1("    stack depth: %d\n", (int)frameStackSize);
308 
309         /* check stack size */
310         if (frameStackSize < frameCount) {
311             NSK_COMPLAIN5("Too small stack of %s thread #%d (%s):\n"
312                             "#   got ctack frames:  %d\n"
313                             "#   got framesCount:   %d\n",
314                             kind, i, threadsDesc[i].threadName,
315                             (int)frameStackSize, (int)frameCount);
316             nsk_jvmti_setFailStatus();
317         }
318 
319         /* find method on the stack */
320         found = 0;
321         for (j = 0; j < frameStackSize; j++) {
322             NSK_DISPLAY3("      %d: methodID: %p, location: %ld\n",
323                                         j, (void*)frameStack[j].method,
324                                         (long)frameStack[j].location);
325             /* check frame method */
326             if (frameStack[j].method == NULL) {
327                 NSK_COMPLAIN3("NULL methodID in stack for %s thread #%d (%s)\n",
328                             kind, i, threadsDesc[i].threadName);
329                 nsk_jvmti_setFailStatus();
330             } else if (frameStack[j].method == threadsDesc[i].method) {
331                 found++;
332                 NSK_DISPLAY1("        found expected method: %s\n",
333                                                 (void*)threadsDesc[i].methodName);
334             }
335         }
336 
337         /* check if expected method found */
338         if (found != 1) {
339             NSK_COMPLAIN5("Unexpected method frames on stack for %s thread #%d (%s):\n"
340                             "#   found frames:  %d\n"
341                             "#   expected:      %d\n",
342                             kind, i, threadsDesc[i].threadName,
343                             found, 1);
344             nsk_jvmti_setFailStatus();
345         }
346     }
347 
348     /* test may continue */
349     return NSK_TRUE;
350 }
351 
352 /**
353  * Clean data:
354  *   - dispose global references to tested threads
355  */
clean()356 static int clean() {
357     int i;
358 
359     /* dispose global references to threads */
360     for (i = 0; i < THREADS_COUNT; i++) {
361         NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni, threadsDesc[i].thread));
362         NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni, threadsDesc[i].cls));
363     }
364 
365     return NSK_TRUE;
366 }
367 
368 /* ============================================================================= */
369 
370 static volatile int testedThreadRunning = NSK_FALSE;
371 static volatile int testedThreadShouldFinish = NSK_FALSE;
372 
373 /** Native running method in tested thread. */
374 JNIEXPORT void JNICALL
Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_testedMethod(JNIEnv * jni,jobject obj)375 Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_testedMethod(JNIEnv* jni,
376                                                                                 jobject obj) {
377     volatile int i = 0, n = 1000;
378 
379     /* run in a loop */
380     testedThreadRunning = NSK_TRUE;
381     while (!testedThreadShouldFinish) {
382         if (n <= 0)
383             n = 1000;
384         if (i >= n)
385             i = 0;
386         i++;
387     }
388     testedThreadRunning = NSK_FALSE;
389 }
390 
391 /** Wait for native method is running. */
392 JNIEXPORT jboolean JNICALL
Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_checkReady(JNIEnv * jni,jobject obj)393 Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_checkReady(JNIEnv* jni,
394                                                                             jobject obj) {
395     while (!testedThreadRunning) {
396         nsk_jvmti_sleep(1000);
397     }
398     return testedThreadRunning ? JNI_TRUE : JNI_FALSE;
399 }
400 
401 /** Let native method to finish. */
402 JNIEXPORT void JNICALL
Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_letFinish(JNIEnv * jni,jobject obj)403 Java_nsk_jvmti_scenarios_sampling_SP02_sp02t002ThreadRunningNative_letFinish(JNIEnv* jni,
404                                                                             jobject obj) {
405     testedThreadShouldFinish = NSK_TRUE;
406 }
407 
408 /* ============================================================================= */
409 
410 /** Agent library initialization. */
411 #ifdef STATIC_BUILD
Agent_OnLoad_sp02t002(JavaVM * jvm,char * options,void * reserved)412 JNIEXPORT jint JNICALL Agent_OnLoad_sp02t002(JavaVM *jvm, char *options, void *reserved) {
413     return Agent_Initialize(jvm, options, reserved);
414 }
Agent_OnAttach_sp02t002(JavaVM * jvm,char * options,void * reserved)415 JNIEXPORT jint JNICALL Agent_OnAttach_sp02t002(JavaVM *jvm, char *options, void *reserved) {
416     return Agent_Initialize(jvm, options, reserved);
417 }
JNI_OnLoad_sp02t002(JavaVM * jvm,char * options,void * reserved)418 JNIEXPORT jint JNI_OnLoad_sp02t002(JavaVM *jvm, char *options, void *reserved) {
419     return JNI_VERSION_1_8;
420 }
421 #endif
Agent_Initialize(JavaVM * jvm,char * options,void * reserved)422 jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
423 
424     /* init framework and parse options */
425     if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
426         return JNI_ERR;
427 
428     timeout = nsk_jvmti_getWaitTime() * 60 * 1000;
429 
430     /* create JVMTI environment */
431     if (!NSK_VERIFY((jvmti =
432             nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
433         return JNI_ERR;
434 
435     /* add specific capabilities for suspending thread */
436     {
437         jvmtiCapabilities suspendCaps;
438         memset(&suspendCaps, 0, sizeof(suspendCaps));
439         suspendCaps.can_suspend = 1;
440         if (!NSK_JVMTI_VERIFY(
441                 NSK_CPP_STUB2(AddCapabilities, jvmti, &suspendCaps)))
442             return JNI_ERR;
443     }
444 
445     /* register agent proc and arg */
446     if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL)))
447         return JNI_ERR;
448 
449     return JNI_OK;
450 }
451 
452 /* ============================================================================= */
453 
454 #ifdef __cplusplus
455 }
456 #endif
457