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 jlong timeout = 0;
  36 
  37 /* constant names */
  38 #define DEBUGEE_CLASS_NAME      "nsk/jvmti/ClassFileLoadHook/classfloadhk007"
  39 #define TESTED_CLASS_NAME       "nsk/jvmti/ClassFileLoadHook/classfloadhk007r"
  40 #define TESTED_CLASS_SIG        "L" TESTED_CLASS_NAME ";"
  41 #define TESTED_CLASSLOADER_NAME "nsk/jvmti/ClassFileLoadHook/classfloadhk007ClassLoader"
  42 #define TESTED_CLASSLOADER_SIG  "L" TESTED_CLASSLOADER_NAME ";"
  43 
  44 #define BYTECODE_FIELD_SIG      "[B"
  45 #define REDEF_BYTECODE_FIELD_NAME  "redefClassBytes"
  46 
  47 #define CLASSLOADER_FIELD_NAME  "classLoader"
  48 #define TESTED_CLASS_FIELD_NAME "testedClass"
  49 #define TESTED_CLASS_FIELD_SIG  "Ljava/lang/Class;"
  50 
  51 static jobject classLoader = NULL;
  52 static jclass testedClass = NULL;
  53 
  54 static jint redefClassSize = 0;
  55 static unsigned char* redefClassBytes = NULL;
  56 
  57 static volatile int eventsCount = 0;
  58 
  59 /* ============================================================================= */
  60 
  61 /** Check (strictly or not) if bytecode has expected size and bytes or complain an error. */
  62 static int checkBytecode(const char kind[], jint size, const unsigned char bytes[],
  63                             jint expectedSize, const unsigned char expectedBytes[],
  64                             int strict) {
  65     int success = NSK_TRUE;
  66 
  67     NSK_DISPLAY3("Check %s bytecode: 0x%p:%d\n", kind, (void*)bytes, (int)size);
  68     if (nsk_getVerboseMode()) {
  69         nsk_printHexBytes("   ", 16, size, bytes);
  70     }
  71 
  72     if (bytes == NULL) {
  73         NSK_COMPLAIN2("Unexpected NULL pointer to %s bytecode in CLASS_FILE_LOAD_HOOK: 0x%p\n",
  74                                                             kind, (void*)bytes);
  75         return NSK_FALSE;
  76     }
  77 
  78     if (size <= 0) {
  79         NSK_COMPLAIN2("Unexpected zero size of %s bytecode in CLASS_FILE_LOAD_HOOK: %d\n",
  80                                                             kind, (int)size);
  81         return NSK_FALSE;
  82     }
  83 
  84     if (strict) {
  85         if (size != expectedSize) {
  86             NSK_COMPLAIN3("Unexpected size of %s bytecode in CLASS_FILE_LOAD_HOOK:\n"
  87                           "#   got size: %d\n"
  88                           "#   expected: %d\n",
  89                             kind, (int)size, (int)expectedSize);
  90             success = NSK_FALSE;
  91         } else {
  92             jint different = 0;
  93             jint i;
  94 
  95             for (i = 0; i < size; i++) {
  96                 if (bytes[i] != expectedBytes[i]) {
  97                     different++;
  98                 }
  99             }
 100             if (different > 0) {
 101                 NSK_COMPLAIN2("Unexpected bytes in %s bytecode in CLASS_FILE_LOAD_HOOK:\n"
 102                               "#   different bytes: %d\n"
 103                               "#   total bytes:     %d\n",
 104                                 (int)different, (int)size);
 105                 success = NSK_FALSE;
 106             }
 107         }
 108 
 109         if (!success) {
 110             NSK_COMPLAIN2("Got %s bytecode is not equal to expected bytecode: %d bytes\n",
 111                                                                         kind, expectedSize);
 112             if (nsk_getVerboseMode()) {
 113                 nsk_printHexBytes("   ", 16, expectedSize, expectedBytes);
 114             }
 115         } else {
 116             NSK_DISPLAY1("All %s bytecode is equal to expected one\n", kind);
 117         }
 118     }
 119 
 120     return success;
 121 }
 122 
 123 /** Get classfile bytecode from a static field of given class. */
 124 static int getBytecode(jvmtiEnv* jvmti, JNIEnv* jni, jclass cls,
 125                                     const char fieldName[], const char fieldSig[],
 126                                     jint* size, unsigned char* *bytes) {
 127 
 128     jfieldID fieldID = NULL;
 129     jbyteArray array = NULL;
 130     jbyte* elements;
 131     int i;
 132 
 133     NSK_DISPLAY1("Find static field: %s\n", fieldName);
 134     if (!NSK_JNI_VERIFY(jni, (fieldID =
 135             NSK_CPP_STUB4(GetStaticFieldID, jni, cls, fieldName, fieldSig)) != NULL)) {
 136         nsk_jvmti_setFailStatus();
 137         return NSK_FALSE;
 138     }
 139     NSK_DISPLAY1("  ... got fieldID: 0x%p\n", (void*)fieldID);
 140 
 141     NSK_DISPLAY1("Get classfile bytes array from static field: %s\n", fieldName);
 142     if (!NSK_JNI_VERIFY(jni, (array = (jbyteArray)
 143             NSK_CPP_STUB3(GetStaticObjectField, jni, cls, fieldID)) != NULL)) {
 144         nsk_jvmti_setFailStatus();
 145         return NSK_FALSE;
 146     }
 147     NSK_DISPLAY1("  ... got array object: 0x%p\n", (void*)array);
 148 
 149     if (!NSK_JNI_VERIFY(jni, (*size =
 150             NSK_CPP_STUB2(GetArrayLength, jni, array)) > 0)) {
 151         nsk_jvmti_setFailStatus();
 152         return NSK_FALSE;
 153     }
 154     NSK_DISPLAY1("  ... got array size: %d bytes\n", (int)*size);
 155 
 156     {
 157         jboolean isCopy;
 158         if (!NSK_JNI_VERIFY(jni, (elements =
 159                 NSK_CPP_STUB3(GetByteArrayElements, jni, array,
 160                                                             &isCopy)) != NULL)) {
 161             nsk_jvmti_setFailStatus();
 162         return NSK_FALSE;
 163         }
 164     }
 165     NSK_DISPLAY1("  ... got elements list: 0x%p\n", (void*)elements);
 166 
 167     if (!NSK_JVMTI_VERIFY(
 168             NSK_CPP_STUB3(Allocate, jvmti, *size, bytes))) {
 169         nsk_jvmti_setFailStatus();
 170         return NSK_FALSE;
 171     }
 172     NSK_DISPLAY1("  ... created bytes array: 0x%p\n", (void*)*bytes);
 173 
 174     for (i = 0; i < *size; i++) {
 175         (*bytes)[i] = (unsigned char)elements[i];
 176     }
 177     NSK_DISPLAY1("  ... copied bytecode: %d bytes\n", (int)*size);
 178 
 179     NSK_DISPLAY1("Release elements list: 0x%p\n", (void*)elements);
 180     NSK_TRACE(NSK_CPP_STUB4(ReleaseByteArrayElements, jni, array, elements, JNI_ABORT));
 181     NSK_DISPLAY0("  ... released\n");
 182 
 183     return NSK_TRUE;
 184 }
 185 
 186 /** Get global reference to object from a static field of given class. */
 187 static jobject getObject(jvmtiEnv* jvmti, JNIEnv* jni, jclass cls,
 188                                     const char fieldName[], const char fieldSig[]) {
 189 
 190     jfieldID fieldID = NULL;
 191     jobject obj = NULL;
 192 
 193     NSK_DISPLAY1("Find static field: %s\n", fieldName);
 194     if (!NSK_JNI_VERIFY(jni, (fieldID =
 195             NSK_CPP_STUB4(GetStaticFieldID, jni, cls, fieldName, fieldSig)) != NULL)) {
 196         nsk_jvmti_setFailStatus();
 197         return NULL;
 198     }
 199     NSK_DISPLAY1("  ... got fieldID: 0x%p\n", (void*)fieldID);
 200 
 201     NSK_DISPLAY1("Get object from static field: %s\n", fieldName);
 202     if (!NSK_JNI_VERIFY(jni, (obj =
 203             NSK_CPP_STUB3(GetStaticObjectField, jni, cls, fieldID)) != NULL)) {
 204         nsk_jvmti_setFailStatus();
 205         return NULL;
 206     }
 207     NSK_DISPLAY1("  ... got object: 0x%p\n", (void*)obj);
 208 
 209     NSK_DISPLAY1("Make global reference to object: 0x%p\n", obj);
 210     if (!NSK_JNI_VERIFY(jni, (obj =
 211             NSK_CPP_STUB2(NewGlobalRef, jni, obj)) != NULL)) {
 212         nsk_jvmti_setFailStatus();
 213         return NULL;
 214     }
 215     NSK_DISPLAY1("  ... got global ref: 0x%p\n", (void*)obj);
 216 
 217     return obj;
 218 }
 219 
 220 /** Redefine given class with new bytecode. */
 221 static int redefineClass(jvmtiEnv* jvmti, jclass klass, const char className[],
 222                                                     jint size, unsigned char bytes[]) {
 223     jvmtiClassDefinition classDef;
 224 
 225     classDef.klass = klass;
 226     classDef.class_byte_count = size;
 227     classDef.class_bytes = bytes;
 228 
 229     NSK_DISPLAY1("Redefine class: %s\n", className);
 230     if (!NSK_JVMTI_VERIFY(
 231             NSK_CPP_STUB3(RedefineClasses, jvmti, 1, &classDef))) {
 232         nsk_jvmti_setFailStatus();
 233         return NSK_FALSE;
 234     }
 235     NSK_DISPLAY1("   ... redefined with bytecode: %d bytes\n", (int)size);
 236 
 237     return NSK_TRUE;
 238 }
 239 
 240 /* ============================================================================= */
 241 
 242 /** Agent algorithm. */
 243 static void JNICALL
 244 agentProc(jvmtiEnv* jvmti, JNIEnv* jni, void* arg) {
 245     NSK_DISPLAY0("Wait for debuggee to load original class\n");
 246     if (!NSK_VERIFY(nsk_jvmti_waitForSync(timeout)))
 247         return;
 248 
 249     /* perform testing */
 250     {
 251         {
 252             jclass debugeeClass = NULL;
 253 
 254             NSK_DISPLAY0(">>> Obtain debuggee class\n");
 255             NSK_DISPLAY1("Find debugee class: %s\n", DEBUGEE_CLASS_NAME);
 256             if (!NSK_JNI_VERIFY(jni, (debugeeClass =
 257                     NSK_CPP_STUB2(FindClass, jni, DEBUGEE_CLASS_NAME)) != NULL)) {
 258                 nsk_jvmti_setFailStatus();
 259                 return;
 260             }
 261             NSK_DISPLAY1("  ... found class: 0x%p\n", (void*)debugeeClass);
 262 
 263             NSK_DISPLAY0(">>> Obtain tested class object\n");
 264             if (!NSK_VERIFY((testedClass = (jclass)
 265                     getObject(jvmti, jni, debugeeClass, TESTED_CLASS_FIELD_NAME,
 266                                                         TESTED_CLASS_FIELD_SIG)) != NULL))
 267                 return;
 268 
 269             NSK_DISPLAY0(">>> Obtain classloader object\n");
 270             if (!NSK_VERIFY((classLoader =
 271                     getObject(jvmti, jni, debugeeClass, CLASSLOADER_FIELD_NAME,
 272                                                         TESTED_CLASSLOADER_SIG)) != NULL))
 273                 return;
 274 
 275             NSK_DISPLAY0(">>> Obtain redefined bytecode of tested class\n");
 276             if (!NSK_VERIFY(getBytecode(jvmti, jni, debugeeClass,
 277                                                 REDEF_BYTECODE_FIELD_NAME,
 278                                                 BYTECODE_FIELD_SIG,
 279                                                 &redefClassSize, &redefClassBytes)))
 280                 return;
 281         }
 282 
 283         NSK_DISPLAY0(">>> Redefine tested class\n");
 284         {
 285             if (!NSK_VERIFY(redefineClass(jvmti, testedClass, TESTED_CLASS_NAME,
 286                                                         redefClassSize, redefClassBytes)))
 287                 return;
 288         }
 289 
 290         NSK_DISPLAY0(">>> Testcase #1: Redefine class and check CLASS_FILE_LOAD_HOOK event\n");
 291         {
 292             jvmtiEvent event = JVMTI_EVENT_CLASS_FILE_LOAD_HOOK;
 293 
 294             NSK_DISPLAY1("Enable event: %s\n", "CLASS_FILE_LOAD_HOOK");
 295             if (!NSK_VERIFY(nsk_jvmti_enableEvents(JVMTI_ENABLE, 1, &event, NULL)))
 296                 return;
 297             NSK_DISPLAY0("  ... event enabled\n");
 298 
 299             NSK_VERIFY(redefineClass(jvmti, testedClass, TESTED_CLASS_NAME,
 300                                                         redefClassSize, redefClassBytes));
 301 
 302             NSK_DISPLAY1("Disable event: %s\n", "CLASS_FILE_LOAD_HOOK");
 303             if (NSK_VERIFY(nsk_jvmti_enableEvents(JVMTI_DISABLE, 1, &event, NULL))) {
 304                 NSK_DISPLAY0("  ... event disabled\n");
 305             }
 306 
 307             NSK_DISPLAY1("Check if event was received: %s\n", "CLASS_FILE_LOAD_HOOK");
 308             if (eventsCount != 1) {
 309                 NSK_COMPLAIN3("Unexpected number of %s events received for tested class:\n"
 310                               "#   received: %d events\n"
 311                               "#   expected: %d events\n",
 312                                 "CLASS_FILE_LOAD_HOOK", eventsCount, 1);
 313                 nsk_jvmti_setFailStatus();
 314             } else {
 315                 NSK_DISPLAY1("  ... received: %d events\n", eventsCount);
 316             }
 317         }
 318 
 319         NSK_DISPLAY0(">>> Clean used data\n");
 320         {
 321             NSK_DISPLAY1("Delete global reference to classloader object: 0x%p\n", (void*)classLoader);
 322             NSK_CPP_STUB2(DeleteGlobalRef, jni, classLoader);
 323 
 324             NSK_DISPLAY1("Delete global reference to tested class object: 0x%p\n", (void*)testedClass);
 325             NSK_CPP_STUB2(DeleteGlobalRef, jni, testedClass);
 326 
 327             NSK_DISPLAY1("Deallocate redefined bytecode array: 0x%p\n", (void*)redefClassBytes);
 328             if (!NSK_JVMTI_VERIFY(
 329                         NSK_CPP_STUB2(Deallocate, jvmti, redefClassBytes))) {
 330                 nsk_jvmti_setFailStatus();
 331             }
 332         }
 333     }
 334 
 335     NSK_DISPLAY0("Let debugee to finish\n");
 336     if (!NSK_VERIFY(nsk_jvmti_resumeSync()))
 337         return;
 338 }
 339 
 340 /* ============================================================================= */
 341 
 342 /** Callback for CLASS_FILE_LOAD_HOOK event **/
 343 static void JNICALL
 344 callbackClassFileLoadHook(jvmtiEnv *jvmti, JNIEnv *jni,
 345                             jclass class_being_redefined,
 346                             jobject loader, const char* name, jobject protection_domain,
 347                             jint class_data_len, const unsigned char* class_data,
 348                             jint *new_class_data_len, unsigned char** new_class_data) {
 349 
 350     NSK_DISPLAY5("  <CLASS_FILE_LOAD_HOOK>: name: %s, loader: 0x%p, redefined: 0x%p, bytecode: 0x%p:%d\n",
 351                         nsk_null_string(name), (void*)loader, (void*)class_being_redefined,
 352                         (void*)class_data, (int)class_data_len);
 353 
 354     if (name != NULL && (strcmp(name, TESTED_CLASS_NAME) == 0)) {
 355         NSK_DISPLAY1("SUCCESS! CLASS_FILE_LOAD_HOOK for tested class: %s\n", TESTED_CLASS_NAME);
 356         eventsCount++;
 357 
 358         NSK_DISPLAY1("Check classloader: 0x%p\n", (void*)loader);
 359         if (loader == NULL) {
 360             NSK_COMPLAIN1("Unexpected NULL classloader in CLASS_FILE_LOAD_HOOK: 0x%p\n",
 361                                                     (void*)loader);
 362             nsk_jvmti_setFailStatus();
 363         } else if (!NSK_CPP_STUB3(IsSameObject, jni, loader, classLoader)) {
 364             NSK_COMPLAIN2("Unexpected classloader in CLASS_FILE_LOAD_HOOK:\n"
 365                           "#   got classloder:   0x%p\n"
 366                           "#   expected same as: 0x%p\n",
 367                             (void*)loader, (void*)classLoader);
 368             nsk_jvmti_setFailStatus();
 369         }
 370 
 371         NSK_DISPLAY1("Check class_being_redefined: 0x%p\n", (void*)class_being_redefined);
 372         if (class_being_redefined == NULL) {
 373             NSK_COMPLAIN1("Unexpected NULL class_being_redefined in CLASS_FILE_LOAD_HOOK: 0x%p\n",
 374                                                     (void*)class_being_redefined);
 375             nsk_jvmti_setFailStatus();
 376         } else if (!NSK_CPP_STUB3(IsSameObject, jni, class_being_redefined, testedClass)) {
 377             NSK_COMPLAIN2("Unexpected class_being_redefined in CLASS_FILE_LOAD_HOOK:\n"
 378                           "#   got class:        0x%p\n"
 379                           "#   expected same as: 0x%p\n",
 380                             (void*)class_being_redefined, (void*)testedClass);
 381             nsk_jvmti_setFailStatus();
 382         }
 383 
 384         if (!checkBytecode("redefined", class_data_len, class_data,
 385                                             redefClassSize, redefClassBytes, NSK_TRUE)) {
 386             nsk_jvmti_setFailStatus();
 387         }
 388     }
 389 }
 390 
 391 /* ============================================================================= */
 392 
 393 /** Agent library initialization. */
 394 #ifdef STATIC_BUILD
 395 JNIEXPORT jint JNICALL Agent_OnLoad_classfloadhk007(JavaVM *jvm, char *options, void *reserved) {
 396     return Agent_Initialize(jvm, options, reserved);
 397 }
 398 JNIEXPORT jint JNICALL Agent_OnAttach_classfloadhk007(JavaVM *jvm, char *options, void *reserved) {
 399     return Agent_Initialize(jvm, options, reserved);
 400 }
 401 JNIEXPORT jint JNI_OnLoad_classfloadhk007(JavaVM *jvm, char *options, void *reserved) {
 402     return JNI_VERSION_1_8;
 403 }
 404 #endif
 405 jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
 406     jvmtiEnv* jvmti = NULL;
 407 
 408     /* init framework and parse options */
 409     if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
 410         return JNI_ERR;
 411 
 412     timeout = nsk_jvmti_getWaitTime() * 60 * 1000;
 413 
 414     /* create JVMTI environment */
 415     if (!NSK_VERIFY((jvmti =
 416             nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
 417         return JNI_ERR;
 418 
 419     NSK_DISPLAY1("Add required capabilities: %s\n", "can_generate_eraly_class_hook_events, can_redefine_classes");
 420     {
 421         jvmtiCapabilities caps;
 422 
 423         memset(&caps, 0, sizeof(caps));
 424         caps.can_generate_all_class_hook_events = 1;
 425         caps.can_redefine_classes = 1;
 426         if (!NSK_JVMTI_VERIFY(
 427                 NSK_CPP_STUB2(AddCapabilities, jvmti, &caps))) {
 428             return JNI_ERR;
 429         }
 430     }
 431     NSK_DISPLAY0("  ... added\n");
 432 
 433     NSK_DISPLAY1("Set callback for event: %s\n", "CLASS_FILE_LOAD_HOOK");
 434     {
 435         jvmtiEventCallbacks callbacks;
 436         jint size = (jint)sizeof(callbacks);
 437 
 438         memset(&callbacks, 0, sizeof(callbacks));
 439         callbacks.ClassFileLoadHook = callbackClassFileLoadHook;
 440         if (!NSK_JVMTI_VERIFY(
 441                 NSK_CPP_STUB3(SetEventCallbacks, jvmti, &callbacks, size))) {
 442             return JNI_ERR;
 443         }
 444     }
 445     NSK_DISPLAY0("  ... set\n");
 446 
 447     /* register agent proc and arg */
 448     if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL)))
 449         return JNI_ERR;
 450 
 451     return JNI_OK;
 452 }
 453 
 454 /* ============================================================================= */
 455 
 456 }