1 /*
   2  * Copyright (c) 2012, 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 
  25 #include "precompiled.hpp"
  26 
  27 #include "memory/universe.hpp"
  28 #include "oops/oop.inline.hpp"
  29 
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/classLoaderData.hpp"
  32 
  33 #include "prims/whitebox.hpp"
  34 #include "prims/wbtestmethods/parserTests.hpp"
  35 
  36 #include "runtime/interfaceSupport.hpp"
  37 #include "runtime/os.hpp"
  38 #include "utilities/debug.hpp"
  39 #include "utilities/macros.hpp"
  40 
  41 #if INCLUDE_ALL_GCS
  42 #include "gc_implementation/g1/concurrentMark.hpp"
  43 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  44 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  45 #endif // INCLUDE_ALL_GCS
  46 
  47 #ifdef INCLUDE_NMT
  48 #include "services/memTracker.hpp"
  49 #endif // INCLUDE_NMT
  50 
  51 #include "compiler/compileBroker.hpp"
  52 #include "runtime/compilationPolicy.hpp"
  53 
  54 bool WhiteBox::_used = false;
  55 
  56 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
  57   return (jlong)(void*)JNIHandles::resolve(obj);
  58 WB_END
  59 
  60 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
  61   return heapOopSize;
  62 WB_END
  63 
  64 
  65 class WBIsKlassAliveClosure : public KlassClosure {
  66     Symbol* _name;
  67     bool _found;
  68 public:
  69     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
  70 
  71     void do_klass(Klass* k) {
  72       if (_found) return;
  73       Symbol* ksym = k->name();
  74       if (ksym->fast_compare(_name) == 0) {
  75         _found = true;
  76       }
  77     }
  78 
  79     bool found() const {
  80         return _found;
  81     }
  82 };
  83 
  84 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
  85   Handle h_name = JNIHandles::resolve(name);
  86   if (h_name.is_null()) return false;
  87   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
  88   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
  89 
  90   WBIsKlassAliveClosure closure(sym);
  91   ClassLoaderDataGraph::classes_do(&closure);
  92 
  93   return closure.found();
  94 WB_END
  95 
  96 #if INCLUDE_ALL_GCS
  97 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
  98   G1CollectedHeap* g1 = G1CollectedHeap::heap();
  99   oop result = JNIHandles::resolve(obj);
 100   const HeapRegion* hr = g1->heap_region_containing(result);
 101   return hr->isHumongous();
 102 WB_END
 103 
 104 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 105   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 106   size_t nr = g1->free_regions();
 107   return (jlong)nr;
 108 WB_END
 109 
 110 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 111   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 112   ConcurrentMark* cm = g1->concurrent_mark();
 113   return cm->concurrent_marking_in_progress();
 114 WB_END
 115 
 116 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 117   return (jint)HeapRegion::GrainBytes;
 118 WB_END
 119 #endif // INCLUDE_ALL_GCS
 120 
 121 #ifdef INCLUDE_NMT
 122 // Keep track of the 3 allocations in NMTAllocTest so we can free them later
 123 // on and verify that they're not visible anymore
 124 static void* nmtMtTest1 = NULL, *nmtMtTest2 = NULL, *nmtMtTest3 = NULL;
 125 
 126 // Alloc memory using the test memory type so that we can use that to see if
 127 // NMT picks it up correctly
 128 WB_ENTRY(jboolean, WB_NMTAllocTest(JNIEnv* env))
 129   void *mem;
 130 
 131   if (!MemTracker::is_on() || MemTracker::shutdown_in_progress()) {
 132     return false;
 133   }
 134 
 135   // Allocate 2 * 128k + 256k + 1024k and free the 1024k one to make sure we track
 136   // everything correctly. Total should be 512k held alive.
 137   nmtMtTest1 = os::malloc(128 * 1024, mtTest);
 138   mem = os::malloc(1024 * 1024, mtTest);
 139   nmtMtTest2 = os::malloc(256 * 1024, mtTest);
 140   os::free(mem, mtTest);
 141   nmtMtTest3 = os::malloc(128 * 1024, mtTest);
 142 
 143   return true;
 144 WB_END
 145 
 146 // Free the memory allocated by NMTAllocTest
 147 WB_ENTRY(jboolean, WB_NMTFreeTestMemory(JNIEnv* env))
 148 
 149   if (nmtMtTest1 == NULL || nmtMtTest2 == NULL || nmtMtTest3 == NULL) {
 150     return false;
 151   }
 152 
 153   os::free(nmtMtTest1, mtTest);
 154   nmtMtTest1 = NULL;
 155   os::free(nmtMtTest2, mtTest);
 156   nmtMtTest2 = NULL;
 157   os::free(nmtMtTest3, mtTest);
 158   nmtMtTest3 = NULL;
 159 
 160   return true;
 161 WB_END
 162 
 163 // Block until the current generation of NMT data to be merged, used to reliably test the NMT feature
 164 WB_ENTRY(jboolean, WB_NMTWaitForDataMerge(JNIEnv* env))
 165 
 166   if (!MemTracker::is_on() || MemTracker::shutdown_in_progress()) {
 167     return false;
 168   }
 169 
 170   return MemTracker::wbtest_wait_for_data_merge();
 171 WB_END
 172 
 173 #endif // INCLUDE_NMT
 174 
 175 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 176   assert(method != NULL, "method should not be null");
 177   ThreadToNativeFromVM ttn(thread);
 178   return env->FromReflectedMethod(method);
 179 }
 180 
 181 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 182   MutexLockerEx mu(Compile_lock);
 183   CodeCache::mark_all_nmethods_for_deoptimization();
 184   VM_Deoptimize op;
 185   VMThread::execute(&op);
 186 WB_END
 187 
 188 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method))
 189   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 190   MutexLockerEx mu(Compile_lock);
 191   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 192   int result = 0;
 193   nmethod* code = mh->code();
 194   if (code != NULL) {
 195     code->mark_for_deoptimization();
 196     ++result;
 197   }
 198   result += CodeCache::mark_for_deoptimization(mh());
 199   if (result > 0) {
 200     VM_Deoptimize op;
 201     VMThread::execute(&op);
 202   }
 203   return result;
 204 WB_END
 205 
 206 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method))
 207   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 208   MutexLockerEx mu(Compile_lock);
 209   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 210   nmethod* code = mh->code();
 211   if (code == NULL) {
 212     return JNI_FALSE;
 213   }
 214   return (code->is_alive() && !code->is_marked_for_deoptimization());
 215 WB_END
 216 
 217 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level))
 218   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 219   MutexLockerEx mu(Compile_lock);
 220   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 221   return CompilationPolicy::can_be_compiled(mh, comp_level);
 222 WB_END
 223 
 224 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 225   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 226   MutexLockerEx mu(Compile_lock);
 227   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 228   return mh->queued_for_compilation();
 229 WB_END
 230 
 231 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method))
 232   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 233   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 234   nmethod* code = mh->code();
 235   return (code != NULL ? code->comp_level() : CompLevel_none);
 236 WB_END
 237 
 238 
 239 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method))
 240   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 241   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 242   mh->set_not_compilable();
 243 WB_END
 244 
 245 WB_ENTRY(jboolean, WB_SetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 246   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 247   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 248   bool result = mh->dont_inline();
 249   mh->set_dont_inline(value == JNI_TRUE);
 250   return result;
 251 WB_END
 252 
 253 WB_ENTRY(jint, WB_GetCompileQueuesSize(JNIEnv* env, jobject o))
 254   return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 255          CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 256 WB_END
 257 
 258 WB_ENTRY(jboolean, WB_SetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 259   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 260   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 261   bool result = mh->force_inline();
 262   mh->set_force_inline(value == JNI_TRUE);
 263   return result;
 264 WB_END
 265 
 266 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level))
 267   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 268   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 269   nmethod* nm = CompileBroker::compile_method(mh, InvocationEntryBci, comp_level, mh, mh->invocation_count(), "WhiteBox", THREAD);
 270   MutexLockerEx mu(Compile_lock);
 271   return (mh->queued_for_compilation() || nm != NULL);
 272 WB_END
 273 
 274 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
 275   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 276   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 277   MutexLockerEx mu(Compile_lock);
 278   MethodData* mdo = mh->method_data();
 279 
 280   if (mdo != NULL) {
 281     mdo->init();
 282     ResourceMark rm;
 283     int arg_count = mdo->method()->size_of_parameters();
 284     for (int i = 0; i < arg_count; i++) {
 285       mdo->set_arg_modified(i, 0);
 286     }
 287   }
 288 
 289   mh->backedge_counter()->init();
 290   mh->invocation_counter()->init();
 291   mh->set_interpreter_invocation_count(0);
 292   mh->set_interpreter_throwout_count(0);
 293   mh->clear_not_c1_compilable();
 294   mh->clear_not_c2_compilable();
 295   mh->clear_not_c2_osr_compilable();
 296   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
 297 
 298 #ifdef TIERED
 299   mh->set_rate(0.0F);
 300   mh->set_prev_event_count(0);
 301   mh->set_prev_time(0);
 302 #endif
 303 WB_END
 304 
 305 //Some convenience methods to deal with objects from java
 306 int WhiteBox::offset_for_field(const char* field_name, oop object,
 307     Symbol* signature_symbol) {
 308   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
 309   Thread* THREAD = Thread::current();
 310 
 311   //Get the class of our object
 312   Klass* arg_klass = object->klass();
 313   //Turn it into an instance-klass
 314   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
 315 
 316   //Create symbols to look for in the class
 317   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
 318       THREAD);
 319 
 320   //To be filled in with an offset of the field we're looking for
 321   fieldDescriptor fd;
 322 
 323   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
 324   if (res == NULL) {
 325     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
 326         name_symbol->as_C_string());
 327     fatal("Invalid layout of preloaded class");
 328   }
 329 
 330   //fetch the field at the offset we've found
 331   int dest_offset = fd.offset();
 332 
 333   return dest_offset;
 334 }
 335 
 336 
 337 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
 338   int offset = offset_for_field(field_name, object,
 339       vmSymbols::string_signature());
 340   oop string = object->obj_field(offset);
 341   if (string == NULL) {
 342     return NULL;
 343   }
 344   const char* ret = java_lang_String::as_utf8_string(string);
 345   return ret;
 346 }
 347 
 348 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
 349   int offset =
 350       offset_for_field(field_name, object, vmSymbols::bool_signature());
 351   bool ret = (object->bool_field(offset) == JNI_TRUE);
 352   return ret;
 353 }
 354 
 355 
 356 #define CC (char*)
 357 
 358 static JNINativeMethod methods[] = {
 359   {CC"getObjectAddress",   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
 360   {CC"getHeapOopSize",     CC"()I",                   (void*)&WB_GetHeapOopSize    },
 361   {CC"isClassAlive0",      CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
 362   {CC"parseCommandLine",
 363       CC"(Ljava/lang/String;[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
 364       (void*) &WB_ParseCommandLine
 365   },
 366 #if INCLUDE_ALL_GCS
 367   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
 368   {CC"g1IsHumongous",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
 369   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
 370   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
 371 #endif // INCLUDE_ALL_GCS
 372 #ifdef INCLUDE_NMT
 373   {CC"NMTAllocTest",       CC"()Z",                   (void*)&WB_NMTAllocTest      },
 374   {CC"NMTFreeTestMemory",  CC"()Z",                   (void*)&WB_NMTFreeTestMemory },
 375   {CC"NMTWaitForDataMerge",CC"()Z",                   (void*)&WB_NMTWaitForDataMerge},
 376 #endif // INCLUDE_NMT
 377   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
 378   {CC"deoptimizeMethod",   CC"(Ljava/lang/reflect/Method;)I",
 379                                                       (void*)&WB_DeoptimizeMethod  },
 380   {CC"isMethodCompiled",   CC"(Ljava/lang/reflect/Method;)Z",
 381                                                       (void*)&WB_IsMethodCompiled  },
 382   {CC"isMethodCompilable", CC"(Ljava/lang/reflect/Method;I)Z",
 383                                                       (void*)&WB_IsMethodCompilable},
 384   {CC"isMethodQueuedForCompilation",
 385       CC"(Ljava/lang/reflect/Method;)Z",              (void*)&WB_IsMethodQueuedForCompilation},
 386   {CC"makeMethodNotCompilable",
 387       CC"(Ljava/lang/reflect/Method;)V",              (void*)&WB_MakeMethodNotCompilable},
 388   {CC"setDontInlineMethod",
 389       CC"(Ljava/lang/reflect/Method;Z)Z",             (void*)&WB_SetDontInlineMethod},
 390   {CC"getMethodCompilationLevel",
 391       CC"(Ljava/lang/reflect/Method;)I",              (void*)&WB_GetMethodCompilationLevel},
 392   {CC"getCompileQueuesSize",
 393       CC"()I",                                        (void*)&WB_GetCompileQueuesSize},
 394   {CC"setForceInlineMethod",
 395       CC"(Ljava/lang/reflect/Method;Z)Z",             (void*)&WB_SetForceInlineMethod},
 396   {CC"enqueueMethodForCompilation",
 397       CC"(Ljava/lang/reflect/Method;I)Z",             (void*)&WB_EnqueueMethodForCompilation},
 398   {CC"clearMethodState",
 399       CC"(Ljava/lang/reflect/Method;)V",              (void*)&WB_ClearMethodState},
 400 };
 401 
 402 #undef CC
 403 
 404 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
 405   {
 406     if (WhiteBoxAPI) {
 407       // Make sure that wbclass is loaded by the null classloader
 408       instanceKlassHandle ikh = instanceKlassHandle(JNIHandles::resolve(wbclass)->klass());
 409       Handle loader(ikh->class_loader());
 410       if (loader.is_null()) {
 411         ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
 412         jint result = env->RegisterNatives(wbclass, methods, sizeof(methods)/sizeof(methods[0]));
 413         if (result == 0) {
 414           WhiteBox::set_used();
 415         }
 416       }
 417     }
 418   }
 419 JVM_END