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 <stdio.h>
  25 #include <stdarg.h>
  26 #include <stdlib.h>
  27 #include <string.h>
  28 
  29 #include <jvmti.h>
  30 #include "agent_common.h"
  31 
  32 #include "nsk_tools.h"
  33 #include "JVMTITools.h"
  34 #include "jvmti_tools.h"
  35 #include "native_thread.h"
  36 
  37 #ifdef __cplusplus
  38 extern "C" {
  39 #endif
  40 
  41 #ifndef JNI_ENV_ARG
  42   #ifdef __cplusplus
  43     #define JNI_ENV_ARG(x, y) y
  44     #define JNI_ENV_PTR(x) x
  45   #else
  46     #define JNI_ENV_ARG(x, y) x, y
  47     #define JNI_ENV_PTR(x) (*x)
  48   #endif
  49 #endif
  50 
  51 #ifndef JNI_ENV_ARG1
  52   #ifdef __cplusplus
  53     #define JNI_ENV_ARG1(x)
  54   #else
  55     #define JNI_ENV_ARG1(x) x
  56   #endif
  57 #endif
  58 
  59 #define PASSED  0
  60 #define STATUS_FAILED  2
  61 
  62 #define TRIES 30
  63 #define MAX_THREADS 5
  64 
  65 static const char *javaField = "_ji06t001a";
  66 static const char *classSig =
  67     "Lnsk/jvmti/scenarios/jni_interception/JI06/ji06t001a;";
  68 
  69 static JavaVM *vm;
  70 static jvmtiEnv *jvmti = NULL;
  71 
  72 static volatile int verbose = 0;
  73 
  74 static volatile jint result = PASSED;
  75 static volatile int monEntered = 0; /* the monitor entered */
  76 static volatile int thrStarted[MAX_THREADS]; /* a thread started */
  77 static volatile int releaseMon = 0; /* flag to release the monitor */
  78 
  79 static volatile jobject clsObj;
  80 static jrawMonitorID countLock;
  81 
  82 /* the original JNI function table */
  83 static jniNativeInterface *orig_jni_functions = NULL;
  84 
  85 /* the redirected JNI function table */
  86 static jniNativeInterface *redir_jni_functions = NULL;
  87 
  88 /* number of the redirected JNI function calls */
  89 static volatile int monent_calls = 0;
  90 
  91 static void lock() {
  92     if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(RawMonitorEnter,
  93             jvmti, countLock)))
  94         exit(STATUS_FAILED);
  95 }
  96 
  97 static void unlock() {
  98     if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(RawMonitorExit,
  99             jvmti, countLock)))
 100         exit(STATUS_FAILED);
 101 }
 102 
 103 /** redirected JNI functions **/
 104 jint JNICALL MyMonitorEnter(JNIEnv *env, jobject obj) {
 105     lock();
 106     monent_calls++;
 107     unlock();
 108 
 109     NSK_DISPLAY1("MyMonitorEnter: the function called successfully: number of calls=%d\n",
 110         monent_calls);
 111 
 112     return orig_jni_functions->MonitorEnter(
 113         JNI_ENV_ARG(env, obj));
 114 }
 115 /*****************************/
 116 
 117 static jint enterMonitor(JNIEnv *env, const char *thr) {
 118     jint result;
 119 
 120     if ((result = JNI_ENV_PTR(env)->
 121             MonitorEnter(JNI_ENV_ARG(env, clsObj))) != 0) {
 122         NSK_COMPLAIN2("TEST FAILURE: %s: MonitorEnter() returns: %d\n",
 123             thr, result);
 124         return STATUS_FAILED;
 125     }
 126     if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG1(env))) {
 127         NSK_COMPLAIN1("TEST FAILURE: %s: exception occured\n",
 128             thr);
 129         JNI_ENV_PTR(env)->ExceptionDescribe(JNI_ENV_ARG1(env));
 130         JNI_ENV_PTR(env)->ExceptionClear(JNI_ENV_ARG1(env));
 131         return STATUS_FAILED;
 132     }
 133 
 134     return PASSED;
 135 }
 136 
 137 static jint exitMonitor(JNIEnv *env, const char *thr) {
 138     jint result;
 139 
 140     if ((result = JNI_ENV_PTR(env)->
 141             MonitorExit(JNI_ENV_ARG(env, clsObj))) != 0) {
 142         NSK_COMPLAIN2("TEST FAILURE: %s: MonitorExit() returns: %d\n",
 143             thr, result);
 144         return STATUS_FAILED;
 145     }
 146 
 147     return PASSED;
 148 }
 149 
 150 static void doRedirect(JNIEnv *env) {
 151     jvmtiError err;
 152 
 153     NSK_DISPLAY0("doRedirect: obtaining the JNI function table ...\n");
 154     if ((err = (*jvmti)->GetJNIFunctionTable(jvmti, &orig_jni_functions)) !=
 155             JVMTI_ERROR_NONE) {
 156         result = STATUS_FAILED;
 157         NSK_COMPLAIN1("TEST FAILED: failed to get original JNI function table: %s\n",
 158             TranslateError(err));
 159         JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 160             "failed to get original JNI function table"));
 161     }
 162     if ((err = (*jvmti)->GetJNIFunctionTable(jvmti, &redir_jni_functions)) !=
 163             JVMTI_ERROR_NONE) {
 164         result = STATUS_FAILED;
 165         NSK_COMPLAIN1("TEST FAILED: failed to get redirected JNI function table: %s\n",
 166             TranslateError(err));
 167         JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 168             "failed to get redirected JNI function table"));
 169     }
 170 
 171     NSK_DISPLAY0("doRedirect: the JNI function table obtained successfully\n\
 172 \toverwriting the function MonitorEnter ...\n");
 173 
 174     redir_jni_functions->MonitorEnter = MyMonitorEnter;
 175 
 176     if ((err = (*jvmti)->SetJNIFunctionTable(jvmti, redir_jni_functions)) !=
 177             JVMTI_ERROR_NONE) {
 178         result = STATUS_FAILED;
 179         NSK_COMPLAIN1("TEST FAILED: failed to set new JNI function table: %s\n",
 180             TranslateError(err));
 181         JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 182             "failed to set new JNI function table"));
 183     }
 184 
 185     NSK_DISPLAY0("doRedirect: the functions are overwritten successfully\n");
 186 }
 187 
 188 static void checkCall(int exMonEntCalls) {
 189     if (monent_calls >= exMonEntCalls) {
 190         NSK_DISPLAY1("CHECK PASSED: the tested JNI function MonitorEnter() has been redirected:\n\
 191 \tat least %d intercepted call(s) as expected",
 192             monent_calls);
 193     }
 194     else {
 195         result = STATUS_FAILED;
 196         NSK_COMPLAIN2("TEST FAILED: the tested JNI function MonitorEnter() has not been redirected properly:\n\
 197 \tonly %d intercepted call(s) instead of at least %d as expected\n",
 198             monent_calls, exMonEntCalls);
 199     }
 200 }
 201 
 202 /* thread procedures */
 203 static int waitingThread(void *context) {
 204     JNIEnv *env;
 205     int exitCode = PASSED;
 206     jint res;
 207     int tries = 0;
 208     /* 4932877 fix in accordance with ANSI C: thread context of type void* -> int* -> int */
 209     int indx = *((int *) context);
 210 
 211     NSK_DISPLAY1("waitingThread: thread #%d started\n\
 212 \tattaching the thread to the VM ...\n",
 213         indx);
 214     if ((res =
 215             JNI_ENV_PTR(vm)->AttachCurrentThread(
 216                 JNI_ENV_ARG(vm, (void **) &env), (void *) 0)) != 0) {
 217         NSK_COMPLAIN1("TEST FAILURE: waitingThread: AttachCurrentThread() returns: %d\n",
 218             res);
 219         return STATUS_FAILED;
 220     }
 221 
 222     NSK_DISPLAY1("waitingThread: thread #%d is trying to enter the monitor ...\n",
 223        indx);
 224 
 225     thrStarted[indx-1] = 1; /* the thread is started */
 226 
 227     if (enterMonitor(env, "waitingThread") == STATUS_FAILED)
 228         return STATUS_FAILED;
 229     if (verbose)
 230         printf("waitingThread: thread #%d entered the monitor\n",
 231             indx);
 232     if (exitMonitor(env, "waitingThread") == STATUS_FAILED)
 233         return STATUS_FAILED;
 234 
 235     NSK_DISPLAY2("waitingThread: thread #%d exits the monitor\n\treturning %d\n",
 236         indx, exitCode);
 237     return exitCode;
 238 }
 239 
 240 static int ownerThread(void *context) {
 241     JNIEnv *env;
 242     int exitCode = PASSED;
 243     jint res;
 244     int tries = 0;
 245 
 246     NSK_DISPLAY0("ownerThread: thread started\n\tattaching the thread to the VM ...\n");
 247     if ((res =
 248             JNI_ENV_PTR(vm)->AttachCurrentThread(
 249                 JNI_ENV_ARG(vm, (void **) &env), (void *) 0)) != 0) {
 250         NSK_COMPLAIN1("TEST FAILURE: ownerThread: AttachCurrentThread() returns: %d\n",
 251             res);
 252         return STATUS_FAILED;
 253     }
 254 
 255     NSK_DISPLAY0("ownerThread: trying to enter the monitor ...\n");
 256     if (enterMonitor(env, "ownerThread") == STATUS_FAILED)
 257         return STATUS_FAILED;
 258 
 259     monEntered = 1; /* the monitor has been entered */
 260     NSK_DISPLAY1("ownerThread: entered the monitor: monEntered=%d\n\
 261 \twaiting ...\n",
 262         monEntered);
 263     do {
 264         THREAD_sleep(1);
 265         tries++;
 266         if (tries > TRIES) {
 267             NSK_COMPLAIN1("TEST FAILED: ownerThread: time exceed after %d attempts\n",
 268                 TRIES);
 269             JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 270                 "ownerThread: time exceed"));
 271         }
 272     } while(releaseMon != 1);
 273 
 274     if (exitMonitor(env, "ownerThread") == STATUS_FAILED)
 275         return STATUS_FAILED;
 276 
 277     NSK_DISPLAY1("ownerThread: exits the monitor\n\treturning %d\n",
 278         exitCode);
 279 
 280     return exitCode;
 281 }
 282 
 283 static int redirectorThread(void *context) {
 284     JNIEnv *env;
 285     int exitCode = PASSED;
 286     jint res;
 287     int tries = 0;
 288 
 289     NSK_DISPLAY0("redirectorThread: thread started\n\tattaching the thread to the VM ...\n");
 290     if ((res =
 291             JNI_ENV_PTR(vm)->AttachCurrentThread(
 292                 JNI_ENV_ARG(vm, (void **) &env), (void *) 0)) != 0) {
 293         NSK_COMPLAIN1("TEST FAILURE: redirectorThread: AttachCurrentThread() returns: %d\n",
 294             res);
 295         return STATUS_FAILED;
 296     }
 297 
 298     NSK_DISPLAY0("redirectorThread: trying to redirect the MonitorEnter() ...\n");
 299     doRedirect(env);
 300 
 301     NSK_DISPLAY1("redirectorThread: the MonitorEnter() redirected\n\treturning %d\n",
 302         exitCode);
 303 
 304     return exitCode;
 305 }
 306 /*********************/
 307 
 308 static jobject getObjectFromField(JNIEnv *env, jobject obj) {
 309     jfieldID fid;
 310     jclass _objCls;
 311 
 312     _objCls = JNI_ENV_PTR(env)->GetObjectClass(JNI_ENV_ARG(env, obj));
 313 
 314     NSK_DISPLAY2("getObjectFromField: obtaining field ID for name=\"%s\" signature=\"%s\"...\n",
 315         javaField, classSig);
 316     if ((fid = JNI_ENV_PTR(env)->GetFieldID(
 317             JNI_ENV_ARG(env, _objCls), javaField, classSig)) == 0) {
 318         result = STATUS_FAILED;
 319         NSK_COMPLAIN1("TEST FAILURE: failed to get ID for the field \"%s\"\n",
 320             javaField);
 321         JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 322             "failed to get ID for the java field"));
 323     }
 324 
 325     return JNI_ENV_PTR(env)->GetObjectField(
 326         JNI_ENV_ARG(env, obj), fid);
 327 }
 328 
 329 JNIEXPORT jint JNICALL
 330 Java_nsk_jvmti_scenarios_jni_1interception_JI06_ji06t001_check(JNIEnv *env, jobject obj) {
 331     char *ownContext = "ownerThr";
 332     char *redirContext = "redirectorThr";
 333     int exitCode = PASSED;
 334     void *ownThr = NULL;
 335     void *redirThr = NULL;
 336     void *waitThr[MAX_THREADS];
 337     int waitContElem[MAX_THREADS]; /* context of a particular waiting thread */
 338     int i;
 339     int tries = 0;
 340 
 341     if (jvmti == NULL) {
 342         NSK_COMPLAIN0("TEST FAILURE: JVMTI client was not properly loaded\n");
 343         return STATUS_FAILED;
 344     }
 345 
 346 /* prepare the testing */
 347     if ((clsObj = JNI_ENV_PTR(env)->NewGlobalRef(
 348             JNI_ENV_ARG(env, getObjectFromField(env, obj)))) == NULL) {
 349         NSK_COMPLAIN1("TEST FAILURE: cannot create a new global reference of class \"%s\"\n",
 350             classSig);
 351         JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 352             "failed to create a new global reference"));
 353     }
 354 
 355     NSK_DISPLAY0("starting monitor owner thread ...\n");
 356     ownThr = THREAD_new(ownerThread, ownContext);
 357     if (THREAD_start(ownThr) == NULL) {
 358         NSK_COMPLAIN0("TEST FAILURE: cannot start monitor owner thread\n");
 359         exit(STATUS_FAILED);
 360     }
 361 
 362     NSK_DISPLAY0("waiting for the monitor to be entered ...\n");
 363     do {
 364         THREAD_sleep(1);
 365         tries++;
 366         if (tries > TRIES) {
 367             NSK_COMPLAIN1("TEST FAILURE: the monitor is still not entered by the owner thread after %d attempts\n",
 368                 TRIES);
 369             JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG(env,
 370                 " the monitor is still not entered by the owner thread"));
 371         }
 372     } while(monEntered != 1);
 373 
 374     for (i=0; i<MAX_THREADS-1; i++) {
 375         NSK_DISPLAY1("starting waiting thread #%d ...\n",
 376             i+1);
 377         thrStarted[i] = 0;
 378         waitContElem[i] = i+1;
 379         /* 4932877 fix in accordance with ANSI C: thread context of type int -> int* -> void*  */
 380         waitThr[i] = THREAD_new(waitingThread, (void *) &(waitContElem[i]));
 381         if (THREAD_start(waitThr[i]) == NULL) {
 382             NSK_COMPLAIN1("TEST FAILURE: cannot start waiting thread #%d\n",
 383                 i+1);
 384             exit(STATUS_FAILED);
 385         }
 386 
 387         tries = 0;
 388         do {
 389             THREAD_sleep(1);
 390             tries++;
 391             if (tries > TRIES) {
 392                 NSK_COMPLAIN1("TEST FAILURE: waiting thread #%d is still not started\n",
 393                     i+1);
 394                 exit(STATUS_FAILED);
 395             }
 396         } while(thrStarted[i] != 1);
 397         NSK_DISPLAY1("the waiting thread #%d started\n",
 398             i+1);
 399     }
 400 
 401 /* begin the testing */
 402     NSK_DISPLAY0(">>> TEST CASE a) Trying to redirect the JNI function ...\n\
 403 \nstarting redirector thread ...\n");
 404     redirThr = THREAD_new(redirectorThread, redirContext);
 405     if (THREAD_start(redirThr) == NULL) {
 406         NSK_COMPLAIN0("TEST FAILURE: cannot start redirector thread\n");
 407         exit(STATUS_FAILED);
 408     }
 409 
 410     NSK_DISPLAY0("waiting for the redirector thread ...\n");
 411     THREAD_waitFor(redirThr);
 412     if (THREAD_status(redirThr) != PASSED)
 413         exitCode = result = STATUS_FAILED;
 414     if (exitCode == STATUS_FAILED)
 415         NSK_COMPLAIN1("the redirector thread done with the code %d\n",
 416             THREAD_status(redirThr));
 417     else
 418         NSK_DISPLAY1("the redirector thread done with the code %d\n",
 419             THREAD_status(redirThr));
 420     free(redirThr);
 421 
 422     releaseMon = 1;
 423 
 424     NSK_DISPLAY0("waiting for the monitor owner thread ...\n");
 425     THREAD_waitFor(ownThr);
 426     if (THREAD_status(ownThr) != PASSED)
 427         exitCode = result = STATUS_FAILED;
 428     if (exitCode == STATUS_FAILED)
 429         NSK_COMPLAIN1("the monitor owner thread done with the code %d\n",
 430             THREAD_status(ownThr));
 431     else
 432         NSK_DISPLAY1("the monitor owner thread done with the code %d\n",
 433             THREAD_status(ownThr));
 434     free(ownThr);
 435     NSK_DISPLAY0("<<<\n\n");
 436 
 437 /*  verification of the interception */
 438     NSK_DISPLAY0(">>> TEST CASE b) Exercising the interception ...\n\
 439 \nmain thread: trying to enter the monitor ...\n");
 440     if (enterMonitor(env, "mainThread") == STATUS_FAILED)
 441         exitCode = STATUS_FAILED;
 442     NSK_DISPLAY0("main thread: entered the monitor\n");
 443     if (exitMonitor(env, "mainThread") == STATUS_FAILED)
 444         exitCode = STATUS_FAILED;
 445     NSK_DISPLAY0("main thread: exited the monitor\n");
 446 
 447     NSK_DISPLAY0("starting a separate verification thread ...\n");
 448     waitContElem[MAX_THREADS-1] = MAX_THREADS;
 449     /* 4932877 fix in accordance with ANSI C: thread context of type int -> int* -> void*  */
 450     waitThr[MAX_THREADS-1] = THREAD_new(waitingThread,
 451         (void *) &(waitContElem[MAX_THREADS-1]));
 452     if (THREAD_start(waitThr[MAX_THREADS-1]) == NULL) {
 453         NSK_COMPLAIN0("TEST FAILURE: cannot start verification thread\n");
 454         exit(STATUS_FAILED);
 455     }
 456     NSK_DISPLAY0("the verification thread started\n");
 457 
 458 /* finish the testing */
 459     for (i=0; i<MAX_THREADS; i++) {
 460         NSK_DISPLAY1("waiting for the thread #%d...\n",
 461             i+1);
 462         THREAD_waitFor(waitThr[i]);
 463         if (THREAD_status(waitThr[i]) != PASSED) {
 464             result = STATUS_FAILED;
 465             NSK_COMPLAIN2("TEST FAILED: the waiting thread #%d done with the error code %d\n",
 466                 i+1, THREAD_status(waitThr[i]));
 467         }
 468         else
 469             NSK_DISPLAY2("the thread #%d done with the code %d\n",
 470                 i+1, THREAD_status(waitThr[i]));
 471 
 472         free(waitThr[i]);
 473     }
 474 
 475     JNI_ENV_PTR(env)->DeleteGlobalRef(JNI_ENV_ARG(env, clsObj));
 476     NSK_DISPLAY0("<<<\n\n");
 477 
 478     NSK_DISPLAY0(">>> TEST CASE c) Checking number of the intercepted calls ...\n");
 479     checkCall(2);
 480     NSK_DISPLAY0("<<<\n\n");
 481 
 482     return result;
 483 }
 484 
 485 #ifdef STATIC_BUILD
 486 JNIEXPORT jint JNICALL Agent_OnLoad_ji06t001(JavaVM *jvm, char *options, void *reserved) {
 487     return Agent_Initialize(jvm, options, reserved);
 488 }
 489 JNIEXPORT jint JNICALL Agent_OnAttach_ji06t001(JavaVM *jvm, char *options, void *reserved) {
 490     return Agent_Initialize(jvm, options, reserved);
 491 }
 492 JNIEXPORT jint JNI_OnLoad_ji06t001(JavaVM *jvm, char *options, void *reserved) {
 493     return JNI_VERSION_1_8;
 494 }
 495 #endif
 496 jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
 497     /* init framework and parse options */
 498     if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
 499         return JNI_ERR;
 500 
 501     /* create JVMTI environment */
 502     if (!NSK_VERIFY((jvmti =
 503             nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
 504         return JNI_ERR;
 505 
 506     vm = jvm;
 507 
 508     if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB3(CreateRawMonitor,
 509             jvmti, "_counter_lock", &countLock)))
 510         return JNI_ERR;
 511 
 512     return JNI_OK;
 513 }
 514 
 515 #ifdef __cplusplus
 516 }
 517 #endif