1 /*
   2  * Copyright (c) 2012, 2016, 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 <new>
  28 
  29 #include "classfile/classLoaderData.hpp"
  30 #include "classfile/stringTable.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/methodMatcher.hpp"
  33 #include "jvmtifiles/jvmtiEnv.hpp"
  34 #include "memory/metadataFactory.hpp"
  35 #include "memory/metaspaceShared.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "memory/universe.hpp"
  38 #include "oops/constantPool.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/wbtestmethods/parserTests.hpp"
  41 #include "prims/whitebox.hpp"
  42 #include "runtime/arguments.hpp"
  43 #include "runtime/compilationPolicy.hpp"
  44 #include "runtime/deoptimization.hpp"
  45 #include "runtime/interfaceSupport.hpp"
  46 #include "runtime/javaCalls.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/sweeper.hpp"
  49 #include "runtime/thread.hpp"
  50 #include "runtime/vm_version.hpp"
  51 #include "utilities/array.hpp"
  52 #include "utilities/debug.hpp"
  53 #include "utilities/exceptions.hpp"
  54 #include "utilities/macros.hpp"
  55 #if INCLUDE_ALL_GCS
  56 #include "gc/g1/concurrentMarkThread.hpp"
  57 #include "gc/g1/g1CollectedHeap.inline.hpp"
  58 #include "gc/g1/g1ConcurrentMark.hpp"
  59 #include "gc/g1/heapRegionRemSet.hpp"
  60 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  61 #include "gc/parallel/adjoiningGenerations.hpp"
  62 #endif // INCLUDE_ALL_GCS
  63 #if INCLUDE_NMT
  64 #include "services/mallocSiteTable.hpp"
  65 #include "services/memTracker.hpp"
  66 #include "utilities/nativeCallStack.hpp"
  67 #endif // INCLUDE_NMT
  68 
  69 
  70 #define SIZE_T_MAX_VALUE ((size_t) -1)
  71 
  72 bool WhiteBox::_used = false;
  73 volatile bool WhiteBox::compilation_locked = false;
  74 
  75 class VM_WhiteBoxOperation : public VM_Operation {
  76  public:
  77   VM_WhiteBoxOperation()                         { }
  78   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
  79   bool allow_nested_vm_operations() const        { return true; }
  80 };
  81 
  82 
  83 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
  84   return (jlong)(void*)JNIHandles::resolve(obj);
  85 WB_END
  86 
  87 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
  88   return heapOopSize;
  89 WB_END
  90 
  91 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
  92   return os::vm_page_size();
  93 WB_END
  94 
  95 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
  96   return os::vm_allocation_granularity();
  97 WB_END
  98 
  99 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 100   return os::large_page_size();
 101 WB_END
 102 
 103 class WBIsKlassAliveClosure : public KlassClosure {
 104     Symbol* _name;
 105     bool _found;
 106 public:
 107     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
 108 
 109     void do_klass(Klass* k) {
 110       if (_found) return;
 111       Symbol* ksym = k->name();
 112       if (ksym->fast_compare(_name) == 0) {
 113         _found = true;
 114       }
 115     }
 116 
 117     bool found() const {
 118         return _found;
 119     }
 120 };
 121 
 122 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
 123   Handle h_name = JNIHandles::resolve(name);
 124   if (h_name.is_null()) return false;
 125   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
 126   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 127 
 128   WBIsKlassAliveClosure closure(sym);
 129   ClassLoaderDataGraph::classes_do(&closure);
 130 
 131   return closure.found();
 132 WB_END
 133 
 134 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 135 #if INCLUDE_JVMTI
 136   ResourceMark rm;
 137   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 138   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 139   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 140   assert(err == JVMTI_ERROR_NONE, "must not fail");
 141 #endif
 142 }
 143 WB_END
 144 
 145 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 146 #if INCLUDE_JVMTI
 147   ResourceMark rm;
 148   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 149   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 150   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 151   assert(err == JVMTI_ERROR_NONE, "must not fail");
 152 #endif
 153 }
 154 WB_END
 155 
 156 
 157 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 158   return (jlong)Arguments::max_heap_for_compressed_oops();
 159 }
 160 WB_END
 161 
 162 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 163   CollectorPolicy * p = Universe::heap()->collector_policy();
 164   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap "
 165     SIZE_FORMAT " Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 166     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
 167     p->space_alignment(), p->heap_alignment());
 168 }
 169 WB_END
 170 
 171 #ifndef PRODUCT
 172 // Forward declaration
 173 void TestReservedSpace_test();
 174 void TestReserveMemorySpecial_test();
 175 void TestVirtualSpace_test();
 176 void TestMetaspaceAux_test();
 177 #endif
 178 
 179 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 180 #ifndef PRODUCT
 181   TestReservedSpace_test();
 182   TestReserveMemorySpecial_test();
 183   TestVirtualSpace_test();
 184   TestMetaspaceAux_test();
 185 #endif
 186 WB_END
 187 
 188 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 189   size_t granularity = os::vm_allocation_granularity();
 190   ReservedHeapSpace rhs(100 * granularity, granularity, false);
 191   VirtualSpace vs;
 192   vs.initialize(rhs, 50 * granularity);
 193 
 194   // Check if constraints are complied
 195   if (!( UseCompressedOops && rhs.base() != NULL &&
 196          Universe::narrow_oop_base() != NULL &&
 197          Universe::narrow_oop_use_implicit_null_checks() )) {
 198     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 199                   "\tUseCompressedOops is %d\n"
 200                   "\trhs.base() is " PTR_FORMAT "\n"
 201                   "\tUniverse::narrow_oop_base() is " PTR_FORMAT "\n"
 202                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
 203                   UseCompressedOops,
 204                   p2i(rhs.base()),
 205                   p2i(Universe::narrow_oop_base()),
 206                   Universe::narrow_oop_use_implicit_null_checks());
 207     return;
 208   }
 209   tty->print_cr("Reading from no access area... ");
 210   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 211                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 212 WB_END
 213 
 214 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 215                                            size_t magnitude, size_t iterations) {
 216   size_t granularity = os::vm_allocation_granularity();
 217   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false);
 218   VirtualSpace vs;
 219   if (!vs.initialize(rhs, 0)) {
 220     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 221     return 3;
 222   }
 223 
 224   long seed = os::random();
 225   tty->print_cr("Random seed is %ld", seed);
 226   os::init_random(seed);
 227 
 228   for (size_t i = 0; i < iterations; i++) {
 229 
 230     // Whether we will shrink or grow
 231     bool shrink = os::random() % 2L == 0;
 232 
 233     // Get random delta to resize virtual space
 234     size_t delta = (size_t)os::random() % magnitude;
 235 
 236     // If we are about to shrink virtual space below zero, then expand instead
 237     if (shrink && vs.committed_size() < delta) {
 238       shrink = false;
 239     }
 240 
 241     // Resizing by delta
 242     if (shrink) {
 243       vs.shrink_by(delta);
 244     } else {
 245       // If expanding fails expand_by will silently return false
 246       vs.expand_by(delta, true);
 247     }
 248   }
 249   return 0;
 250 }
 251 
 252 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 253         jlong reserved_space_size, jlong magnitude, jlong iterations))
 254   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 255                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 256                 iterations);
 257   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 258     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 259     return 1;
 260   }
 261 
 262   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 263   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 264   if (sizeof(size_t) < sizeof(jlong)) {
 265     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 266     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 267         || iterations > size_t_max_value) {
 268       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 269       return 2;
 270     }
 271   }
 272 
 273   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 274                                         (size_t) magnitude, (size_t) iterations);
 275 WB_END
 276 
 277 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 278   oop p = JNIHandles::resolve(obj);
 279 #if INCLUDE_ALL_GCS
 280   if (UseG1GC) {
 281     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 282     const HeapRegion* hr = g1->heap_region_containing(p);
 283     if (hr == NULL) {
 284       return false;
 285     }
 286     return !(hr->is_young());
 287   } else if (UseParallelGC) {
 288     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 289     return !psh->is_in_young(p);
 290   }
 291 #endif // INCLUDE_ALL_GCS
 292   GenCollectedHeap* gch = GenCollectedHeap::heap();
 293   return !gch->is_in_young(p);
 294 WB_END
 295 
 296 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 297   oop p = JNIHandles::resolve(obj);
 298   return p->size() * HeapWordSize;
 299 WB_END
 300 
 301 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 302   size_t alignment = Universe::heap()->collector_policy()->space_alignment();
 303   return (jlong)alignment;
 304 WB_END
 305 
 306 #if INCLUDE_ALL_GCS
 307 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 308   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 309   oop result = JNIHandles::resolve(obj);
 310   const HeapRegion* hr = g1->heap_region_containing(result);
 311   return hr->is_humongous();
 312 WB_END
 313 
 314 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 315   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 316   const HeapRegion* hr = g1->heap_region_containing((void*) addr);
 317   return hr->is_humongous();
 318 WB_END
 319 
 320 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 321   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 322   const HeapRegion* hr = g1->heap_region_containing((void*) addr);
 323   return hr->is_free();
 324 WB_END
 325 
 326 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 327   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 328   size_t nr = g1->max_regions();
 329   return (jlong)nr;
 330 WB_END
 331 
 332 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 333   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 334   size_t nr = g1->num_free_regions();
 335   return (jlong)nr;
 336 WB_END
 337 
 338 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 339   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 340   return g1h->concurrent_mark()->cmThread()->during_cycle();
 341 WB_END
 342 
 343 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 344   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 345   if (!g1h->concurrent_mark()->cmThread()->during_cycle()) {
 346     g1h->collect(GCCause::_wb_conc_mark);
 347     return true;
 348   }
 349   return false;
 350 WB_END
 351 
 352 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 353   return (jint)HeapRegion::GrainBytes;
 354 WB_END
 355 
 356 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 357   ParallelScavengeHeap* ps = ParallelScavengeHeap::heap();
 358   size_t alignment = ps->gens()->virtual_spaces()->alignment();
 359   return (jlong)alignment;
 360 WB_END
 361 
 362 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 363   size_t alignment = ParallelScavengeHeap::heap()->generation_alignment();
 364   return (jlong)alignment;
 365 WB_END
 366 
 367 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 368   ResourceMark rm(THREAD);
 369   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 370   MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 371   Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 372   return JNIHandles::make_local(env, h());
 373 WB_END
 374 #endif // INCLUDE_ALL_GCS
 375 
 376 #if INCLUDE_NMT
 377 // Alloc memory using the test memory type so that we can use that to see if
 378 // NMT picks it up correctly
 379 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 380   jlong addr = 0;
 381   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 382   return addr;
 383 WB_END
 384 
 385 // Alloc memory with pseudo call stack. The test can create psudo malloc
 386 // allocation site to stress the malloc tracking.
 387 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 388   address pc = (address)(size_t)pseudo_stack;
 389   NativeCallStack stack(&pc, 1);
 390   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 391 WB_END
 392 
 393 // Free the memory allocated by NMTAllocTest
 394 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 395   os::free((void*)(uintptr_t)mem);
 396 WB_END
 397 
 398 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 399   jlong addr = 0;
 400 
 401   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 402   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 403 
 404   return addr;
 405 WB_END
 406 
 407 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 408   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 409   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 410 WB_END
 411 
 412 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 413   os::uncommit_memory((char *)(uintptr_t)addr, size);
 414 WB_END
 415 
 416 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 417   os::release_memory((char *)(uintptr_t)addr, size);
 418 WB_END
 419 
 420 WB_ENTRY(jboolean, WB_NMTChangeTrackingLevel(JNIEnv* env))
 421   // Test that we can downgrade NMT levels but not upgrade them.
 422   if (MemTracker::tracking_level() == NMT_off) {
 423     MemTracker::transition_to(NMT_off);
 424     return MemTracker::tracking_level() == NMT_off;
 425   } else {
 426     assert(MemTracker::tracking_level() == NMT_detail, "Should start out as detail tracking");
 427     MemTracker::transition_to(NMT_summary);
 428     assert(MemTracker::tracking_level() == NMT_summary, "Should be summary now");
 429 
 430     // Can't go to detail once NMT is set to summary.
 431     MemTracker::transition_to(NMT_detail);
 432     assert(MemTracker::tracking_level() == NMT_summary, "Should still be summary now");
 433 
 434     // Shutdown sets tracking level to minimal.
 435     MemTracker::shutdown();
 436     assert(MemTracker::tracking_level() == NMT_minimal, "Should be minimal now");
 437 
 438     // Once the tracking level is minimal, we cannot increase to summary.
 439     // The code ignores this request instead of asserting because if the malloc site
 440     // table overflows in another thread, it tries to change the code to summary.
 441     MemTracker::transition_to(NMT_summary);
 442     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 443 
 444     // Really can never go up to detail, verify that the code would never do this.
 445     MemTracker::transition_to(NMT_detail);
 446     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 447     return MemTracker::tracking_level() == NMT_minimal;
 448   }
 449 WB_END
 450 
 451 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 452   int hash_size = MallocSiteTable::hash_buckets();
 453   assert(hash_size > 0, "NMT hash_size should be > 0");
 454   return (jint)hash_size;
 455 WB_END
 456 #endif // INCLUDE_NMT
 457 
 458 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 459   assert(method != NULL, "method should not be null");
 460   ThreadToNativeFromVM ttn(thread);
 461   return env->FromReflectedMethod(method);
 462 }
 463 
 464 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 465 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 466  private:
 467   int _result;
 468   const bool _make_not_entrant;
 469  public:
 470   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 471         _result(0), _make_not_entrant(make_not_entrant) { }
 472   int  result() const { return _result; }
 473 
 474   void doit() {
 475     for (JavaThread* t = Threads::first(); t != NULL; t = t->next()) {
 476       if (t->has_last_Java_frame()) {
 477         for (StackFrameStream fst(t, UseBiasedLocking); !fst.is_done(); fst.next()) {
 478           frame* f = fst.current();
 479           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 480             RegisterMap* reg_map = fst.register_map();
 481             Deoptimization::deoptimize(t, *f, reg_map);
 482             if (_make_not_entrant) {
 483                 nmethod* nm = CodeCache::find_nmethod(f->pc());
 484                 assert(nm != NULL, "sanity check");
 485                 nm->make_not_entrant();
 486             }
 487             ++_result;
 488           }
 489         }
 490       }
 491     }
 492   }
 493 };
 494 
 495 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 496   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 497   VMThread::execute(&op);
 498   return op.result();
 499 WB_END
 500 
 501 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 502   MutexLockerEx mu(Compile_lock);
 503   CodeCache::mark_all_nmethods_for_deoptimization();
 504   VM_Deoptimize op;
 505   VMThread::execute(&op);
 506 WB_END
 507 
 508 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 509   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 510   int result = 0;
 511   CHECK_JNI_EXCEPTION_(env, result);
 512   MutexLockerEx mu(Compile_lock);
 513   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 514   if (is_osr) {
 515     result += mh->mark_osr_nmethods();
 516   } else if (mh->code() != NULL) {
 517     mh->code()->mark_for_deoptimization();
 518     ++result;
 519   }
 520   result += CodeCache::mark_for_deoptimization(mh());
 521   if (result > 0) {
 522     VM_Deoptimize op;
 523     VMThread::execute(&op);
 524   }
 525   return result;
 526 WB_END
 527 
 528 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 529   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 530   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 531   MutexLockerEx mu(Compile_lock);
 532   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 533   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 534   if (code == NULL) {
 535     return JNI_FALSE;
 536   }
 537   return (code->is_alive() && !code->is_marked_for_deoptimization());
 538 WB_END
 539 
 540 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 541   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 542   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 543   MutexLockerEx mu(Compile_lock);
 544   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 545   if (is_osr) {
 546     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 547   } else {
 548     return CompilationPolicy::can_be_compiled(mh, comp_level);
 549   }
 550 WB_END
 551 
 552 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 553   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 554   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 555   MutexLockerEx mu(Compile_lock);
 556   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 557   return mh->queued_for_compilation();
 558 WB_END
 559 
 560 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 561   if (compLevel < CompLevel_none || compLevel > CompLevel_highest_tier) {
 562     return false; // Intrinsic is not available on a non-existent compilation level.
 563   }
 564   jmethodID method_id, compilation_context_id;
 565   method_id = reflected_method_to_jmid(thread, env, method);
 566   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 567   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 568 
 569   DirectiveSet* directive;
 570   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 571   if (compilation_context != NULL) {
 572     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 573     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 574     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 575     directive = DirectivesStack::getMatchingDirective(cch, comp);
 576   } else {
 577     // Calling with NULL matches default directive
 578     directive = DirectivesStack::getDefaultDirective(comp);
 579   }
 580   bool result = CompileBroker::compiler(compLevel)->is_intrinsic_available(mh, directive);
 581   DirectivesStack::release(directive);
 582   return result;
 583 WB_END
 584 
 585 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 586   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 587   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 588   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 589   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 590   return (code != NULL ? code->comp_level() : CompLevel_none);
 591 WB_END
 592 
 593 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 594   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 595   CHECK_JNI_EXCEPTION(env);
 596   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 597   if (is_osr) {
 598     mh->set_not_osr_compilable(comp_level, true /* report */, "WhiteBox");
 599   } else {
 600     mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
 601   }
 602 WB_END
 603 
 604 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 605   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 606   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 607   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 608   nmethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 609   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 610 WB_END
 611 
 612 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 613   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 614   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 615   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 616   bool result = mh->dont_inline();
 617   mh->set_dont_inline(value == JNI_TRUE);
 618   return result;
 619 WB_END
 620 
 621 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 622   if (comp_level == CompLevel_any) {
 623     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 624         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 625   } else {
 626     return CompileBroker::queue_size(comp_level);
 627   }
 628 WB_END
 629 
 630 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 631   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 632   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 633   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 634   bool result = mh->force_inline();
 635   mh->set_force_inline(value == JNI_TRUE);
 636   return result;
 637 WB_END
 638 
 639 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
 640   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 641   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 642   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 643   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), "WhiteBox", THREAD);
 644   MutexLockerEx mu(Compile_lock);
 645   return (mh->queued_for_compilation() || nm != NULL);
 646 WB_END
 647 
 648 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
 649   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 650   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 651 
 652   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 653   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
 654   bool result = directive->PrintAssemblyOption;
 655   DirectivesStack::release(directive);
 656 
 657   return result;
 658 WB_END
 659 
 660 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
 661   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 662   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 663 
 664   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 665 
 666   ResourceMark rm;
 667   const char* error_msg = NULL;
 668   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
 669   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
 670 
 671   if (m == NULL) {
 672     assert(error_msg != NULL, "Always have an error message");
 673     tty->print_cr("Got error: %s", error_msg);
 674     return -1; // Pattern failed
 675   }
 676 
 677   // Pattern works - now check if it matches
 678   int result;
 679   if (m->match(mh, InlineMatcher::force_inline)) {
 680     result = 2; // Force inline match
 681   } else if (m->match(mh, InlineMatcher::dont_inline)) {
 682     result = 1; // Dont inline match
 683   } else {
 684     result = 0; // No match
 685   }
 686   delete m;
 687   return result;
 688 WB_END
 689 
 690 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
 691   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 692   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 693 
 694   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 695 
 696   ResourceMark rm;
 697   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
 698 
 699   const char* error_msg = NULL;
 700 
 701   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg);
 702   if (m == NULL) {
 703     assert(error_msg != NULL, "Must have error_msg");
 704     tty->print_cr("Got error: %s", error_msg);
 705     return -1;
 706   }
 707 
 708   // Pattern works - now check if it matches
 709   int result = m->matches(mh);
 710   delete m;
 711   assert(result == 0 || result == 1, "Result out of range");
 712   return result;
 713 WB_END
 714 
 715 class AlwaysFalseClosure : public BoolObjectClosure {
 716  public:
 717   bool do_object_b(oop p) { return false; }
 718 };
 719 
 720 static AlwaysFalseClosure always_false;
 721 
 722 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
 723   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 724   CHECK_JNI_EXCEPTION(env);
 725   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 726   MutexLockerEx mu(Compile_lock);
 727   MethodData* mdo = mh->method_data();
 728   MethodCounters* mcs = mh->method_counters();
 729 
 730   if (mdo != NULL) {
 731     mdo->init();
 732     ResourceMark rm;
 733     int arg_count = mdo->method()->size_of_parameters();
 734     for (int i = 0; i < arg_count; i++) {
 735       mdo->set_arg_modified(i, 0);
 736     }
 737     MutexLockerEx mu(mdo->extra_data_lock());
 738     mdo->clean_method_data(&always_false);
 739   }
 740 
 741   mh->clear_not_c1_compilable();
 742   mh->clear_not_c2_compilable();
 743   mh->clear_not_c2_osr_compilable();
 744   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
 745   if (mcs != NULL) {
 746     mcs->backedge_counter()->init();
 747     mcs->invocation_counter()->init();
 748     mcs->set_interpreter_invocation_count(0);
 749     mcs->set_interpreter_throwout_count(0);
 750 
 751 #ifdef TIERED
 752     mcs->set_rate(0.0F);
 753     mh->set_prev_event_count(0);
 754     mh->set_prev_time(0);
 755 #endif
 756   }
 757 WB_END
 758 
 759 template <typename T>
 760 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, Flag::Error (*TAt)(const char*, T*, bool, bool)) {
 761   if (name == NULL) {
 762     return false;
 763   }
 764   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 765   const char* flag_name = env->GetStringUTFChars(name, NULL);
 766   Flag::Error result = (*TAt)(flag_name, value, true, true);
 767   env->ReleaseStringUTFChars(name, flag_name);
 768   return (result == Flag::SUCCESS);
 769 }
 770 
 771 template <typename T>
 772 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, Flag::Error (*TAtPut)(const char*, T*, Flag::Flags)) {
 773   if (name == NULL) {
 774     return false;
 775   }
 776   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 777   const char* flag_name = env->GetStringUTFChars(name, NULL);
 778   Flag::Error result = (*TAtPut)(flag_name, value, Flag::INTERNAL);
 779   env->ReleaseStringUTFChars(name, flag_name);
 780   return (result == Flag::SUCCESS);
 781 }
 782 
 783 template <typename T>
 784 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
 785   ResourceMark rm(thread);
 786   jclass clazz = env->FindClass(name->as_C_string());
 787   CHECK_JNI_EXCEPTION_(env, NULL);
 788   jmethodID methodID = env->GetStaticMethodID(clazz,
 789         vmSymbols::valueOf_name()->as_C_string(),
 790         sig->as_C_string());
 791   CHECK_JNI_EXCEPTION_(env, NULL);
 792   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
 793   CHECK_JNI_EXCEPTION_(env, NULL);
 794   return result;
 795 }
 796 
 797 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
 798   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
 799 }
 800 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
 801   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
 802 }
 803 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
 804   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
 805 }
 806 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
 807   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
 808 }*/
 809 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
 810   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
 811 }
 812 
 813 static Flag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
 814   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 815   const char* flag_name = env->GetStringUTFChars(name, NULL);
 816   Flag* result = Flag::find_flag(flag_name, strlen(flag_name), true, true);
 817   env->ReleaseStringUTFChars(name, flag_name);
 818   return result;
 819 }
 820 
 821 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
 822   Flag* flag = getVMFlag(thread, env, name);
 823   return (flag != NULL) && flag->is_constant_in_binary();
 824 WB_END
 825 
 826 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
 827   Flag* flag = getVMFlag(thread, env, name);
 828   return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
 829 WB_END
 830 
 831 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
 832   bool result;
 833   if (GetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAt)) {
 834     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 835     return booleanBox(thread, env, result);
 836   }
 837   return NULL;
 838 WB_END
 839 
 840 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
 841   int result;
 842   if (GetVMFlag <int> (thread, env, name, &result, &CommandLineFlags::intAt)) {
 843     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 844     return longBox(thread, env, result);
 845   }
 846   return NULL;
 847 WB_END
 848 
 849 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
 850   uint result;
 851   if (GetVMFlag <uint> (thread, env, name, &result, &CommandLineFlags::uintAt)) {
 852     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 853     return longBox(thread, env, result);
 854   }
 855   return NULL;
 856 WB_END
 857 
 858 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
 859   intx result;
 860   if (GetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAt)) {
 861     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 862     return longBox(thread, env, result);
 863   }
 864   return NULL;
 865 WB_END
 866 
 867 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
 868   uintx result;
 869   if (GetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAt)) {
 870     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 871     return longBox(thread, env, result);
 872   }
 873   return NULL;
 874 WB_END
 875 
 876 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
 877   uint64_t result;
 878   if (GetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAt)) {
 879     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 880     return longBox(thread, env, result);
 881   }
 882   return NULL;
 883 WB_END
 884 
 885 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
 886   uintx result;
 887   if (GetVMFlag <size_t> (thread, env, name, &result, &CommandLineFlags::size_tAt)) {
 888     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 889     return longBox(thread, env, result);
 890   }
 891   return NULL;
 892 WB_END
 893 
 894 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
 895   double result;
 896   if (GetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAt)) {
 897     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 898     return doubleBox(thread, env, result);
 899   }
 900   return NULL;
 901 WB_END
 902 
 903 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
 904   ccstr ccstrResult;
 905   if (GetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAt)) {
 906     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 907     jstring result = env->NewStringUTF(ccstrResult);
 908     CHECK_JNI_EXCEPTION_(env, NULL);
 909     return result;
 910   }
 911   return NULL;
 912 WB_END
 913 
 914 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
 915   bool result = value == JNI_TRUE ? true : false;
 916   SetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAtPut);
 917 WB_END
 918 
 919 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 920   int result = value;
 921   SetVMFlag <int> (thread, env, name, &result, &CommandLineFlags::intAtPut);
 922 WB_END
 923 
 924 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 925   uint result = value;
 926   SetVMFlag <uint> (thread, env, name, &result, &CommandLineFlags::uintAtPut);
 927 WB_END
 928 
 929 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 930   intx result = value;
 931   SetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAtPut);
 932 WB_END
 933 
 934 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 935   uintx result = value;
 936   SetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAtPut);
 937 WB_END
 938 
 939 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 940   uint64_t result = value;
 941   SetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAtPut);
 942 WB_END
 943 
 944 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 945   size_t result = value;
 946   SetVMFlag <size_t> (thread, env, name, &result, &CommandLineFlags::size_tAtPut);
 947 WB_END
 948 
 949 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
 950   double result = value;
 951   SetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAtPut);
 952 WB_END
 953 
 954 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
 955   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 956   const char* ccstrValue = (value == NULL) ? NULL : env->GetStringUTFChars(value, NULL);
 957   ccstr ccstrResult = ccstrValue;
 958   bool needFree;
 959   {
 960     ThreadInVMfromNative ttvfn(thread); // back to VM
 961     needFree = SetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAtPut);
 962   }
 963   if (value != NULL) {
 964     env->ReleaseStringUTFChars(value, ccstrValue);
 965   }
 966   if (needFree) {
 967     FREE_C_HEAP_ARRAY(char, ccstrResult);
 968   }
 969 WB_END
 970 
 971 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
 972   WhiteBox::compilation_locked = true;
 973 WB_END
 974 
 975 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
 976   MonitorLockerEx mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
 977   WhiteBox::compilation_locked = false;
 978   mo.notify_all();
 979 WB_END
 980 
 981 WB_ENTRY(void, WB_ForceNMethodSweep(JNIEnv* env, jobject o))
 982   // Force a code cache sweep and block until it finished
 983   NMethodSweeper::force_sweep();
 984 WB_END
 985 
 986 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
 987   ResourceMark rm(THREAD);
 988   int len;
 989   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
 990   return (StringTable::lookup(name, len) != NULL);
 991 WB_END
 992 
 993 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
 994   Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(true);
 995   Universe::heap()->collect(GCCause::_last_ditch_collection);
 996 #if INCLUDE_ALL_GCS
 997   if (UseG1GC) {
 998     // Needs to be cleared explicitly for G1
 999     Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(false);
1000   }
1001 #endif // INCLUDE_ALL_GCS
1002 WB_END
1003 
1004 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1005   Universe::heap()->collect(GCCause::_wb_young_gc);
1006 WB_END
1007 
1008 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1009   // static+volatile in order to force the read to happen
1010   // (not be eliminated by the compiler)
1011   static char c;
1012   static volatile char* p;
1013 
1014   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
1015   if (p == NULL) {
1016     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1017   }
1018 
1019   c = *p;
1020 WB_END
1021 
1022 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1023   const char* features = VM_Version::features_string();
1024   ThreadToNativeFromVM ttn(thread);
1025   jstring features_string = env->NewStringUTF(features);
1026 
1027   CHECK_JNI_EXCEPTION_(env, NULL);
1028 
1029   return features_string;
1030 WB_END
1031 
1032 int WhiteBox::get_blob_type(const CodeBlob* code) {
1033   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1034   return CodeCache::get_code_heap(code)->code_blob_type();
1035 }
1036 
1037 CodeHeap* WhiteBox::get_code_heap(int blob_type) {
1038   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1039   return CodeCache::get_code_heap(blob_type);
1040 }
1041 
1042 struct CodeBlobStub {
1043   CodeBlobStub(const CodeBlob* blob) :
1044       name(os::strdup(blob->name())),
1045       size(blob->size()),
1046       blob_type(WhiteBox::get_blob_type(blob)),
1047       address((jlong) blob) { }
1048   ~CodeBlobStub() { os::free((void*) name); }
1049   const char* const name;
1050   const jint        size;
1051   const jint        blob_type;
1052   const jlong       address;
1053 };
1054 
1055 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1056   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1057   CHECK_JNI_EXCEPTION_(env, NULL);
1058   jobjectArray result = env->NewObjectArray(4, clazz, NULL);
1059 
1060   jstring name = env->NewStringUTF(cb->name);
1061   CHECK_JNI_EXCEPTION_(env, NULL);
1062   env->SetObjectArrayElement(result, 0, name);
1063 
1064   jobject obj = integerBox(thread, env, cb->size);
1065   CHECK_JNI_EXCEPTION_(env, NULL);
1066   env->SetObjectArrayElement(result, 1, obj);
1067 
1068   obj = integerBox(thread, env, cb->blob_type);
1069   CHECK_JNI_EXCEPTION_(env, NULL);
1070   env->SetObjectArrayElement(result, 2, obj);
1071 
1072   obj = longBox(thread, env, cb->address);
1073   CHECK_JNI_EXCEPTION_(env, NULL);
1074   env->SetObjectArrayElement(result, 3, obj);
1075 
1076   return result;
1077 }
1078 
1079 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1080   ResourceMark rm(THREAD);
1081   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1082   CHECK_JNI_EXCEPTION_(env, NULL);
1083   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1084   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1085   jobjectArray result = NULL;
1086   if (code == NULL) {
1087     return result;
1088   }
1089   int insts_size = code->insts_size();
1090 
1091   ThreadToNativeFromVM ttn(thread);
1092   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1093   CHECK_JNI_EXCEPTION_(env, NULL);
1094   result = env->NewObjectArray(5, clazz, NULL);
1095   if (result == NULL) {
1096     return result;
1097   }
1098 
1099   CodeBlobStub stub(code);
1100   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1101   CHECK_JNI_EXCEPTION_(env, NULL);
1102   env->SetObjectArrayElement(result, 0, codeBlob);
1103 
1104   jobject level = integerBox(thread, env, code->comp_level());
1105   CHECK_JNI_EXCEPTION_(env, NULL);
1106   env->SetObjectArrayElement(result, 1, level);
1107 
1108   jbyteArray insts = env->NewByteArray(insts_size);
1109   CHECK_JNI_EXCEPTION_(env, NULL);
1110   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1111   env->SetObjectArrayElement(result, 2, insts);
1112 
1113   jobject id = integerBox(thread, env, code->compile_id());
1114   CHECK_JNI_EXCEPTION_(env, NULL);
1115   env->SetObjectArrayElement(result, 3, id);
1116 
1117   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1118   CHECK_JNI_EXCEPTION_(env, NULL);
1119   env->SetObjectArrayElement(result, 4, entry_point);
1120 
1121   return result;
1122 WB_END
1123 
1124 CodeBlob* WhiteBox::allocate_code_blob(int size, int blob_type) {
1125   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1126   BufferBlob* blob;
1127   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1128   if (full_size < size) {
1129     full_size += round_to(size - full_size, oopSize);
1130   }
1131   {
1132     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1133     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1134     ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1135   }
1136   // Track memory usage statistic after releasing CodeCache_lock
1137   MemoryService::track_code_cache_memory_usage();
1138   return blob;
1139 }
1140 
1141 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1142   if (size < 0) {
1143     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1144       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1145   }
1146   return (jlong) WhiteBox::allocate_code_blob(size, blob_type);
1147 WB_END
1148 
1149 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1150   if (addr == 0) {
1151     return;
1152   }
1153   BufferBlob::free((BufferBlob*) addr);
1154 WB_END
1155 
1156 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1157   ResourceMark rm;
1158   GrowableArray<CodeBlobStub*> blobs;
1159   {
1160     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1161     CodeHeap* heap = WhiteBox::get_code_heap(blob_type);
1162     if (heap == NULL) {
1163       return NULL;
1164     }
1165     for (CodeBlob* cb = (CodeBlob*) heap->first();
1166          cb != NULL; cb = (CodeBlob*) heap->next(cb)) {
1167       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1168       new (stub) CodeBlobStub(cb);
1169       blobs.append(stub);
1170     }
1171   }
1172   if (blobs.length() == 0) {
1173     return NULL;
1174   }
1175   ThreadToNativeFromVM ttn(thread);
1176   jobjectArray result = NULL;
1177   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1178   CHECK_JNI_EXCEPTION_(env, NULL);
1179   result = env->NewObjectArray(blobs.length(), clazz, NULL);
1180   if (result == NULL) {
1181     return result;
1182   }
1183   int i = 0;
1184   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1185        it != blobs.end(); ++it) {
1186     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1187     CHECK_JNI_EXCEPTION_(env, NULL);
1188     env->SetObjectArrayElement(result, i, obj);
1189     ++i;
1190   }
1191   return result;
1192 WB_END
1193 
1194 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1195   return CompileBroker::get_compilation_activity_mode();
1196 WB_END
1197 
1198 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1199   if (addr == 0) {
1200     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1201       "WB_GetCodeBlob: addr is null");
1202   }
1203   ThreadToNativeFromVM ttn(thread);
1204   CodeBlobStub stub((CodeBlob*) addr);
1205   return codeBlob2objectArray(thread, env, &stub);
1206 WB_END
1207 
1208 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1209   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1210   CHECK_JNI_EXCEPTION_(env, 0);
1211   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1212   return (jlong) mh->method_data();
1213 WB_END
1214 
1215 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1216   return (jlong) Thread::current()->stack_size();
1217 WB_END
1218 
1219 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1220   JavaThread* t = JavaThread::current();
1221   return (jlong) t->stack_available(os::current_stack_pointer()) - (jlong)JavaThread::stack_shadow_zone_size();
1222 WB_END
1223 
1224 
1225 int WhiteBox::array_bytes_to_length(size_t bytes) {
1226   return Array<u1>::bytes_to_length(bytes);
1227 }
1228 
1229 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1230   if (size < 0) {
1231     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1232         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1233   }
1234 
1235   oop class_loader_oop = JNIHandles::resolve(class_loader);
1236   ClassLoaderData* cld = class_loader_oop != NULL
1237       ? java_lang_ClassLoader::loader_data(class_loader_oop)
1238       : ClassLoaderData::the_null_class_loader_data();
1239 
1240   void* metadata = MetadataFactory::new_writeable_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1241 
1242   return (jlong)(uintptr_t)metadata;
1243 WB_END
1244 
1245 WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
1246   oop class_loader_oop = JNIHandles::resolve(class_loader);
1247   ClassLoaderData* cld = class_loader_oop != NULL
1248       ? java_lang_ClassLoader::loader_data(class_loader_oop)
1249       : ClassLoaderData::the_null_class_loader_data();
1250 
1251   MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
1252 WB_END
1253 
1254 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1255   if (inc < 0) {
1256     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1257         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1258   }
1259 
1260   jlong max_size_t = (jlong) ((size_t) -1);
1261   if (inc > max_size_t) {
1262     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1263         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1264   }
1265 
1266   size_t new_cap_until_GC = 0;
1267   size_t aligned_inc = align_size_down((size_t) inc, Metaspace::commit_alignment());
1268   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1269   if (!success) {
1270     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1271                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1272                 "due to contention with another thread");
1273   }
1274   return (jlong) new_cap_until_GC;
1275 WB_END
1276 
1277 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1278   return (jlong) MetaspaceGC::capacity_until_GC();
1279 WB_END
1280 
1281 
1282 
1283 WB_ENTRY(void, WB_AssertMatchingSafepointCalls(JNIEnv* env, jobject o, jboolean mutexSafepointValue, jboolean attemptedNoSafepointValue))
1284   Monitor::SafepointCheckRequired sfpt_check_required = mutexSafepointValue ?
1285                                            Monitor::_safepoint_check_always :
1286                                            Monitor::_safepoint_check_never;
1287   MutexLockerEx ml(new Mutex(Mutex::leaf, "SFPT_Test_lock", true, sfpt_check_required),
1288                    attemptedNoSafepointValue == JNI_TRUE);
1289 WB_END
1290 
1291 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
1292   return (jboolean)MetaspaceShared::is_in_shared_space(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1293 WB_END
1294 
1295 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1296   oop obj_oop = JNIHandles::resolve(obj);
1297   return (jboolean) obj_oop->mark()->has_monitor();
1298 WB_END
1299 
1300 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1301   VM_ForceSafepoint force_safepoint_op;
1302   VMThread::execute(&force_safepoint_op);
1303 WB_END
1304 
1305 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1306   instanceKlassHandle ikh(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1307   return (jlong) ikh->constants();
1308 WB_END
1309 
1310 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1311   return ConstantPool::CPCACHE_INDEX_TAG;
1312 WB_END
1313 
1314 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1315   instanceKlassHandle ikh(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1316   ConstantPool* cp = ikh->constants();
1317   if (cp->cache() == NULL) {
1318       return -1;
1319   }
1320   return cp->cache()->length();
1321 WB_END
1322 
1323 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1324   instanceKlassHandle ikh(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1325   ConstantPool* cp = ikh->constants();
1326   if (cp->cache() == NULL) {
1327     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1328   }
1329   jint cpci = index;
1330   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1331   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1332     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1333   }
1334   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1335   return cpi;
1336 WB_END
1337 
1338 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1339   return ConstantPool::encode_invokedynamic_index(index);
1340 WB_END
1341 
1342 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb))
1343   VM_ClearICs clear_ics;
1344   VMThread::execute(&clear_ics);
1345 WB_END
1346 
1347 template <typename T>
1348 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1349   assert(value != NULL, "sanity");
1350   if (method == NULL || name == NULL) {
1351     return false;
1352   }
1353   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1354   CHECK_JNI_EXCEPTION_(env, false);
1355   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1356   // can't be in VM when we call JNI
1357   ThreadToNativeFromVM ttnfv(thread);
1358   const char* flag_name = env->GetStringUTFChars(name, NULL);
1359   bool result =  CompilerOracle::has_option_value(mh, flag_name, *value);
1360   env->ReleaseStringUTFChars(name, flag_name);
1361   return result;
1362 }
1363 
1364 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1365   bool result;
1366   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1367     // can't be in VM when we call JNI
1368     ThreadToNativeFromVM ttnfv(thread);
1369     return booleanBox(thread, env, result);
1370   }
1371   return NULL;
1372 WB_END
1373 
1374 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1375   intx result;
1376   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1377     // can't be in VM when we call JNI
1378     ThreadToNativeFromVM ttnfv(thread);
1379     return longBox(thread, env, result);
1380   }
1381   return NULL;
1382 WB_END
1383 
1384 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1385   uintx result;
1386   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
1387     // can't be in VM when we call JNI
1388     ThreadToNativeFromVM ttnfv(thread);
1389     return longBox(thread, env, result);
1390   }
1391   return NULL;
1392 WB_END
1393 
1394 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1395   double result;
1396   if (GetMethodOption <double> (thread, env, method, name, &result)) {
1397     // can't be in VM when we call JNI
1398     ThreadToNativeFromVM ttnfv(thread);
1399     return doubleBox(thread, env, result);
1400   }
1401   return NULL;
1402 WB_END
1403 
1404 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1405   ccstr ccstrResult;
1406   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
1407     // can't be in VM when we call JNI
1408     ThreadToNativeFromVM ttnfv(thread);
1409     jstring result = env->NewStringUTF(ccstrResult);
1410     CHECK_JNI_EXCEPTION_(env, NULL);
1411     return result;
1412   }
1413   return NULL;
1414 WB_END
1415 
1416 WB_ENTRY(jboolean, WB_IsShared(JNIEnv* env, jobject wb, jobject obj))
1417   oop obj_oop = JNIHandles::resolve(obj);
1418   return MetaspaceShared::is_in_shared_space((void*)obj_oop);
1419 WB_END
1420 
1421 WB_ENTRY(jboolean, WB_AreSharedStringsIgnored(JNIEnv* env))
1422   return StringTable::shared_string_ignored();
1423 WB_END
1424 
1425 //Some convenience methods to deal with objects from java
1426 int WhiteBox::offset_for_field(const char* field_name, oop object,
1427     Symbol* signature_symbol) {
1428   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
1429   Thread* THREAD = Thread::current();
1430 
1431   //Get the class of our object
1432   Klass* arg_klass = object->klass();
1433   //Turn it into an instance-klass
1434   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
1435 
1436   //Create symbols to look for in the class
1437   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
1438       THREAD);
1439 
1440   //To be filled in with an offset of the field we're looking for
1441   fieldDescriptor fd;
1442 
1443   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
1444   if (res == NULL) {
1445     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
1446         name_symbol->as_C_string());
1447     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:classload=info to see the origin of the problem class");
1448   }
1449 
1450   //fetch the field at the offset we've found
1451   int dest_offset = fd.offset();
1452 
1453   return dest_offset;
1454 }
1455 
1456 
1457 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
1458   int offset = offset_for_field(field_name, object,
1459       vmSymbols::string_signature());
1460   oop string = object->obj_field(offset);
1461   if (string == NULL) {
1462     return NULL;
1463   }
1464   const char* ret = java_lang_String::as_utf8_string(string);
1465   return ret;
1466 }
1467 
1468 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
1469   int offset =
1470       offset_for_field(field_name, object, vmSymbols::bool_signature());
1471   bool ret = (object->bool_field(offset) == JNI_TRUE);
1472   return ret;
1473 }
1474 
1475 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
1476   ResourceMark rm;
1477   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
1478 
1479   //  one by one registration natives for exception catching
1480   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
1481   CHECK_JNI_EXCEPTION(env);
1482   for (int i = 0, n = method_count; i < n; ++i) {
1483     // Skip dummy entries
1484     if (method_array[i].fnPtr == NULL) continue;
1485     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
1486       jthrowable throwable_obj = env->ExceptionOccurred();
1487       if (throwable_obj != NULL) {
1488         env->ExceptionClear();
1489         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
1490           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
1491           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
1492           tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s",
1493               method_array[i].name, method_array[i].signature);
1494         }
1495       } else {
1496         // Registration failed unexpectedly.
1497         tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered",
1498             method_array[i].name, method_array[i].signature);
1499         env->UnregisterNatives(wbclass);
1500         break;
1501       }
1502     }
1503   }
1504 }
1505 
1506 #define CC (char*)
1507 
1508 static JNINativeMethod methods[] = {
1509   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
1510   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
1511   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
1512   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
1513   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
1514   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
1515   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
1516   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
1517   {CC"isClassAlive0",                    CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
1518   {CC"parseCommandLine0",
1519       CC"(Ljava/lang/String;C[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
1520       (void*) &WB_ParseCommandLine
1521   },
1522   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
1523                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
1524   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
1525                                                       (void*)&WB_AddToSystemClassLoaderSearch},
1526   {CC"getCompressedOopsMaxHeapSize", CC"()J",
1527       (void*)&WB_GetCompressedOopsMaxHeapSize},
1528   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
1529   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
1530   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
1531   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
1532   {CC"isSharedClass", CC"(Ljava/lang/Class;)Z",       (void*)&WB_IsSharedClass },
1533 #if INCLUDE_ALL_GCS
1534   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
1535   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z",(void*)&WB_G1IsHumongous     },
1536   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
1537   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
1538   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
1539   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
1540   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
1541   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
1542   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
1543                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
1544   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
1545   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
1546 #endif // INCLUDE_ALL_GCS
1547 #if INCLUDE_NMT
1548   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
1549   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
1550   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
1551   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
1552   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
1553   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
1554   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
1555   {CC"NMTChangeTrackingLevel", CC"()Z",               (void*)&WB_NMTChangeTrackingLevel},
1556   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
1557 #endif // INCLUDE_NMT
1558   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
1559   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
1560   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
1561                                                       (void*)&WB_DeoptimizeMethod  },
1562   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
1563                                                       (void*)&WB_IsMethodCompiled  },
1564   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
1565                                                       (void*)&WB_IsMethodCompilable},
1566   {CC"isMethodQueuedForCompilation0",
1567       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
1568   {CC"isIntrinsicAvailable0",
1569       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
1570                                                       (void*)&WB_IsIntrinsicAvailable},
1571   {CC"makeMethodNotCompilable0",
1572       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
1573   {CC"testSetDontInlineMethod0",
1574       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
1575   {CC"getMethodCompilationLevel0",
1576       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
1577   {CC"getMethodEntryBci0",
1578       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
1579   {CC"getCompileQueueSize",
1580       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
1581   {CC"testSetForceInlineMethod0",
1582       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
1583   {CC"enqueueMethodForCompilation0",
1584       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
1585   {CC"clearMethodState0",
1586       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
1587   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
1588   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
1589   {CC"matchesMethod",
1590       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
1591                                                       (void*)&WB_MatchesMethod},
1592   {CC"matchesInline",
1593       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
1594                                                       (void*)&WB_MatchesInline},
1595   {CC"shouldPrintAssembly",
1596         CC"(Ljava/lang/reflect/Executable;I)Z",
1597                                                         (void*)&WB_ShouldPrintAssembly},
1598 
1599   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
1600   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
1601   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
1602   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
1603   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
1604   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
1605   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
1606   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
1607   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
1608   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
1609   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
1610                                                       (void*)&WB_SetStringVMFlag},
1611   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
1612                                                       (void*)&WB_GetBooleanVMFlag},
1613   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
1614                                                       (void*)&WB_GetIntVMFlag},
1615   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
1616                                                       (void*)&WB_GetUintVMFlag},
1617   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
1618                                                       (void*)&WB_GetIntxVMFlag},
1619   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
1620                                                       (void*)&WB_GetUintxVMFlag},
1621   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
1622                                                       (void*)&WB_GetUint64VMFlag},
1623   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
1624                                                       (void*)&WB_GetSizeTVMFlag},
1625   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
1626                                                       (void*)&WB_GetDoubleVMFlag},
1627   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
1628                                                       (void*)&WB_GetStringVMFlag},
1629   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
1630   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
1631   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
1632   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
1633   {CC"allocateMetaspace",
1634      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
1635   {CC"freeMetaspace",
1636      CC"(Ljava/lang/ClassLoader;JJ)V",                (void*)&WB_FreeMetaspace },
1637   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
1638   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
1639   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
1640   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
1641                                                       (void*)&WB_GetNMethod         },
1642   {CC"forceNMethodSweep",  CC"()V",                   (void*)&WB_ForceNMethodSweep  },
1643   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
1644   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
1645   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
1646   {CC"getCompilationActivityMode",
1647                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
1648   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
1649                                                       (void*)&WB_GetMethodData      },
1650   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
1651   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
1652   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
1653   {CC"assertMatchingSafepointCalls", CC"(ZZ)V",       (void*)&WB_AssertMatchingSafepointCalls },
1654   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
1655   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
1656   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
1657   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
1658   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
1659   {CC"remapInstructionOperandFromCPCache0",
1660       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
1661   {CC"encodeConstantPoolIndyIndex0",
1662       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
1663   {CC"getMethodBooleanOption",
1664       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
1665                                                       (void*)&WB_GetMethodBooleaneOption},
1666   {CC"getMethodIntxOption",
1667       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
1668                                                       (void*)&WB_GetMethodIntxOption},
1669   {CC"getMethodUintxOption",
1670       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
1671                                                       (void*)&WB_GetMethodUintxOption},
1672   {CC"getMethodDoubleOption",
1673       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
1674                                                       (void*)&WB_GetMethodDoubleOption},
1675   {CC"getMethodStringOption",
1676       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
1677                                                       (void*)&WB_GetMethodStringOption},
1678   {CC"isShared",           CC"(Ljava/lang/Object;)Z", (void*)&WB_IsShared },
1679   {CC"areSharedStringsIgnored",           CC"()Z",    (void*)&WB_AreSharedStringsIgnored },
1680   {CC"clearInlineCaches",  CC"()V",                   (void*)&WB_ClearInlineCaches },
1681 };
1682 
1683 #undef CC
1684 
1685 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
1686   {
1687     if (WhiteBoxAPI) {
1688       // Make sure that wbclass is loaded by the null classloader
1689       instanceKlassHandle ikh = instanceKlassHandle(JNIHandles::resolve(wbclass)->klass());
1690       Handle loader(ikh->class_loader());
1691       if (loader.is_null()) {
1692         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
1693         WhiteBox::register_extended(env, wbclass, thread);
1694         WhiteBox::set_used();
1695       }
1696     }
1697   }
1698 JVM_END