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 extern "C" {
  31 
  32 /* ============================================================================= */
  33 
  34 /* scaffold objects */
  35 static JNIEnv* jni = NULL;
  36 static jvmtiEnv *jvmti = NULL;
  37 static jlong timeout = 0;
  38 
  39 /* number of tested threads */
  40 #define THREADS_KINDS           6
  41 #define DEFAULT_THREADS_NUMBER  1
  42 
  43 /* names of tested threads */
  44 static const char* threadsName[THREADS_KINDS] = {
  45     "ThreadRunning",
  46     "ThreadEntering",
  47     "ThreadWaiting",
  48     "ThreadSleeping",
  49     "ThreadRunningInterrupted",
  50     "ThreadRunningNative"
  51 };
  52 
  53 /* expected states of tested threads */
  54 #define JVMTI_THREAD_STATE_NOT_STARTED 0
  55 static jint threadsStatus[THREADS_KINDS] = {
  56     JVMTI_THREAD_STATE_RUNNABLE,
  57     JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER,
  58     JVMTI_THREAD_STATE_IN_OBJECT_WAIT,
  59     JVMTI_THREAD_STATE_SLEEPING,
  60     JVMTI_THREAD_STATE_RUNNABLE,
  61     JVMTI_THREAD_STATE_RUNNABLE
  62 };
  63 
  64 /* references to tested threads */
  65 static jthread* threadsList[THREADS_KINDS];
  66 static int threadsCounts[THREADS_KINDS];
  67 static int threadsCount = 0;
  68 
  69 /* indexes of known threads */
  70 static const int interruptedThreadIndex = THREADS_KINDS - 2;
  71 static const int nativeThreadIndex = THREADS_KINDS - 1;
  72 
  73 /* ============================================================================= */
  74 
  75 /* testcase(s) */
  76 static int prepare();
  77 static int checkThreads(int suspended, const char* kind, jlong timeout);
  78 static int suspendThreadsList(int suspend);
  79 static int suspendThreadsIndividually(int suspend);
  80 static int clean();
  81 
  82 /* ============================================================================= */
  83 
  84 /** Agent algorithm. */
  85 static void JNICALL
  86 agentProc(jvmtiEnv* jvmti, JNIEnv* agentJNI, void* arg) {
  87     jni = agentJNI;
  88 
  89     /* get JNI environment for agent thread */
  90     jni = nsk_jvmti_getAgentJNIEnv();
  91 
  92     /* wait for initial sync */
  93     if (!nsk_jvmti_waitForSync(timeout))
  94         return;
  95 
  96     /* perform testcase(s) */
  97     {
  98         /* prepare data: find threads */
  99         if (!prepare()) {
 100             nsk_jvmti_setFailStatus();
 101             return;
 102         }
 103 
 104         /* testcase #1: check not suspended threads */
 105         NSK_DISPLAY0("Testcase #1: check state of not suspended threads\n");
 106         if (!checkThreads(NSK_FALSE, "not suspended", timeout))
 107             return;
 108 
 109         /* suspend threads */
 110         NSK_DISPLAY0("Suspend threads list\n");
 111         if (!suspendThreadsList(NSK_TRUE))
 112             return;
 113 
 114         /* testcase #2: check suspended threads */
 115         NSK_DISPLAY0("Testcase #2: check state of suspended threads\n");
 116         if (!checkThreads(NSK_TRUE, "suspended", 0))
 117             return;
 118 
 119         /* resume threads */
 120         NSK_DISPLAY0("Resume threads individually\n");
 121         if (!suspendThreadsIndividually(NSK_FALSE))
 122             return;
 123 
 124         /* testcase #3: check resumed threads */
 125         NSK_DISPLAY0("Testcase #3: check state of resumed threads\n");
 126         if (!checkThreads(NSK_FALSE, "resumed", 0))
 127             return;
 128 
 129         /* clean date: delete threads references */
 130         if (!clean()) {
 131             nsk_jvmti_setFailStatus();
 132             return;
 133         }
 134     }
 135 
 136     /* resume debugee after last sync */
 137     if (!nsk_jvmti_resumeSync())
 138         return;
 139 }
 140 
 141 /* ============================================================================= */
 142 
 143 /**
 144  * Prepare data:
 145  *    - clean threads list
 146  *    - get all live threads
 147  *    - get threads name
 148  *    - find tested threads
 149  *    - make global refs
 150  */
 151 static int prepare() {
 152     jthread *allThreadsList = NULL;
 153     jint allThreadsCount = 0;
 154     int notfound = 0;
 155     int i, j;
 156 
 157     NSK_DISPLAY1("Prepare: find tested threads: %d kinds\n", THREADS_KINDS);
 158 
 159     /* allocate and clean threads list */
 160     for (i = 0; i < THREADS_KINDS; i++) {
 161         threadsCounts[i] = 0;
 162         threadsList[i] = NULL;
 163 
 164         if (!NSK_JVMTI_VERIFY(
 165                 NSK_CPP_STUB3(Allocate, jvmti, (threadsCount * sizeof(jthread)),
 166                                                     (unsigned char**)&threadsList[i])))
 167             return NSK_FALSE;
 168 
 169         for (j = 0; j < threadsCount; j++) {
 170             threadsList[i][j] = NULL;
 171         }
 172     }
 173 
 174     /* get all live threads */
 175     if (!NSK_JVMTI_VERIFY(
 176             NSK_CPP_STUB3(GetAllThreads, jvmti, &allThreadsCount, &allThreadsList)))
 177         return NSK_FALSE;
 178 
 179     if (!NSK_VERIFY(allThreadsCount > 0 && allThreadsList != NULL))
 180         return NSK_FALSE;
 181 
 182     /* find tested threads */
 183     for (i = 0; i < allThreadsCount; i++) {
 184         jvmtiThreadInfo threadInfo;
 185 
 186         if (!NSK_VERIFY(allThreadsList[i] != NULL))
 187             return NSK_FALSE;
 188 
 189         /* get thread name (info) */
 190         if (!NSK_JVMTI_VERIFY(
 191                 NSK_CPP_STUB3(GetThreadInfo, jvmti, allThreadsList[i], &threadInfo)))
 192             return NSK_FALSE;
 193 
 194         /* find by name */
 195         if (threadInfo.name != NULL) {
 196             for (j = 0; j < THREADS_KINDS; j++) {
 197                 if (strcmp(threadInfo.name, threadsName[j]) == 0) {
 198                     int k = threadsCounts[j];
 199                     if (k < threadsCount)
 200                         threadsList[j][k] = allThreadsList[i];
 201                     threadsCounts[j]++;
 202                 }
 203             }
 204         }
 205     }
 206 
 207     /* deallocate all threads list */
 208     if (!NSK_JVMTI_VERIFY(
 209             NSK_CPP_STUB2(Deallocate, jvmti, (unsigned char*)allThreadsList)))
 210         return NSK_FALSE;
 211 
 212     /* check if all tested threads found */
 213     notfound = 0;
 214     for (i = 0; i < THREADS_KINDS; i++) {
 215         if (threadsCounts[i] != threadsCount) {
 216             NSK_COMPLAIN3("Found unexpected number of tested threads (%s):\n"
 217                             "#   found:    %d\n"
 218                             "#   expected: %d\n",
 219                             threadsName[i], threadsCounts[i], threadsCount);
 220             nsk_jvmti_setFailStatus();
 221             notfound++;
 222         }
 223     }
 224 
 225     if (notfound > 0)
 226         return NSK_FALSE;
 227 
 228     /* make global refs */
 229     for (i = 0; i < THREADS_KINDS; i++) {
 230         for (j = 0; j < threadsCount; j++) {
 231             if (!NSK_JNI_VERIFY(jni, (threadsList[i][j] =
 232                     NSK_CPP_STUB2(NewGlobalRef, jni, threadsList[i][j])) != NULL))
 233                 return NSK_FALSE;
 234         }
 235     }
 236 
 237     return NSK_TRUE;
 238 }
 239 
 240 /**
 241  * Suspend or resume tested threads list.
 242  */
 243 static int suspendThreadsList(int suspend) {
 244     jlong resultsSize = threadsCount * sizeof(jvmtiError);
 245     jvmtiError* results = NULL;
 246     const char* kind = (suspend ? "suspending" : "resuming");
 247     int i, j;
 248 
 249     /* allocate results array */
 250     if (!NSK_JVMTI_VERIFY(
 251             NSK_CPP_STUB3(Allocate, jvmti, resultsSize, (unsigned char**)&results))) {
 252         nsk_jvmti_setFailStatus();
 253         return NSK_FALSE;
 254     }
 255 
 256     for (i = 0; i < THREADS_KINDS; i++) {
 257         /* suspend or resume threads list */
 258         if (suspend) {
 259             if (!NSK_JVMTI_VERIFY(
 260                     NSK_CPP_STUB4(SuspendThreadList, jvmti, threadsCount,
 261                                                         threadsList[i], results)))
 262                 nsk_jvmti_setFailStatus();
 263         } else {
 264             if (!NSK_JVMTI_VERIFY(
 265                     NSK_CPP_STUB4(ResumeThreadList, jvmti, threadsCount,
 266                                                         threadsList[i], results)))
 267                 nsk_jvmti_setFailStatus();
 268         }
 269 
 270         /* check results */
 271         for (j = 0; j < threadsCount; j++) {
 272             if (results[j] != JVMTI_ERROR_NONE) {
 273                 NSK_COMPLAIN5("Unexpected result of %s thread #%d (%s):\n"
 274                                 "#   got result: %s (%d)\n",
 275                                 kind, j, threadsName[i],
 276                                 TranslateError(results[j]), (int)results[j]);
 277                 nsk_jvmti_setFailStatus();
 278             }
 279         }
 280     }
 281 
 282     /* deallocate results array */
 283     if (!NSK_JVMTI_VERIFY(
 284             NSK_CPP_STUB2(Deallocate, jvmti, (unsigned char*)results))) {
 285         nsk_jvmti_setFailStatus();
 286     }
 287 
 288     return NSK_TRUE;
 289 }
 290 
 291 /**
 292  * Suspend or resume tested threads individually.
 293  */
 294 static int suspendThreadsIndividually(int suspend) {
 295     int i, j;
 296 
 297     for (i = 0; i < THREADS_KINDS; i++) {
 298         for (j = 0; j < threadsCount; j++) {
 299             if (suspend) {
 300                 NSK_DISPLAY2("    suspend thread #%d (%s)\n", j, threadsName[i]);
 301                 if (!NSK_JVMTI_VERIFY(
 302                         NSK_CPP_STUB2(SuspendThread, jvmti, threadsList[i][j])))
 303                     nsk_jvmti_setFailStatus();
 304             } else {
 305                 NSK_DISPLAY2("    resume thread #%d (%s)\n", j, threadsName[i]);
 306                 if (!NSK_JVMTI_VERIFY(
 307                         NSK_CPP_STUB2(ResumeThread, jvmti, threadsList[i][j])))
 308                     nsk_jvmti_setFailStatus();
 309             }
 310         }
 311     }
 312     return NSK_TRUE;
 313 }
 314 
 315 /**
 316  * Testcase: check tested threads
 317  *    - get thread state and state
 318  *    - wait for WAITIME if state is not expected
 319  *    - check if thread state is as expected
 320  *
 321  * Returns NSK_TRUE if test may continue; or NSK_FALSE for test break.
 322  */
 323 static int checkThreads(int suspended, const char* kind, jlong timeout) {
 324     int i, j;
 325 
 326     /* check each thread */
 327     for (i = 0; i < THREADS_KINDS; i++) {
 328         for (j = 0; j < threadsCount; j++) {
 329             jint state = JVMTI_THREAD_STATE_NOT_STARTED;
 330             jlong t = 0;
 331 
 332             NSK_DISPLAY2("    thread #%d (%s):\n", j, threadsName[i]);
 333 
 334             /* get thread state */
 335             if (!NSK_JVMTI_VERIFY(
 336                     NSK_CPP_STUB3(GetThreadState, jvmti, threadsList[i][j], &state))) {
 337                 nsk_jvmti_setFailStatus();
 338                 return NSK_FALSE;
 339             }
 340 
 341             NSK_DISPLAY2("        state  = %s (%d)\n",
 342                                         TranslateState(state), (int)state);
 343 
 344             /* check SUSPENDED state */
 345             if (suspended) {
 346                 if (!(state & JVMTI_THREAD_STATE_SUSPENDED)) {
 347                     NSK_COMPLAIN5("No SUSPENDED state for %s thread #%d (%s):\n"
 348                                     "#    got flags: %s (%d)\n",
 349                                     kind, j, threadsName[i],
 350                                     TranslateState(state), (int)state);
 351                     nsk_jvmti_setFailStatus();
 352                 }
 353             } else {
 354                 if (state & JVMTI_THREAD_STATE_SUSPENDED) {
 355                     NSK_COMPLAIN5("Unexpected SUSPENDED state for %s thread #%d (%s):\n"
 356                                     "#   got flags: %s (%d)\n",
 357                                     kind, j, threadsName[i],
 358                                     TranslateState(state), (int)state);
 359                     nsk_jvmti_setFailStatus();
 360                 }
 361             }
 362         }
 363     }
 364 
 365     /* test may continue */
 366     return NSK_TRUE;
 367 }
 368 
 369 /**
 370  * Clean data:
 371  *   - dispose global references to tested threads
 372  */
 373 static int clean() {
 374     int i, j;
 375 
 376     /* dispose global references to threads */
 377     for (i = 0; i < THREADS_KINDS; i++) {
 378         for (j = 0; j < threadsCount; j++) {
 379             NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni, threadsList[i][j]));
 380         }
 381     }
 382 
 383     /* deallocate memory */
 384     for (i = 0; i < THREADS_KINDS; i++) {
 385         if (!NSK_JVMTI_VERIFY(
 386                 NSK_CPP_STUB2(Deallocate, jvmti, (unsigned char*)threadsList[i])))
 387             return NSK_FALSE;
 388         threadsList[i] = NULL;
 389     }
 390 
 391     return NSK_TRUE;
 392 }
 393 
 394 /* ============================================================================= */
 395 
 396 static volatile int testedThreadRunning = NSK_FALSE;
 397 static volatile int testedThreadShouldFinish = NSK_FALSE;
 398 
 399 /** Native running method in tested thread. */
 400 JNIEXPORT void JNICALL
 401 Java_nsk_jvmti_scenarios_sampling_SP03_sp03t002ThreadRunningNative_nativeMethod(JNIEnv* jni,
 402                                                                                      jobject obj) {
 403     volatile int i = 0, n = 1000;
 404 
 405     /* run in a loop */
 406     testedThreadRunning = NSK_TRUE;
 407     while (!testedThreadShouldFinish) {
 408         if (n <= 0)
 409             n = 1000;
 410         if (i >= n)
 411             i = 0;
 412         i++;
 413     }
 414     testedThreadRunning = NSK_FALSE;
 415 }
 416 
 417 /** Wait for native method is running. */
 418 JNIEXPORT jboolean JNICALL
 419 Java_nsk_jvmti_scenarios_sampling_SP03_sp03t002ThreadRunningNative_checkReady(JNIEnv* jni,
 420                                                                                    jobject obj) {
 421     while (!testedThreadRunning) {
 422         nsk_jvmti_sleep(1000);
 423     }
 424     return testedThreadRunning ? JNI_TRUE : JNI_FALSE;
 425 }
 426 
 427 /** Let native method to finish. */
 428 JNIEXPORT void JNICALL
 429 Java_nsk_jvmti_scenarios_sampling_SP03_sp03t002ThreadRunningNative_letFinish(JNIEnv* jni,
 430                                                                                   jobject obj) {
 431     testedThreadShouldFinish = NSK_TRUE;
 432 }
 433 
 434 /* ============================================================================= */
 435 
 436 /** Agent library initialization. */
 437 #ifdef STATIC_BUILD
 438 JNIEXPORT jint JNICALL Agent_OnLoad_sp03t002(JavaVM *jvm, char *options, void *reserved) {
 439     return Agent_Initialize(jvm, options, reserved);
 440 }
 441 JNIEXPORT jint JNICALL Agent_OnAttach_sp03t002(JavaVM *jvm, char *options, void *reserved) {
 442     return Agent_Initialize(jvm, options, reserved);
 443 }
 444 JNIEXPORT jint JNI_OnLoad_sp03t002(JavaVM *jvm, char *options, void *reserved) {
 445     return JNI_VERSION_1_8;
 446 }
 447 #endif
 448 jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
 449 
 450     /* init framework and parse options */
 451     if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
 452         return JNI_ERR;
 453 
 454     timeout = nsk_jvmti_getWaitTime() * 60 * 1000;
 455 
 456     /* get number of threads for each kind */
 457     threadsCount = nsk_jvmti_findOptionIntValue("threads", DEFAULT_THREADS_NUMBER);
 458     if (!NSK_VERIFY(threadsCount > 0))
 459         return JNI_ERR;
 460 
 461     /* create JVMTI environment */
 462     if (!NSK_VERIFY((jvmti =
 463             nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
 464         return JNI_ERR;
 465 
 466     /* add specific capabilities for suspending thread */
 467     {
 468         jvmtiCapabilities suspendCaps;
 469         memset(&suspendCaps, 0, sizeof(suspendCaps));
 470         suspendCaps.can_suspend = 1;
 471         if (!NSK_JVMTI_VERIFY(
 472                 NSK_CPP_STUB2(AddCapabilities, jvmti, &suspendCaps)))
 473             return JNI_ERR;
 474     }
 475 
 476     /* register agent proc and arg */
 477     if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL)))
 478         return JNI_ERR;
 479 
 480     return JNI_OK;
 481 }
 482 
 483 /* ============================================================================= */
 484 
 485 }