1 /*
   2  * Copyright (c) 2012, 2019, 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/classLoaderDataGraph.hpp"
  30 #include "classfile/modules.hpp"
  31 #include "classfile/protectionDomainCache.hpp"
  32 #include "classfile/stringTable.hpp"
  33 #include "code/codeCache.hpp"
  34 #include "compiler/methodMatcher.hpp"
  35 #include "compiler/directivesParser.hpp"
  36 #include "gc/shared/gcConfig.hpp"
  37 #include "gc/shared/genCollectedHeap.hpp"
  38 #include "jvmtifiles/jvmtiEnv.hpp"
  39 #include "memory/heapShared.inline.hpp"
  40 #include "memory/metaspaceShared.hpp"
  41 #include "memory/metadataFactory.hpp"
  42 #include "memory/iterator.hpp"
  43 #include "memory/resourceArea.hpp"
  44 #include "memory/universe.hpp"
  45 #include "memory/oopFactory.hpp"
  46 #include "oops/array.hpp"
  47 #include "oops/constantPool.inline.hpp"
  48 #include "oops/method.inline.hpp"
  49 #include "oops/objArrayKlass.hpp"
  50 #include "oops/objArrayOop.inline.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "oops/typeArrayOop.inline.hpp"
  53 #include "prims/resolvedMethodTable.hpp"
  54 #include "prims/wbtestmethods/parserTests.hpp"
  55 #include "prims/whitebox.inline.hpp"
  56 #include "runtime/arguments.hpp"
  57 #include "runtime/compilationPolicy.hpp"
  58 #include "runtime/deoptimization.hpp"
  59 #include "runtime/fieldDescriptor.inline.hpp"
  60 #include "runtime/flags/jvmFlag.hpp"
  61 #include "runtime/frame.inline.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/handshake.hpp"
  64 #include "runtime/interfaceSupport.inline.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/jniHandles.inline.hpp"
  67 #include "runtime/os.hpp"
  68 #include "runtime/sweeper.hpp"
  69 #include "runtime/thread.hpp"
  70 #include "runtime/threadSMR.hpp"
  71 #include "runtime/vm_version.hpp"
  72 #include "services/memoryService.hpp"
  73 #include "utilities/align.hpp"
  74 #include "utilities/debug.hpp"
  75 #include "utilities/elfFile.hpp"
  76 #include "utilities/exceptions.hpp"
  77 #include "utilities/macros.hpp"
  78 #if INCLUDE_CDS
  79 #include "prims/cdsoffsets.hpp"
  80 #endif // INCLUDE_CDS
  81 #if INCLUDE_G1GC
  82 #include "gc/g1/g1CollectedHeap.inline.hpp"
  83 #include "gc/g1/g1ConcurrentMark.hpp"
  84 #include "gc/g1/g1ConcurrentMarkThread.hpp"
  85 #include "gc/g1/heapRegionRemSet.hpp"
  86 #include "gc/g1/heterogeneousHeapRegionManager.hpp"
  87 #endif // INCLUDE_G1GC
  88 #if INCLUDE_PARALLELGC
  89 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  90 #include "gc/parallel/adjoiningGenerations.hpp"
  91 #endif // INCLUDE_PARALLELGC
  92 #if INCLUDE_NMT
  93 #include "services/mallocSiteTable.hpp"
  94 #include "services/memTracker.hpp"
  95 #include "utilities/nativeCallStack.hpp"
  96 #endif // INCLUDE_NMT
  97 #if INCLUDE_AOT
  98 #include "aot/aotLoader.hpp"
  99 #endif // INCLUDE_AOT
 100 
 101 #ifdef LINUX
 102 #include "osContainer_linux.hpp"
 103 #endif
 104 
 105 #define SIZE_T_MAX_VALUE ((size_t) -1)
 106 
 107 #define CHECK_JNI_EXCEPTION_(env, value)                               \
 108   do {                                                                 \
 109     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 110     THREAD->clear_pending_jni_exception_check();                       \
 111     if (HAS_PENDING_EXCEPTION) {                                       \
 112       return(value);                                                   \
 113     }                                                                  \
 114   } while (0)
 115 
 116 #define CHECK_JNI_EXCEPTION(env)                                       \
 117   do {                                                                 \
 118     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 119     THREAD->clear_pending_jni_exception_check();                       \
 120     if (HAS_PENDING_EXCEPTION) {                                       \
 121       return;                                                          \
 122     }                                                                  \
 123   } while (0)
 124 
 125 bool WhiteBox::_used = false;
 126 volatile bool WhiteBox::compilation_locked = false;
 127 
 128 class VM_WhiteBoxOperation : public VM_Operation {
 129  public:
 130   VM_WhiteBoxOperation()                         { }
 131   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
 132   bool allow_nested_vm_operations() const        { return true; }
 133 };
 134 
 135 
 136 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
 137   return (jlong)(void*)JNIHandles::resolve(obj);
 138 WB_END
 139 
 140 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
 141   return heapOopSize;
 142 WB_END
 143 
 144 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
 145   return os::vm_page_size();
 146 WB_END
 147 
 148 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
 149   return os::vm_allocation_granularity();
 150 WB_END
 151 
 152 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 153   return os::large_page_size();
 154 WB_END
 155 
 156 class WBIsKlassAliveClosure : public LockedClassesDo {
 157     Symbol* _name;
 158     bool _found;
 159 public:
 160     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
 161 
 162     void do_klass(Klass* k) {
 163       if (_found) return;
 164       Symbol* ksym = k->name();
 165       if (ksym->fast_compare(_name) == 0) {
 166         _found = true;
 167       }
 168     }
 169 
 170     bool found() const {
 171         return _found;
 172     }
 173 };
 174 
 175 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
 176   oop h_name = JNIHandles::resolve(name);
 177   if (h_name == NULL) return false;
 178   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
 179   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 180 
 181   WBIsKlassAliveClosure closure(sym);
 182   ClassLoaderDataGraph::classes_do(&closure);
 183 
 184   return closure.found();
 185 WB_END
 186 
 187 WB_ENTRY(jint, WB_GetSymbolRefcount(JNIEnv* env, jobject unused, jstring name))
 188   oop h_name = JNIHandles::resolve(name);
 189   if (h_name == NULL) return false;
 190   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_0);
 191   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 192   return (jint)sym->refcount();
 193 WB_END
 194 
 195 
 196 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 197 #if INCLUDE_JVMTI
 198   ResourceMark rm;
 199   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 200   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 201   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 202   assert(err == JVMTI_ERROR_NONE, "must not fail");
 203 #endif
 204 }
 205 WB_END
 206 
 207 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 208 #if INCLUDE_JVMTI
 209   ResourceMark rm;
 210   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 211   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 212   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 213   assert(err == JVMTI_ERROR_NONE, "must not fail");
 214 #endif
 215 }
 216 WB_END
 217 
 218 
 219 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 220   return (jlong)Arguments::max_heap_for_compressed_oops();
 221 }
 222 WB_END
 223 
 224 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 225   CollectorPolicy * p = Universe::heap()->collector_policy();
 226   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap "
 227     SIZE_FORMAT " Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 228     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
 229     p->space_alignment(), p->heap_alignment());
 230 }
 231 WB_END
 232 
 233 #ifndef PRODUCT
 234 // Forward declaration
 235 void TestReservedSpace_test();
 236 void TestReserveMemorySpecial_test();
 237 void TestVirtualSpace_test();
 238 void TestMetaspaceUtils_test();
 239 #endif
 240 
 241 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 242 #ifndef PRODUCT
 243   TestReservedSpace_test();
 244   TestReserveMemorySpecial_test();
 245   TestVirtualSpace_test();
 246   TestMetaspaceUtils_test();
 247 #endif
 248 WB_END
 249 
 250 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 251   size_t granularity = os::vm_allocation_granularity();
 252   ReservedHeapSpace rhs(100 * granularity, granularity, false);
 253   VirtualSpace vs;
 254   vs.initialize(rhs, 50 * granularity);
 255 
 256   // Check if constraints are complied
 257   if (!( UseCompressedOops && rhs.base() != NULL &&
 258          Universe::narrow_oop_base() != NULL &&
 259          Universe::narrow_oop_use_implicit_null_checks() )) {
 260     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 261                   "\tUseCompressedOops is %d\n"
 262                   "\trhs.base() is " PTR_FORMAT "\n"
 263                   "\tUniverse::narrow_oop_base() is " PTR_FORMAT "\n"
 264                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
 265                   UseCompressedOops,
 266                   p2i(rhs.base()),
 267                   p2i(Universe::narrow_oop_base()),
 268                   Universe::narrow_oop_use_implicit_null_checks());
 269     return;
 270   }
 271   tty->print_cr("Reading from no access area... ");
 272   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 273                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 274 WB_END
 275 
 276 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 277                                            size_t magnitude, size_t iterations) {
 278   size_t granularity = os::vm_allocation_granularity();
 279   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false);
 280   VirtualSpace vs;
 281   if (!vs.initialize(rhs, 0)) {
 282     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 283     return 3;
 284   }
 285 
 286   int seed = os::random();
 287   tty->print_cr("Random seed is %d", seed);
 288   os::init_random(seed);
 289 
 290   for (size_t i = 0; i < iterations; i++) {
 291 
 292     // Whether we will shrink or grow
 293     bool shrink = os::random() % 2L == 0;
 294 
 295     // Get random delta to resize virtual space
 296     size_t delta = (size_t)os::random() % magnitude;
 297 
 298     // If we are about to shrink virtual space below zero, then expand instead
 299     if (shrink && vs.committed_size() < delta) {
 300       shrink = false;
 301     }
 302 
 303     // Resizing by delta
 304     if (shrink) {
 305       vs.shrink_by(delta);
 306     } else {
 307       // If expanding fails expand_by will silently return false
 308       vs.expand_by(delta, true);
 309     }
 310   }
 311   return 0;
 312 }
 313 
 314 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 315         jlong reserved_space_size, jlong magnitude, jlong iterations))
 316   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 317                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 318                 iterations);
 319   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 320     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 321     return 1;
 322   }
 323 
 324   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 325   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 326   if (sizeof(size_t) < sizeof(jlong)) {
 327     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 328     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 329         || iterations > size_t_max_value) {
 330       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 331       return 2;
 332     }
 333   }
 334 
 335   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 336                                         (size_t) magnitude, (size_t) iterations);
 337 WB_END
 338 
 339 WB_ENTRY(jboolean, WB_IsGCSupported(JNIEnv* env, jobject o, jint name))
 340   return GCConfig::is_gc_supported((CollectedHeap::Name)name);
 341 WB_END
 342 
 343 WB_ENTRY(jboolean, WB_IsGCSelected(JNIEnv* env, jobject o, jint name))
 344   return GCConfig::is_gc_selected((CollectedHeap::Name)name);
 345 WB_END
 346 
 347 WB_ENTRY(jboolean, WB_IsGCSelectedErgonomically(JNIEnv* env, jobject o))
 348   return GCConfig::is_gc_selected_ergonomically();
 349 WB_END
 350 
 351 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 352   oop p = JNIHandles::resolve(obj);
 353 #if INCLUDE_G1GC
 354   if (UseG1GC) {
 355     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 356     const HeapRegion* hr = g1h->heap_region_containing(p);
 357     if (hr == NULL) {
 358       return false;
 359     }
 360     return !(hr->is_young());
 361   }
 362 #endif
 363 #if INCLUDE_PARALLELGC
 364   if (UseParallelGC) {
 365     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 366     return !psh->is_in_young(p);
 367   }
 368 #endif
 369 #if INCLUDE_ZGC
 370   if (UseZGC) {
 371     return Universe::heap()->is_in(p);
 372   }
 373 #endif
 374   GenCollectedHeap* gch = GenCollectedHeap::heap();
 375   return !gch->is_in_young(p);
 376 WB_END
 377 
 378 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 379   oop p = JNIHandles::resolve(obj);
 380   return Universe::heap()->obj_size(p) * HeapWordSize;
 381 WB_END
 382 
 383 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 384   size_t alignment = Universe::heap()->collector_policy()->space_alignment();
 385   return (jlong)alignment;
 386 WB_END
 387 
 388 WB_ENTRY(jlong, WB_GetHeapAlignment(JNIEnv* env, jobject o))
 389   size_t alignment = Universe::heap()->collector_policy()->heap_alignment();
 390   return (jlong)alignment;
 391 WB_END
 392 
 393 WB_ENTRY(jboolean, WB_SupportsConcurrentGCPhaseControl(JNIEnv* env, jobject o))
 394   return Universe::heap()->supports_concurrent_phase_control();
 395 WB_END
 396 
 397 WB_ENTRY(jboolean, WB_RequestConcurrentGCPhase(JNIEnv* env, jobject o, jstring name))
 398   Handle h_name(THREAD, JNIHandles::resolve(name));
 399   ResourceMark rm;
 400   const char* c_name = java_lang_String::as_utf8_string(h_name());
 401   return Universe::heap()->request_concurrent_phase(c_name);
 402 WB_END
 403 
 404 #if INCLUDE_G1GC
 405 
 406 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 407   if (UseG1GC) {
 408     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 409     oop result = JNIHandles::resolve(obj);
 410     const HeapRegion* hr = g1h->heap_region_containing(result);
 411     return hr->is_humongous();
 412   }
 413   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1IsHumongous: G1 GC is not enabled");
 414 WB_END
 415 
 416 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 417   if (UseG1GC) {
 418     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 419     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 420     return hr->is_humongous();
 421   }
 422   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToHumongousRegion: G1 GC is not enabled");
 423 WB_END
 424 
 425 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 426   if (UseG1GC) {
 427     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 428     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 429     return hr->is_free();
 430   }
 431   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToFreeRegion: G1 GC is not enabled");
 432 WB_END
 433 
 434 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 435   if (UseG1GC) {
 436     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 437     size_t nr = g1h->max_regions();
 438     return (jlong)nr;
 439   }
 440   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumMaxRegions: G1 GC is not enabled");
 441 WB_END
 442 
 443 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 444   if (UseG1GC) {
 445     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 446     size_t nr = g1h->num_free_regions();
 447     return (jlong)nr;
 448   }
 449   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumFreeRegions: G1 GC is not enabled");
 450 WB_END
 451 
 452 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 453   if (UseG1GC) {
 454     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 455     return g1h->concurrent_mark()->cm_thread()->during_cycle();
 456   }
 457   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1InConcurrentMark: G1 GC is not enabled");
 458 WB_END
 459 
 460 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 461   if (UseG1GC) {
 462     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 463     if (!g1h->concurrent_mark()->cm_thread()->during_cycle()) {
 464       g1h->collect(GCCause::_wb_conc_mark);
 465       return true;
 466     }
 467     return false;
 468   }
 469   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1StartMarkCycle: G1 GC is not enabled");
 470 WB_END
 471 
 472 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 473   if (UseG1GC) {
 474     return (jint)HeapRegion::GrainBytes;
 475   }
 476   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1RegionSize: G1 GC is not enabled");
 477 WB_END
 478 
 479 #endif // INCLUDE_G1GC
 480 
 481 #if INCLUDE_G1GC || INCLUDE_PARALLELGC
 482 WB_ENTRY(jlong, WB_DramReservedStart(JNIEnv* env, jobject o))
 483 #if INCLUDE_G1GC
 484   if (UseG1GC) {
 485     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 486     if (g1h->is_heterogeneous_heap()) {
 487       uint start_region = HeterogeneousHeapRegionManager::manager()->start_index_of_dram();
 488       return (jlong)(g1h->base() + start_region * HeapRegion::GrainBytes);
 489     } else {
 490       return (jlong)g1h->base();
 491     }
 492   }
 493 #endif // INCLUDE_G1GC
 494 #if INCLUDE_PARALLELGC
 495   if (UseParallelGC) {
 496     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 497     if (AllocateOldGenAt != NULL) {
 498       MemRegion reserved = ps_heap->young_gen()->reserved();
 499       return (jlong)reserved.start();
 500     } else {
 501       return (jlong)ps_heap->base();
 502     }
 503   }
 504 #endif // INCLUDE_PARALLELGC
 505   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_DramReservedStart: enabled only for G1 and Parallel GC");
 506 WB_END
 507 
 508 WB_ENTRY(jlong, WB_DramReservedEnd(JNIEnv* env, jobject o))
 509 #if INCLUDE_G1GC
 510   if (UseG1GC) {
 511     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 512     if (g1h->is_heterogeneous_heap()) {
 513       uint end_region = HeterogeneousHeapRegionManager::manager()->end_index_of_dram();
 514       return (jlong)(g1h->base() + (end_region + 1) * HeapRegion::GrainBytes - 1);
 515     } else {
 516       return (jlong)g1h->base() + g1h->collector_policy()->max_heap_byte_size();
 517     }
 518   }
 519 #endif // INCLUDE_G1GC
 520 #if INCLUDE_PARALLELGC
 521   if (UseParallelGC) {
 522     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 523     if (AllocateOldGenAt != NULL) {
 524       MemRegion reserved = ps_heap->young_gen()->reserved();
 525       return (jlong)reserved.end();
 526     } else {
 527       return (jlong)ps_heap->reserved_region().end();
 528     }
 529   }
 530 #endif // INCLUDE_PARALLELGC
 531   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_DramReservedEnd: enabled only for G1 and Parallel GC");
 532 WB_END
 533 
 534 WB_ENTRY(jlong, WB_NvdimmReservedStart(JNIEnv* env, jobject o))
 535 #if INCLUDE_G1GC
 536   if (UseG1GC) {
 537     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 538     if (g1h->is_heterogeneous_heap()) {
 539       uint start_region = HeterogeneousHeapRegionManager::manager()->start_index_of_nvdimm();
 540       return (jlong)(g1h->base() + start_region * HeapRegion::GrainBytes);
 541     } else {
 542       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 543     }
 544   }
 545 #endif // INCLUDE_G1GC
 546 #if INCLUDE_PARALLELGC
 547   if (UseParallelGC) {
 548     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 549     if (AllocateOldGenAt != NULL) {
 550       MemRegion reserved = ps_heap->old_gen()->reserved();
 551       return (jlong)reserved.start();
 552     } else {
 553       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 554     }
 555   }
 556 #endif // INCLUDE_PARALLELGC
 557   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: enabled only for G1 and Parallel GC");
 558 WB_END
 559 
 560 WB_ENTRY(jlong, WB_NvdimmReservedEnd(JNIEnv* env, jobject o))
 561 #if INCLUDE_G1GC
 562   if (UseG1GC) {
 563     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 564     if (g1h->is_heterogeneous_heap()) {
 565       uint end_region = HeterogeneousHeapRegionManager::manager()->start_index_of_nvdimm();
 566       return (jlong)(g1h->base() + (end_region + 1) * HeapRegion::GrainBytes - 1);
 567     } else {
 568       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 569     }
 570   }
 571 #endif // INCLUDE_G1GC
 572 #if INCLUDE_PARALLELGC
 573   if (UseParallelGC) {
 574     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 575     if (AllocateOldGenAt != NULL) {
 576       MemRegion reserved = ps_heap->old_gen()->reserved();
 577       return (jlong)reserved.end();
 578       } else {
 579       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 580     }
 581   }
 582 #endif // INCLUDE_PARALLELGC
 583   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: enabled only for G1 and Parallel GC");
 584 WB_END
 585 
 586 #endif // INCLUDE_G1GC || INCLUDE_PARALLELGC
 587 
 588 #if INCLUDE_PARALLELGC
 589 
 590 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 591   if (UseParallelGC) {
 592     return ParallelScavengeHeap::heap()->gens()->virtual_spaces()->alignment();
 593   }
 594   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSVirtualSpaceAlignment: Parallel GC is not enabled");
 595 WB_END
 596 
 597 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 598   if (UseParallelGC) {
 599     return ParallelScavengeHeap::heap()->generation_alignment();
 600   }
 601   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSHeapGenerationAlignment: Parallel GC is not enabled");
 602 WB_END
 603 
 604 #endif // INCLUDE_PARALLELGC
 605 
 606 #if INCLUDE_G1GC
 607 
 608 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 609   if (UseG1GC) {
 610     ResourceMark rm(THREAD);
 611     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 612     MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 613     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 614     return JNIHandles::make_local(env, h());
 615   }
 616   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1AuxiliaryMemoryUsage: G1 GC is not enabled");
 617 WB_END
 618 
 619 class OldRegionsLivenessClosure: public HeapRegionClosure {
 620 
 621  private:
 622   const int _liveness;
 623   size_t _total_count;
 624   size_t _total_memory;
 625   size_t _total_memory_to_free;
 626 
 627  public:
 628   OldRegionsLivenessClosure(int liveness) :
 629     _liveness(liveness),
 630     _total_count(0),
 631     _total_memory(0),
 632     _total_memory_to_free(0) { }
 633 
 634     size_t total_count() { return _total_count; }
 635     size_t total_memory() { return _total_memory; }
 636     size_t total_memory_to_free() { return _total_memory_to_free; }
 637 
 638   bool do_heap_region(HeapRegion* r) {
 639     if (r->is_old()) {
 640       size_t prev_live = r->marked_bytes();
 641       size_t live = r->live_bytes();
 642       size_t size = r->used();
 643       size_t reg_size = HeapRegion::GrainBytes;
 644       if (size > 0 && ((int)(live * 100 / size) < _liveness)) {
 645         _total_memory += size;
 646         ++_total_count;
 647         if (size == reg_size) {
 648         // we don't include non-full regions since they are unlikely included in mixed gc
 649         // for testing purposes it's enough to have lowest estimation of total memory that is expected to be freed
 650           _total_memory_to_free += size - prev_live;
 651         }
 652       }
 653     }
 654     return false;
 655   }
 656 };
 657 
 658 
 659 WB_ENTRY(jlongArray, WB_G1GetMixedGCInfo(JNIEnv* env, jobject o, jint liveness))
 660   if (!UseG1GC) {
 661     THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1GetMixedGCInfo: G1 GC is not enabled");
 662   }
 663   if (liveness < 0) {
 664     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "liveness value should be non-negative");
 665   }
 666 
 667   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 668   OldRegionsLivenessClosure rli(liveness);
 669   g1h->heap_region_iterate(&rli);
 670 
 671   typeArrayOop result = oopFactory::new_longArray(3, CHECK_NULL);
 672   result->long_at_put(0, rli.total_count());
 673   result->long_at_put(1, rli.total_memory());
 674   result->long_at_put(2, rli.total_memory_to_free());
 675   return (jlongArray) JNIHandles::make_local(env, result);
 676 WB_END
 677 
 678 #endif // INCLUDE_G1GC
 679 
 680 #if INCLUDE_NMT
 681 // Alloc memory using the test memory type so that we can use that to see if
 682 // NMT picks it up correctly
 683 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 684   jlong addr = 0;
 685   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 686   return addr;
 687 WB_END
 688 
 689 // Alloc memory with pseudo call stack. The test can create psudo malloc
 690 // allocation site to stress the malloc tracking.
 691 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 692   address pc = (address)(size_t)pseudo_stack;
 693   NativeCallStack stack(&pc, 1);
 694   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 695 WB_END
 696 
 697 // Alloc memory with pseudo call stack and specific memory type.
 698 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStackAndType(JNIEnv* env, jobject o, jlong size, jint pseudo_stack, jint type))
 699   address pc = (address)(size_t)pseudo_stack;
 700   NativeCallStack stack(&pc, 1);
 701   return (jlong)(uintptr_t)os::malloc(size, (MEMFLAGS)type, stack);
 702 WB_END
 703 
 704 // Free the memory allocated by NMTAllocTest
 705 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 706   os::free((void*)(uintptr_t)mem);
 707 WB_END
 708 
 709 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 710   jlong addr = 0;
 711 
 712   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 713   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 714 
 715   return addr;
 716 WB_END
 717 
 718 WB_ENTRY(jlong, WB_NMTAttemptReserveMemoryAt(JNIEnv* env, jobject o, jlong addr, jlong size))
 719   addr = (jlong)(uintptr_t)os::attempt_reserve_memory_at((size_t)size, (char*)(uintptr_t)addr);
 720   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 721 
 722   return addr;
 723 WB_END
 724 
 725 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 726   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 727   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 728 WB_END
 729 
 730 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 731   os::uncommit_memory((char *)(uintptr_t)addr, size);
 732 WB_END
 733 
 734 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 735   os::release_memory((char *)(uintptr_t)addr, size);
 736 WB_END
 737 
 738 WB_ENTRY(jboolean, WB_NMTChangeTrackingLevel(JNIEnv* env))
 739   // Test that we can downgrade NMT levels but not upgrade them.
 740   if (MemTracker::tracking_level() == NMT_off) {
 741     MemTracker::transition_to(NMT_off);
 742     return MemTracker::tracking_level() == NMT_off;
 743   } else {
 744     assert(MemTracker::tracking_level() == NMT_detail, "Should start out as detail tracking");
 745     MemTracker::transition_to(NMT_summary);
 746     assert(MemTracker::tracking_level() == NMT_summary, "Should be summary now");
 747 
 748     // Can't go to detail once NMT is set to summary.
 749     MemTracker::transition_to(NMT_detail);
 750     assert(MemTracker::tracking_level() == NMT_summary, "Should still be summary now");
 751 
 752     // Shutdown sets tracking level to minimal.
 753     MemTracker::shutdown();
 754     assert(MemTracker::tracking_level() == NMT_minimal, "Should be minimal now");
 755 
 756     // Once the tracking level is minimal, we cannot increase to summary.
 757     // The code ignores this request instead of asserting because if the malloc site
 758     // table overflows in another thread, it tries to change the code to summary.
 759     MemTracker::transition_to(NMT_summary);
 760     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 761 
 762     // Really can never go up to detail, verify that the code would never do this.
 763     MemTracker::transition_to(NMT_detail);
 764     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 765     return MemTracker::tracking_level() == NMT_minimal;
 766   }
 767 WB_END
 768 
 769 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 770   int hash_size = MallocSiteTable::hash_buckets();
 771   assert(hash_size > 0, "NMT hash_size should be > 0");
 772   return (jint)hash_size;
 773 WB_END
 774 #endif // INCLUDE_NMT
 775 
 776 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 777   assert(method != NULL, "method should not be null");
 778   ThreadToNativeFromVM ttn(thread);
 779   return env->FromReflectedMethod(method);
 780 }
 781 
 782 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 783 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 784  private:
 785   int _result;
 786   const bool _make_not_entrant;
 787  public:
 788   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 789         _result(0), _make_not_entrant(make_not_entrant) { }
 790   int  result() const { return _result; }
 791 
 792   void doit() {
 793     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 794       if (t->has_last_Java_frame()) {
 795         for (StackFrameStream fst(t, UseBiasedLocking); !fst.is_done(); fst.next()) {
 796           frame* f = fst.current();
 797           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 798             RegisterMap* reg_map = fst.register_map();
 799             Deoptimization::deoptimize(t, *f, reg_map);
 800             if (_make_not_entrant) {
 801                 CompiledMethod* cm = CodeCache::find_compiled(f->pc());
 802                 assert(cm != NULL, "sanity check");
 803                 cm->make_not_entrant();
 804             }
 805             ++_result;
 806           }
 807         }
 808       }
 809     }
 810   }
 811 };
 812 
 813 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 814   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 815   VMThread::execute(&op);
 816   return op.result();
 817 WB_END
 818 
 819 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 820   MutexLockerEx mu(Compile_lock);
 821   CodeCache::mark_all_nmethods_for_deoptimization();
 822   VM_Deoptimize op;
 823   VMThread::execute(&op);
 824 WB_END
 825 
 826 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 827   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 828   int result = 0;
 829   CHECK_JNI_EXCEPTION_(env, result);
 830   MutexLockerEx mu(Compile_lock);
 831   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 832   if (is_osr) {
 833     result += mh->mark_osr_nmethods();
 834   } else if (mh->code() != NULL) {
 835     mh->code()->mark_for_deoptimization();
 836     ++result;
 837   }
 838   result += CodeCache::mark_for_deoptimization(mh());
 839   if (result > 0) {
 840     VM_Deoptimize op;
 841     VMThread::execute(&op);
 842   }
 843   return result;
 844 WB_END
 845 
 846 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 847   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 848   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 849   MutexLockerEx mu(Compile_lock);
 850   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 851   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 852   if (code == NULL) {
 853     return JNI_FALSE;
 854   }
 855   return (code->is_alive() && !code->is_marked_for_deoptimization());
 856 WB_END
 857 
 858 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 859   if (method == NULL || comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 860     return false;
 861   }
 862   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 863   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 864   MutexLockerEx mu(Compile_lock);
 865   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 866   if (is_osr) {
 867     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 868   } else {
 869     return CompilationPolicy::can_be_compiled(mh, comp_level);
 870   }
 871 WB_END
 872 
 873 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 874   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 875   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 876   MutexLockerEx mu(Compile_lock);
 877   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 878   return mh->queued_for_compilation();
 879 WB_END
 880 
 881 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 882   if (compLevel < CompLevel_none || compLevel > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 883     return false; // Intrinsic is not available on a non-existent compilation level.
 884   }
 885   jmethodID method_id, compilation_context_id;
 886   method_id = reflected_method_to_jmid(thread, env, method);
 887   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 888   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 889 
 890   DirectiveSet* directive;
 891   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 892   assert(comp != NULL, "compiler not available");
 893   if (compilation_context != NULL) {
 894     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 895     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 896     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 897     directive = DirectivesStack::getMatchingDirective(cch, comp);
 898   } else {
 899     // Calling with NULL matches default directive
 900     directive = DirectivesStack::getDefaultDirective(comp);
 901   }
 902   bool result = comp->is_intrinsic_available(mh, directive);
 903   DirectivesStack::release(directive);
 904   return result;
 905 WB_END
 906 
 907 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 908   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 909   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 910   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 911   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 912   return (code != NULL ? code->comp_level() : CompLevel_none);
 913 WB_END
 914 
 915 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 916   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 917   CHECK_JNI_EXCEPTION(env);
 918   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 919   if (is_osr) {
 920     mh->set_not_osr_compilable(comp_level, true /* report */, "WhiteBox");
 921   } else {
 922     mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
 923   }
 924 WB_END
 925 
 926 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 927   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 928   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 929   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 930   CompiledMethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 931   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 932 WB_END
 933 
 934 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 935   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 936   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 937   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 938   bool result = mh->dont_inline();
 939   mh->set_dont_inline(value == JNI_TRUE);
 940   return result;
 941 WB_END
 942 
 943 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 944   if (comp_level == CompLevel_any) {
 945     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 946         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 947   } else {
 948     return CompileBroker::queue_size(comp_level);
 949   }
 950 WB_END
 951 
 952 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 953   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 954   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 955   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 956   bool result = mh->force_inline();
 957   mh->set_force_inline(value == JNI_TRUE);
 958   return result;
 959 WB_END
 960 
 961 bool WhiteBox::compile_method(Method* method, int comp_level, int bci, Thread* THREAD) {
 962   // Screen for unavailable/bad comp level or null method
 963   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
 964   if (method == NULL) {
 965     tty->print_cr("WB error: request to compile NULL method");
 966     return false;
 967   }
 968   if (comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 969     tty->print_cr("WB error: invalid compilation level %d", comp_level);
 970     return false;
 971   }
 972   if (comp == NULL) {
 973     tty->print_cr("WB error: no compiler for requested compilation level %d", comp_level);
 974     return false;
 975   }
 976 
 977   // Check if compilation is blocking
 978   methodHandle mh(THREAD, method);
 979   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
 980   bool is_blocking = !directive->BackgroundCompilationOption;
 981   DirectivesStack::release(directive);
 982 
 983   // Compile method and check result
 984   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), CompileTask::Reason_Whitebox, THREAD);
 985   MutexLockerEx mu(Compile_lock);
 986   bool is_queued = mh->queued_for_compilation();
 987   if ((!is_blocking && is_queued) || nm != NULL) {
 988     return true;
 989   }
 990   tty->print("WB error: failed to %s compile at level %d method ", is_blocking ? "blocking" : "", comp_level);
 991   mh->print_short_name(tty);
 992   tty->cr();
 993   if (is_blocking && is_queued) {
 994     tty->print_cr("WB error: blocking compilation is still in queue!");
 995   }
 996   return false;
 997 }
 998 
 999 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
1000   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1001   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1002   return WhiteBox::compile_method(Method::checked_resolve_jmethod_id(jmid), comp_level, bci, THREAD);
1003 WB_END
1004 
1005 WB_ENTRY(jboolean, WB_EnqueueInitializerForCompilation(JNIEnv* env, jobject o, jclass klass, jint comp_level))
1006   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1007   Method* clinit = ik->class_initializer();
1008   if (clinit == NULL) {
1009     return false;
1010   }
1011   return WhiteBox::compile_method(clinit, comp_level, InvocationEntryBci, THREAD);
1012 WB_END
1013 
1014 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
1015   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1016   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1017 
1018   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1019   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
1020   bool result = directive->PrintAssemblyOption;
1021   DirectivesStack::release(directive);
1022 
1023   return result;
1024 WB_END
1025 
1026 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
1027   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1028   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1029 
1030   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1031 
1032   ResourceMark rm;
1033   const char* error_msg = NULL;
1034   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1035   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
1036 
1037   if (m == NULL) {
1038     assert(error_msg != NULL, "Always have an error message");
1039     tty->print_cr("Got error: %s", error_msg);
1040     return -1; // Pattern failed
1041   }
1042 
1043   // Pattern works - now check if it matches
1044   int result;
1045   if (m->match(mh, InlineMatcher::force_inline)) {
1046     result = 2; // Force inline match
1047   } else if (m->match(mh, InlineMatcher::dont_inline)) {
1048     result = 1; // Dont inline match
1049   } else {
1050     result = 0; // No match
1051   }
1052   delete m;
1053   return result;
1054 WB_END
1055 
1056 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
1057   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1058   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1059 
1060   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1061 
1062   ResourceMark rm;
1063   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1064 
1065   const char* error_msg = NULL;
1066 
1067   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg);
1068   if (m == NULL) {
1069     assert(error_msg != NULL, "Must have error_msg");
1070     tty->print_cr("Got error: %s", error_msg);
1071     return -1;
1072   }
1073 
1074   // Pattern works - now check if it matches
1075   int result = m->matches(mh);
1076   delete m;
1077   assert(result == 0 || result == 1, "Result out of range");
1078   return result;
1079 WB_END
1080 
1081 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
1082   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1083   CHECK_JNI_EXCEPTION(env);
1084   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1085   MutexLockerEx mu(Compile_lock);
1086   MethodData* mdo = mh->method_data();
1087   MethodCounters* mcs = mh->method_counters();
1088 
1089   if (mdo != NULL) {
1090     mdo->init();
1091     ResourceMark rm;
1092     int arg_count = mdo->method()->size_of_parameters();
1093     for (int i = 0; i < arg_count; i++) {
1094       mdo->set_arg_modified(i, 0);
1095     }
1096     MutexLockerEx mu(mdo->extra_data_lock());
1097     mdo->clean_method_data(/*always_clean*/true);
1098   }
1099 
1100   mh->clear_not_c1_compilable();
1101   mh->clear_not_c2_compilable();
1102   mh->clear_not_c2_osr_compilable();
1103   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
1104   if (mcs != NULL) {
1105     mcs->backedge_counter()->init();
1106     mcs->invocation_counter()->init();
1107     mcs->set_interpreter_invocation_count(0);
1108     mcs->set_interpreter_throwout_count(0);
1109 
1110 #ifdef TIERED
1111     mcs->set_rate(0.0F);
1112     mh->set_prev_event_count(0);
1113     mh->set_prev_time(0);
1114 #endif
1115   }
1116 WB_END
1117 
1118 template <typename T>
1119 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, JVMFlag::Error (*TAt)(const char*, T*, bool, bool)) {
1120   if (name == NULL) {
1121     return false;
1122   }
1123   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1124   const char* flag_name = env->GetStringUTFChars(name, NULL);
1125   CHECK_JNI_EXCEPTION_(env, false);
1126   JVMFlag::Error result = (*TAt)(flag_name, value, true, true);
1127   env->ReleaseStringUTFChars(name, flag_name);
1128   return (result == JVMFlag::SUCCESS);
1129 }
1130 
1131 template <typename T>
1132 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, JVMFlag::Error (*TAtPut)(const char*, T*, JVMFlag::Flags)) {
1133   if (name == NULL) {
1134     return false;
1135   }
1136   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1137   const char* flag_name = env->GetStringUTFChars(name, NULL);
1138   CHECK_JNI_EXCEPTION_(env, false);
1139   JVMFlag::Error result = (*TAtPut)(flag_name, value, JVMFlag::INTERNAL);
1140   env->ReleaseStringUTFChars(name, flag_name);
1141   return (result == JVMFlag::SUCCESS);
1142 }
1143 
1144 template <typename T>
1145 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
1146   ResourceMark rm(thread);
1147   jclass clazz = env->FindClass(name->as_C_string());
1148   CHECK_JNI_EXCEPTION_(env, NULL);
1149   jmethodID methodID = env->GetStaticMethodID(clazz,
1150         vmSymbols::valueOf_name()->as_C_string(),
1151         sig->as_C_string());
1152   CHECK_JNI_EXCEPTION_(env, NULL);
1153   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
1154   CHECK_JNI_EXCEPTION_(env, NULL);
1155   return result;
1156 }
1157 
1158 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
1159   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
1160 }
1161 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
1162   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
1163 }
1164 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
1165   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
1166 }
1167 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
1168   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
1169 }*/
1170 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
1171   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
1172 }
1173 
1174 static JVMFlag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
1175   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1176   const char* flag_name = env->GetStringUTFChars(name, NULL);
1177   CHECK_JNI_EXCEPTION_(env, NULL);
1178   JVMFlag* result = JVMFlag::find_flag(flag_name, strlen(flag_name), true, true);
1179   env->ReleaseStringUTFChars(name, flag_name);
1180   return result;
1181 }
1182 
1183 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
1184   JVMFlag* flag = getVMFlag(thread, env, name);
1185   return (flag != NULL) && flag->is_constant_in_binary();
1186 WB_END
1187 
1188 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
1189   JVMFlag* flag = getVMFlag(thread, env, name);
1190   return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
1191 WB_END
1192 
1193 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
1194   bool result;
1195   if (GetVMFlag <bool> (thread, env, name, &result, &JVMFlag::boolAt)) {
1196     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1197     return booleanBox(thread, env, result);
1198   }
1199   return NULL;
1200 WB_END
1201 
1202 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
1203   int result;
1204   if (GetVMFlag <int> (thread, env, name, &result, &JVMFlag::intAt)) {
1205     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1206     return longBox(thread, env, result);
1207   }
1208   return NULL;
1209 WB_END
1210 
1211 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
1212   uint result;
1213   if (GetVMFlag <uint> (thread, env, name, &result, &JVMFlag::uintAt)) {
1214     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1215     return longBox(thread, env, result);
1216   }
1217   return NULL;
1218 WB_END
1219 
1220 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
1221   intx result;
1222   if (GetVMFlag <intx> (thread, env, name, &result, &JVMFlag::intxAt)) {
1223     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1224     return longBox(thread, env, result);
1225   }
1226   return NULL;
1227 WB_END
1228 
1229 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
1230   uintx result;
1231   if (GetVMFlag <uintx> (thread, env, name, &result, &JVMFlag::uintxAt)) {
1232     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1233     return longBox(thread, env, result);
1234   }
1235   return NULL;
1236 WB_END
1237 
1238 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
1239   uint64_t result;
1240   if (GetVMFlag <uint64_t> (thread, env, name, &result, &JVMFlag::uint64_tAt)) {
1241     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1242     return longBox(thread, env, result);
1243   }
1244   return NULL;
1245 WB_END
1246 
1247 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
1248   size_t result;
1249   if (GetVMFlag <size_t> (thread, env, name, &result, &JVMFlag::size_tAt)) {
1250     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1251     return longBox(thread, env, result);
1252   }
1253   return NULL;
1254 WB_END
1255 
1256 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
1257   double result;
1258   if (GetVMFlag <double> (thread, env, name, &result, &JVMFlag::doubleAt)) {
1259     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1260     return doubleBox(thread, env, result);
1261   }
1262   return NULL;
1263 WB_END
1264 
1265 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
1266   ccstr ccstrResult;
1267   if (GetVMFlag <ccstr> (thread, env, name, &ccstrResult, &JVMFlag::ccstrAt)) {
1268     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1269     jstring result = env->NewStringUTF(ccstrResult);
1270     CHECK_JNI_EXCEPTION_(env, NULL);
1271     return result;
1272   }
1273   return NULL;
1274 WB_END
1275 
1276 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
1277   bool result = value == JNI_TRUE ? true : false;
1278   SetVMFlag <bool> (thread, env, name, &result, &JVMFlag::boolAtPut);
1279 WB_END
1280 
1281 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1282   int result = value;
1283   SetVMFlag <int> (thread, env, name, &result, &JVMFlag::intAtPut);
1284 WB_END
1285 
1286 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1287   uint result = value;
1288   SetVMFlag <uint> (thread, env, name, &result, &JVMFlag::uintAtPut);
1289 WB_END
1290 
1291 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1292   intx result = value;
1293   SetVMFlag <intx> (thread, env, name, &result, &JVMFlag::intxAtPut);
1294 WB_END
1295 
1296 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1297   uintx result = value;
1298   SetVMFlag <uintx> (thread, env, name, &result, &JVMFlag::uintxAtPut);
1299 WB_END
1300 
1301 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1302   uint64_t result = value;
1303   SetVMFlag <uint64_t> (thread, env, name, &result, &JVMFlag::uint64_tAtPut);
1304 WB_END
1305 
1306 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1307   size_t result = value;
1308   SetVMFlag <size_t> (thread, env, name, &result, &JVMFlag::size_tAtPut);
1309 WB_END
1310 
1311 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
1312   double result = value;
1313   SetVMFlag <double> (thread, env, name, &result, &JVMFlag::doubleAtPut);
1314 WB_END
1315 
1316 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
1317   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1318   const char* ccstrValue;
1319   if (value == NULL) {
1320     ccstrValue = NULL;
1321   }
1322   else {
1323     ccstrValue = env->GetStringUTFChars(value, NULL);
1324     CHECK_JNI_EXCEPTION(env);
1325   }
1326   ccstr ccstrResult = ccstrValue;
1327   bool needFree;
1328   {
1329     ThreadInVMfromNative ttvfn(thread); // back to VM
1330     needFree = SetVMFlag <ccstr> (thread, env, name, &ccstrResult, &JVMFlag::ccstrAtPut);
1331   }
1332   if (value != NULL) {
1333     env->ReleaseStringUTFChars(value, ccstrValue);
1334   }
1335   if (needFree) {
1336     FREE_C_HEAP_ARRAY(char, ccstrResult);
1337   }
1338 WB_END
1339 
1340 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
1341   WhiteBox::compilation_locked = true;
1342 WB_END
1343 
1344 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
1345   MonitorLockerEx mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
1346   WhiteBox::compilation_locked = false;
1347   mo.notify_all();
1348 WB_END
1349 
1350 WB_ENTRY(void, WB_ForceNMethodSweep(JNIEnv* env, jobject o))
1351   // Force a code cache sweep and block until it finished
1352   NMethodSweeper::force_sweep();
1353 WB_END
1354 
1355 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
1356   ResourceMark rm(THREAD);
1357   int len;
1358   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
1359   return (StringTable::lookup(name, len) != NULL);
1360 WB_END
1361 
1362 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
1363   Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1364   Universe::heap()->collect(GCCause::_wb_full_gc);
1365 #if INCLUDE_G1GC
1366   if (UseG1GC) {
1367     // Needs to be cleared explicitly for G1
1368     Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1369   }
1370 #endif // INCLUDE_G1GC
1371 WB_END
1372 
1373 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1374   Universe::heap()->collect(GCCause::_wb_young_gc);
1375 WB_END
1376 
1377 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1378   // static+volatile in order to force the read to happen
1379   // (not be eliminated by the compiler)
1380   static char c;
1381   static volatile char* p;
1382 
1383   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
1384   if (p == NULL) {
1385     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1386   }
1387 
1388   c = *p;
1389 WB_END
1390 
1391 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1392   const char* features = VM_Version::features_string();
1393   ThreadToNativeFromVM ttn(thread);
1394   jstring features_string = env->NewStringUTF(features);
1395 
1396   CHECK_JNI_EXCEPTION_(env, NULL);
1397 
1398   return features_string;
1399 WB_END
1400 
1401 int WhiteBox::get_blob_type(const CodeBlob* code) {
1402   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1403   if (code->is_aot()) {
1404     return -1;
1405   }
1406   return CodeCache::get_code_heap(code)->code_blob_type();
1407 }
1408 
1409 CodeHeap* WhiteBox::get_code_heap(int blob_type) {
1410   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1411   return CodeCache::get_code_heap(blob_type);
1412 }
1413 
1414 struct CodeBlobStub {
1415   CodeBlobStub(const CodeBlob* blob) :
1416       name(os::strdup(blob->name())),
1417       size(blob->size()),
1418       blob_type(WhiteBox::get_blob_type(blob)),
1419       address((jlong) blob) { }
1420   ~CodeBlobStub() { os::free((void*) name); }
1421   const char* const name;
1422   const jint        size;
1423   const jint        blob_type;
1424   const jlong       address;
1425 };
1426 
1427 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1428   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1429   CHECK_JNI_EXCEPTION_(env, NULL);
1430   jobjectArray result = env->NewObjectArray(4, clazz, NULL);
1431 
1432   jstring name = env->NewStringUTF(cb->name);
1433   CHECK_JNI_EXCEPTION_(env, NULL);
1434   env->SetObjectArrayElement(result, 0, name);
1435 
1436   jobject obj = integerBox(thread, env, cb->size);
1437   CHECK_JNI_EXCEPTION_(env, NULL);
1438   env->SetObjectArrayElement(result, 1, obj);
1439 
1440   obj = integerBox(thread, env, cb->blob_type);
1441   CHECK_JNI_EXCEPTION_(env, NULL);
1442   env->SetObjectArrayElement(result, 2, obj);
1443 
1444   obj = longBox(thread, env, cb->address);
1445   CHECK_JNI_EXCEPTION_(env, NULL);
1446   env->SetObjectArrayElement(result, 3, obj);
1447 
1448   return result;
1449 }
1450 
1451 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1452   ResourceMark rm(THREAD);
1453   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1454   CHECK_JNI_EXCEPTION_(env, NULL);
1455   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1456   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1457   jobjectArray result = NULL;
1458   if (code == NULL) {
1459     return result;
1460   }
1461   int comp_level = code->comp_level();
1462   int insts_size = comp_level == CompLevel_aot ? code->code_end() - code->code_begin() : code->insts_size();
1463 
1464   ThreadToNativeFromVM ttn(thread);
1465   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1466   CHECK_JNI_EXCEPTION_(env, NULL);
1467   result = env->NewObjectArray(5, clazz, NULL);
1468   if (result == NULL) {
1469     return result;
1470   }
1471 
1472   CodeBlobStub stub(code);
1473   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1474   CHECK_JNI_EXCEPTION_(env, NULL);
1475   env->SetObjectArrayElement(result, 0, codeBlob);
1476 
1477   jobject level = integerBox(thread, env, comp_level);
1478   CHECK_JNI_EXCEPTION_(env, NULL);
1479   env->SetObjectArrayElement(result, 1, level);
1480 
1481   jbyteArray insts = env->NewByteArray(insts_size);
1482   CHECK_JNI_EXCEPTION_(env, NULL);
1483   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1484   env->SetObjectArrayElement(result, 2, insts);
1485 
1486   jobject id = integerBox(thread, env, code->compile_id());
1487   CHECK_JNI_EXCEPTION_(env, NULL);
1488   env->SetObjectArrayElement(result, 3, id);
1489 
1490   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1491   CHECK_JNI_EXCEPTION_(env, NULL);
1492   env->SetObjectArrayElement(result, 4, entry_point);
1493 
1494   return result;
1495 WB_END
1496 
1497 CodeBlob* WhiteBox::allocate_code_blob(int size, int blob_type) {
1498   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1499   BufferBlob* blob;
1500   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1501   if (full_size < size) {
1502     full_size += align_up(size - full_size, oopSize);
1503   }
1504   {
1505     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1506     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1507     if (blob != NULL) {
1508       ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1509     }
1510   }
1511   // Track memory usage statistic after releasing CodeCache_lock
1512   MemoryService::track_code_cache_memory_usage();
1513   return blob;
1514 }
1515 
1516 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1517   if (size < 0) {
1518     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1519       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1520   }
1521   return (jlong) WhiteBox::allocate_code_blob(size, blob_type);
1522 WB_END
1523 
1524 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1525   if (addr == 0) {
1526     return;
1527   }
1528   BufferBlob::free((BufferBlob*) addr);
1529 WB_END
1530 
1531 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1532   ResourceMark rm;
1533   GrowableArray<CodeBlobStub*> blobs;
1534   {
1535     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1536     CodeHeap* heap = WhiteBox::get_code_heap(blob_type);
1537     if (heap == NULL) {
1538       return NULL;
1539     }
1540     for (CodeBlob* cb = (CodeBlob*) heap->first();
1541          cb != NULL; cb = (CodeBlob*) heap->next(cb)) {
1542       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1543       new (stub) CodeBlobStub(cb);
1544       blobs.append(stub);
1545     }
1546   }
1547   ThreadToNativeFromVM ttn(thread);
1548   jobjectArray result = NULL;
1549   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1550   CHECK_JNI_EXCEPTION_(env, NULL);
1551   result = env->NewObjectArray(blobs.length(), clazz, NULL);
1552   CHECK_JNI_EXCEPTION_(env, NULL);
1553   if (result == NULL) {
1554     return result;
1555   }
1556   int i = 0;
1557   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1558        it != blobs.end(); ++it) {
1559     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1560     CHECK_JNI_EXCEPTION_(env, NULL);
1561     env->SetObjectArrayElement(result, i, obj);
1562     CHECK_JNI_EXCEPTION_(env, NULL);
1563     ++i;
1564   }
1565   return result;
1566 WB_END
1567 
1568 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1569   return CompileBroker::get_compilation_activity_mode();
1570 WB_END
1571 
1572 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1573   if (addr == 0) {
1574     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1575       "WB_GetCodeBlob: addr is null");
1576   }
1577   ThreadToNativeFromVM ttn(thread);
1578   CodeBlobStub stub((CodeBlob*) addr);
1579   return codeBlob2objectArray(thread, env, &stub);
1580 WB_END
1581 
1582 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1583   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1584   CHECK_JNI_EXCEPTION_(env, 0);
1585   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1586   return (jlong) mh->method_data();
1587 WB_END
1588 
1589 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1590   return (jlong) Thread::current()->stack_size();
1591 WB_END
1592 
1593 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1594   JavaThread* t = JavaThread::current();
1595   return (jlong) t->stack_available(os::current_stack_pointer()) - (jlong)JavaThread::stack_shadow_zone_size();
1596 WB_END
1597 
1598 
1599 int WhiteBox::array_bytes_to_length(size_t bytes) {
1600   return Array<u1>::bytes_to_length(bytes);
1601 }
1602 
1603 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1604   if (size < 0) {
1605     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1606         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1607   }
1608 
1609   oop class_loader_oop = JNIHandles::resolve(class_loader);
1610   ClassLoaderData* cld = class_loader_oop != NULL
1611       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1612       : ClassLoaderData::the_null_class_loader_data();
1613 
1614   void* metadata = MetadataFactory::new_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1615 
1616   return (jlong)(uintptr_t)metadata;
1617 WB_END
1618 
1619 WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
1620   oop class_loader_oop = JNIHandles::resolve(class_loader);
1621   ClassLoaderData* cld = class_loader_oop != NULL
1622       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1623       : ClassLoaderData::the_null_class_loader_data();
1624 
1625   MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
1626 WB_END
1627 
1628 WB_ENTRY(void, WB_DefineModule(JNIEnv* env, jobject o, jobject module, jboolean is_open,
1629                                 jstring version, jstring location, jobjectArray packages))
1630   ResourceMark rm(THREAD);
1631 
1632   objArrayOop packages_oop = objArrayOop(JNIHandles::resolve(packages));
1633   objArrayHandle packages_h(THREAD, packages_oop);
1634   int num_packages = (packages_h == NULL ? 0 : packages_h->length());
1635 
1636   char** pkgs = NULL;
1637   if (num_packages > 0) {
1638     pkgs = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char*, num_packages);
1639     for (int x = 0; x < num_packages; x++) {
1640       oop pkg_str = packages_h->obj_at(x);
1641       if (pkg_str == NULL || !pkg_str->is_a(SystemDictionary::String_klass())) {
1642         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1643                   err_msg("Bad package name"));
1644       }
1645       pkgs[x] = java_lang_String::as_utf8_string(pkg_str);
1646     }
1647   }
1648   Modules::define_module(module, is_open, version, location, (const char* const*)pkgs, num_packages, CHECK);
1649 WB_END
1650 
1651 WB_ENTRY(void, WB_AddModuleExports(JNIEnv* env, jobject o, jobject from_module, jstring package, jobject to_module))
1652   ResourceMark rm(THREAD);
1653   char* package_name = NULL;
1654   if (package != NULL) {
1655       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1656   }
1657   Modules::add_module_exports_qualified(from_module, package_name, to_module, CHECK);
1658 WB_END
1659 
1660 WB_ENTRY(void, WB_AddModuleExportsToAllUnnamed(JNIEnv* env, jobject o, jclass module, jstring package))
1661   ResourceMark rm(THREAD);
1662   char* package_name = NULL;
1663   if (package != NULL) {
1664       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1665   }
1666   Modules::add_module_exports_to_all_unnamed(module, package_name, CHECK);
1667 WB_END
1668 
1669 WB_ENTRY(void, WB_AddModuleExportsToAll(JNIEnv* env, jobject o, jclass module, jstring package))
1670   ResourceMark rm(THREAD);
1671   char* package_name = NULL;
1672   if (package != NULL) {
1673       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1674   }
1675   Modules::add_module_exports(module, package_name, NULL, CHECK);
1676 WB_END
1677 
1678 WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jobject source_module))
1679   Modules::add_reads_module(from_module, source_module, CHECK);
1680 WB_END
1681 
1682 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1683   if (inc < 0) {
1684     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1685         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1686   }
1687 
1688   jlong max_size_t = (jlong) ((size_t) -1);
1689   if (inc > max_size_t) {
1690     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1691         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1692   }
1693 
1694   size_t new_cap_until_GC = 0;
1695   size_t aligned_inc = align_down((size_t) inc, Metaspace::commit_alignment());
1696   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1697   if (!success) {
1698     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1699                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1700                 "due to contention with another thread");
1701   }
1702   return (jlong) new_cap_until_GC;
1703 WB_END
1704 
1705 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1706   return (jlong) MetaspaceGC::capacity_until_GC();
1707 WB_END
1708 
1709 WB_ENTRY(jboolean, WB_MetaspaceShouldConcurrentCollect(JNIEnv* env, jobject wb))
1710   return MetaspaceGC::should_concurrent_collect();
1711 WB_END
1712 
1713 WB_ENTRY(jlong, WB_MetaspaceReserveAlignment(JNIEnv* env, jobject wb))
1714   return (jlong)Metaspace::reserve_alignment();
1715 WB_END
1716 
1717 WB_ENTRY(void, WB_AssertMatchingSafepointCalls(JNIEnv* env, jobject o, jboolean mutexSafepointValue, jboolean attemptedNoSafepointValue))
1718   Monitor::SafepointCheckRequired sfpt_check_required = mutexSafepointValue ?
1719                                            Monitor::_safepoint_check_always :
1720                                            Monitor::_safepoint_check_never;
1721   MutexLockerEx ml(new Mutex(Mutex::leaf, "SFPT_Test_lock", true, sfpt_check_required),
1722                    attemptedNoSafepointValue == JNI_TRUE);
1723 WB_END
1724 
1725 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1726   oop obj_oop = JNIHandles::resolve(obj);
1727   return (jboolean) obj_oop->mark()->has_monitor();
1728 WB_END
1729 
1730 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1731   VM_ForceSafepoint force_safepoint_op;
1732   VMThread::execute(&force_safepoint_op);
1733 WB_END
1734 
1735 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1736   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1737   return (jlong) ik->constants();
1738 WB_END
1739 
1740 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1741   return ConstantPool::CPCACHE_INDEX_TAG;
1742 WB_END
1743 
1744 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1745   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1746   ConstantPool* cp = ik->constants();
1747   if (cp->cache() == NULL) {
1748       return -1;
1749   }
1750   return cp->cache()->length();
1751 WB_END
1752 
1753 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1754   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1755   ConstantPool* cp = ik->constants();
1756   if (cp->cache() == NULL) {
1757     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1758   }
1759   jint cpci = index;
1760   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1761   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1762     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1763   }
1764   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1765   return cpi;
1766 WB_END
1767 
1768 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1769   return ConstantPool::encode_invokedynamic_index(index);
1770 WB_END
1771 
1772 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb, jboolean preserve_static_stubs))
1773   VM_ClearICs clear_ics(preserve_static_stubs == JNI_TRUE);
1774   VMThread::execute(&clear_ics);
1775 WB_END
1776 
1777 template <typename T>
1778 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1779   assert(value != NULL, "sanity");
1780   if (method == NULL || name == NULL) {
1781     return false;
1782   }
1783   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1784   CHECK_JNI_EXCEPTION_(env, false);
1785   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1786   // can't be in VM when we call JNI
1787   ThreadToNativeFromVM ttnfv(thread);
1788   const char* flag_name = env->GetStringUTFChars(name, NULL);
1789   CHECK_JNI_EXCEPTION_(env, false);
1790   bool result =  CompilerOracle::has_option_value(mh, flag_name, *value);
1791   env->ReleaseStringUTFChars(name, flag_name);
1792   return result;
1793 }
1794 
1795 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1796   bool result;
1797   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1798     // can't be in VM when we call JNI
1799     ThreadToNativeFromVM ttnfv(thread);
1800     return booleanBox(thread, env, result);
1801   }
1802   return NULL;
1803 WB_END
1804 
1805 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1806   intx result;
1807   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1808     // can't be in VM when we call JNI
1809     ThreadToNativeFromVM ttnfv(thread);
1810     return longBox(thread, env, result);
1811   }
1812   return NULL;
1813 WB_END
1814 
1815 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1816   uintx result;
1817   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
1818     // can't be in VM when we call JNI
1819     ThreadToNativeFromVM ttnfv(thread);
1820     return longBox(thread, env, result);
1821   }
1822   return NULL;
1823 WB_END
1824 
1825 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1826   double result;
1827   if (GetMethodOption <double> (thread, env, method, name, &result)) {
1828     // can't be in VM when we call JNI
1829     ThreadToNativeFromVM ttnfv(thread);
1830     return doubleBox(thread, env, result);
1831   }
1832   return NULL;
1833 WB_END
1834 
1835 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1836   ccstr ccstrResult;
1837   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
1838     // can't be in VM when we call JNI
1839     ThreadToNativeFromVM ttnfv(thread);
1840     jstring result = env->NewStringUTF(ccstrResult);
1841     CHECK_JNI_EXCEPTION_(env, NULL);
1842     return result;
1843   }
1844   return NULL;
1845 WB_END
1846 
1847 WB_ENTRY(jobject, WB_GetDefaultArchivePath(JNIEnv* env, jobject wb))
1848   const char* p = Arguments::get_default_shared_archive_path();
1849   ThreadToNativeFromVM ttn(thread);
1850   jstring path_string = env->NewStringUTF(p);
1851 
1852   CHECK_JNI_EXCEPTION_(env, NULL);
1853 
1854   return path_string;
1855 WB_END
1856 
1857 WB_ENTRY(jboolean, WB_IsSharingEnabled(JNIEnv* env, jobject wb))
1858   return UseSharedSpaces;
1859 WB_END
1860 
1861 WB_ENTRY(jboolean, WB_IsShared(JNIEnv* env, jobject wb, jobject obj))
1862   oop obj_oop = JNIHandles::resolve(obj);
1863   return HeapShared::is_archived_object(obj_oop);
1864 WB_END
1865 
1866 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
1867   return (jboolean)MetaspaceShared::is_in_shared_metaspace(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1868 WB_END
1869 
1870 WB_ENTRY(jboolean, WB_AreSharedStringsIgnored(JNIEnv* env))
1871   return !HeapShared::closed_archive_heap_region_mapped();
1872 WB_END
1873 
1874 WB_ENTRY(jobject, WB_GetResolvedReferences(JNIEnv* env, jobject wb, jclass clazz))
1875   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1876   if (k->is_instance_klass()) {
1877     InstanceKlass *ik = InstanceKlass::cast(k);
1878     ConstantPool *cp = ik->constants();
1879     objArrayOop refs =  cp->resolved_references();
1880     return (jobject)JNIHandles::make_local(env, refs);
1881   } else {
1882     return NULL;
1883   }
1884 WB_END
1885 
1886 WB_ENTRY(jboolean, WB_AreOpenArchiveHeapObjectsMapped(JNIEnv* env))
1887   return HeapShared::open_archive_heap_region_mapped();
1888 WB_END
1889 
1890 WB_ENTRY(jboolean, WB_IsCDSIncludedInVmBuild(JNIEnv* env))
1891 #if INCLUDE_CDS
1892 # ifdef _LP64
1893     if (!UseCompressedOops || !UseCompressedClassPointers) {
1894       // On 64-bit VMs, CDS is supported only with compressed oops/pointers
1895       return false;
1896     }
1897 # endif // _LP64
1898   return true;
1899 #else
1900   return false;
1901 #endif // INCLUDE_CDS
1902 WB_END
1903 
1904 WB_ENTRY(jboolean, WB_IsJavaHeapArchiveSupported(JNIEnv* env))
1905   return HeapShared::is_heap_object_archiving_allowed();
1906 WB_END
1907 
1908 
1909 WB_ENTRY(jboolean, WB_IsJFRIncludedInVmBuild(JNIEnv* env))
1910 #if INCLUDE_JFR
1911   return true;
1912 #else
1913   return false;
1914 #endif // INCLUDE_JFR
1915 WB_END
1916 
1917 #if INCLUDE_CDS
1918 
1919 WB_ENTRY(jint, WB_GetOffsetForName(JNIEnv* env, jobject o, jstring name))
1920   ResourceMark rm;
1921   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
1922   int result = CDSOffsets::find_offset(c_name);
1923   return (jint)result;
1924 WB_END
1925 
1926 #endif // INCLUDE_CDS
1927 
1928 WB_ENTRY(jint, WB_HandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle, jboolean all_threads))
1929   class TraceSelfClosure : public ThreadClosure {
1930     jint _num_threads_completed;
1931 
1932     void do_thread(Thread* th) {
1933       assert(th->is_Java_thread(), "sanity");
1934       JavaThread* jt = (JavaThread*)th;
1935       ResourceMark rm;
1936 
1937       jt->print_on(tty);
1938       jt->print_stack_on(tty);
1939       tty->cr();
1940       Atomic::inc(&_num_threads_completed);
1941     }
1942 
1943   public:
1944     TraceSelfClosure() : _num_threads_completed(0) {}
1945 
1946     jint num_threads_completed() const { return _num_threads_completed; }
1947   };
1948   TraceSelfClosure tsc;
1949 
1950   if (all_threads) {
1951     Handshake::execute(&tsc);
1952   } else {
1953     oop thread_oop = JNIHandles::resolve(thread_handle);
1954     if (thread_oop != NULL) {
1955       JavaThread* target = java_lang_Thread::thread(thread_oop);
1956       Handshake::execute(&tsc, target);
1957     }
1958   }
1959   return tsc.num_threads_completed();
1960 WB_END
1961 
1962 //Some convenience methods to deal with objects from java
1963 int WhiteBox::offset_for_field(const char* field_name, oop object,
1964     Symbol* signature_symbol) {
1965   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
1966   Thread* THREAD = Thread::current();
1967 
1968   //Get the class of our object
1969   Klass* arg_klass = object->klass();
1970   //Turn it into an instance-klass
1971   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
1972 
1973   //Create symbols to look for in the class
1974   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
1975       THREAD);
1976 
1977   //To be filled in with an offset of the field we're looking for
1978   fieldDescriptor fd;
1979 
1980   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
1981   if (res == NULL) {
1982     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
1983         name_symbol->as_C_string());
1984     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
1985   }
1986 
1987   //fetch the field at the offset we've found
1988   int dest_offset = fd.offset();
1989 
1990   return dest_offset;
1991 }
1992 
1993 
1994 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
1995   int offset = offset_for_field(field_name, object,
1996       vmSymbols::string_signature());
1997   oop string = object->obj_field(offset);
1998   if (string == NULL) {
1999     return NULL;
2000   }
2001   const char* ret = java_lang_String::as_utf8_string(string);
2002   return ret;
2003 }
2004 
2005 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
2006   int offset =
2007       offset_for_field(field_name, object, vmSymbols::bool_signature());
2008   bool ret = (object->bool_field(offset) == JNI_TRUE);
2009   return ret;
2010 }
2011 
2012 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
2013   ResourceMark rm;
2014   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
2015 
2016   //  one by one registration natives for exception catching
2017   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
2018   CHECK_JNI_EXCEPTION(env);
2019   for (int i = 0, n = method_count; i < n; ++i) {
2020     // Skip dummy entries
2021     if (method_array[i].fnPtr == NULL) continue;
2022     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
2023       jthrowable throwable_obj = env->ExceptionOccurred();
2024       if (throwable_obj != NULL) {
2025         env->ExceptionClear();
2026         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
2027           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
2028           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
2029           tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s",
2030               method_array[i].name, method_array[i].signature);
2031         }
2032       } else {
2033         // Registration failed unexpectedly.
2034         tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered",
2035             method_array[i].name, method_array[i].signature);
2036         env->UnregisterNatives(wbclass);
2037         break;
2038       }
2039     }
2040   }
2041 }
2042 
2043 WB_ENTRY(jint, WB_AddCompilerDirective(JNIEnv* env, jobject o, jstring compDirect))
2044   // can't be in VM when we call JNI
2045   ThreadToNativeFromVM ttnfv(thread);
2046   const char* dir = env->GetStringUTFChars(compDirect, NULL);
2047   CHECK_JNI_EXCEPTION_(env, 0);
2048   int ret;
2049   {
2050     ThreadInVMfromNative ttvfn(thread); // back to VM
2051     ret = DirectivesParser::parse_string(dir, tty);
2052   }
2053   env->ReleaseStringUTFChars(compDirect, dir);
2054   // -1 for error parsing directive. Return 0 as number of directives added.
2055   if (ret == -1) {
2056     ret = 0;
2057   }
2058   return (jint) ret;
2059 WB_END
2060 
2061 WB_ENTRY(void, WB_RemoveCompilerDirective(JNIEnv* env, jobject o, jint count))
2062   DirectivesStack::pop(count);
2063 WB_END
2064 
2065 // Checks that the library libfile has the noexecstack bit set.
2066 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
2067   jboolean ret = false;
2068 #ifdef LINUX
2069   // Can't be in VM when we call JNI.
2070   ThreadToNativeFromVM ttnfv(thread);
2071   const char* lf = env->GetStringUTFChars(libfile, NULL);
2072   CHECK_JNI_EXCEPTION_(env, 0);
2073   ret = (jboolean) ElfFile::specifies_noexecstack(lf);
2074   env->ReleaseStringUTFChars(libfile, lf);
2075 #endif
2076   return ret;
2077 WB_END
2078 
2079 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
2080   LINUX_ONLY(return OSContainer::is_containerized();)
2081   return false;
2082 WB_END
2083 
2084 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
2085   os::print_os_info(tty);
2086 WB_END
2087 
2088 // Elf decoder
2089 WB_ENTRY(void, WB_DisableElfSectionCache(JNIEnv* env))
2090 #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX)
2091   ElfFile::_do_not_cache_elf_section = true;
2092 #endif
2093 WB_END
2094 
2095 WB_ENTRY(jint, WB_ResolvedMethodRemovedCount(JNIEnv* env, jobject o))
2096   return (jint) ResolvedMethodTable::removed_entries_count();
2097 WB_END
2098 
2099 WB_ENTRY(jint, WB_ProtectionDomainRemovedCount(JNIEnv* env, jobject o))
2100   return (jint) SystemDictionary::pd_cache_table()->removed_entries_count();
2101 WB_END
2102 
2103 WB_ENTRY(jint, WB_AotLibrariesCount(JNIEnv* env, jobject o))
2104   jint result = 0;
2105 #if INCLUDE_AOT
2106   result = (jint) AOTLoader::heaps_count();
2107 #endif
2108   return result;
2109 WB_END
2110 
2111 #define CC (char*)
2112 
2113 static JNINativeMethod methods[] = {
2114   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
2115   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
2116   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
2117   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
2118   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
2119   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
2120   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
2121   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
2122   {CC"getHeapAlignment",                 CC"()J",                   (void*)&WB_GetHeapAlignment},
2123   {CC"isClassAlive0",                    CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
2124   {CC"getSymbolRefcount",                CC"(Ljava/lang/String;)I", (void*)&WB_GetSymbolRefcount },
2125   {CC"parseCommandLine0",
2126       CC"(Ljava/lang/String;C[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
2127       (void*) &WB_ParseCommandLine
2128   },
2129   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
2130                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
2131   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
2132                                                       (void*)&WB_AddToSystemClassLoaderSearch},
2133   {CC"getCompressedOopsMaxHeapSize", CC"()J",
2134       (void*)&WB_GetCompressedOopsMaxHeapSize},
2135   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
2136   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
2137   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
2138   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
2139 #if INCLUDE_CDS
2140   {CC"getOffsetForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetOffsetForName},
2141 #endif
2142 #if INCLUDE_G1GC
2143   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
2144   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
2145   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
2146   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
2147   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
2148   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
2149   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
2150   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
2151   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
2152                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
2153   {CC"g1GetMixedGCInfo",   CC"(I)[J",                 (void*)&WB_G1GetMixedGCInfo },
2154 #endif // INCLUDE_G1GC
2155 #if INCLUDE_G1GC || INCLUDE_PARALLELGC
2156   {CC"dramReservedStart",   CC"()J",                  (void*)&WB_DramReservedStart },
2157   {CC"dramReservedEnd",     CC"()J",                  (void*)&WB_DramReservedEnd },
2158   {CC"nvdimmReservedStart", CC"()J",                  (void*)&WB_NvdimmReservedStart },
2159   {CC"nvdimmReservedEnd",   CC"()J",                  (void*)&WB_NvdimmReservedEnd },
2160 #endif // INCLUDE_G1GC || INCLUDE_PARALLELGC
2161 #if INCLUDE_PARALLELGC
2162   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
2163   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
2164 #endif
2165 #if INCLUDE_NMT
2166   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
2167   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
2168   {CC"NMTMallocWithPseudoStackAndType", CC"(JII)J",   (void*)&WB_NMTMallocWithPseudoStackAndType},
2169   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
2170   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
2171   {CC"NMTAttemptReserveMemoryAt",    CC"(JJ)J",       (void*)&WB_NMTAttemptReserveMemoryAt },
2172   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
2173   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
2174   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
2175   {CC"NMTChangeTrackingLevel", CC"()Z",               (void*)&WB_NMTChangeTrackingLevel},
2176   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
2177 #endif // INCLUDE_NMT
2178   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
2179   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
2180   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
2181                                                       (void*)&WB_DeoptimizeMethod  },
2182   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
2183                                                       (void*)&WB_IsMethodCompiled  },
2184   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
2185                                                       (void*)&WB_IsMethodCompilable},
2186   {CC"isMethodQueuedForCompilation0",
2187       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
2188   {CC"isIntrinsicAvailable0",
2189       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
2190                                                       (void*)&WB_IsIntrinsicAvailable},
2191   {CC"makeMethodNotCompilable0",
2192       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
2193   {CC"testSetDontInlineMethod0",
2194       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
2195   {CC"getMethodCompilationLevel0",
2196       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
2197   {CC"getMethodEntryBci0",
2198       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
2199   {CC"getCompileQueueSize",
2200       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
2201   {CC"testSetForceInlineMethod0",
2202       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
2203   {CC"enqueueMethodForCompilation0",
2204       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
2205   {CC"enqueueInitializerForCompilation0",
2206       CC"(Ljava/lang/Class;I)Z",                      (void*)&WB_EnqueueInitializerForCompilation},
2207   {CC"clearMethodState0",
2208       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
2209   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
2210   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
2211   {CC"matchesMethod",
2212       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2213                                                       (void*)&WB_MatchesMethod},
2214   {CC"matchesInline",
2215       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2216                                                       (void*)&WB_MatchesInline},
2217   {CC"shouldPrintAssembly",
2218         CC"(Ljava/lang/reflect/Executable;I)Z",
2219                                                         (void*)&WB_ShouldPrintAssembly},
2220 
2221   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
2222   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
2223   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
2224   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
2225   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
2226   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
2227   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
2228   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
2229   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
2230   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
2231   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
2232                                                       (void*)&WB_SetStringVMFlag},
2233   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
2234                                                       (void*)&WB_GetBooleanVMFlag},
2235   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
2236                                                       (void*)&WB_GetIntVMFlag},
2237   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2238                                                       (void*)&WB_GetUintVMFlag},
2239   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2240                                                       (void*)&WB_GetIntxVMFlag},
2241   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2242                                                       (void*)&WB_GetUintxVMFlag},
2243   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
2244                                                       (void*)&WB_GetUint64VMFlag},
2245   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2246                                                       (void*)&WB_GetSizeTVMFlag},
2247   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
2248                                                       (void*)&WB_GetDoubleVMFlag},
2249   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
2250                                                       (void*)&WB_GetStringVMFlag},
2251   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
2252   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
2253   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
2254   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
2255   {CC"allocateMetaspace",
2256      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
2257   {CC"freeMetaspace",
2258      CC"(Ljava/lang/ClassLoader;JJ)V",                (void*)&WB_FreeMetaspace },
2259   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
2260   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
2261   {CC"metaspaceShouldConcurrentCollect", CC"()Z",     (void*)&WB_MetaspaceShouldConcurrentCollect },
2262   {CC"metaspaceReserveAlignment", CC"()J",            (void*)&WB_MetaspaceReserveAlignment },
2263   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
2264   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
2265                                                       (void*)&WB_GetNMethod         },
2266   {CC"forceNMethodSweep",  CC"()V",                   (void*)&WB_ForceNMethodSweep  },
2267   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
2268   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
2269   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
2270   {CC"getCompilationActivityMode",
2271                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
2272   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
2273                                                       (void*)&WB_GetMethodData      },
2274   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
2275   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
2276   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
2277   {CC"DefineModule",       CC"(Ljava/lang/Object;ZLjava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V",
2278                                                       (void*)&WB_DefineModule },
2279   {CC"AddModuleExports",   CC"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
2280                                                       (void*)&WB_AddModuleExports },
2281   {CC"AddReadsModule",     CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
2282                                                       (void*)&WB_AddReadsModule },
2283   {CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2284                                                       (void*)&WB_AddModuleExportsToAllUnnamed },
2285   {CC"AddModuleExportsToAll", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2286                                                       (void*)&WB_AddModuleExportsToAll },
2287   {CC"assertMatchingSafepointCalls", CC"(ZZ)V",       (void*)&WB_AssertMatchingSafepointCalls },
2288   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
2289   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
2290   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
2291   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
2292   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
2293   {CC"remapInstructionOperandFromCPCache0",
2294       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
2295   {CC"encodeConstantPoolIndyIndex0",
2296       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
2297   {CC"getMethodBooleanOption",
2298       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
2299                                                       (void*)&WB_GetMethodBooleaneOption},
2300   {CC"getMethodIntxOption",
2301       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2302                                                       (void*)&WB_GetMethodIntxOption},
2303   {CC"getMethodUintxOption",
2304       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2305                                                       (void*)&WB_GetMethodUintxOption},
2306   {CC"getMethodDoubleOption",
2307       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
2308                                                       (void*)&WB_GetMethodDoubleOption},
2309   {CC"getMethodStringOption",
2310       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
2311                                                       (void*)&WB_GetMethodStringOption},
2312   {CC"getDefaultArchivePath",             CC"()Ljava/lang/String;",
2313                                                       (void*)&WB_GetDefaultArchivePath},
2314   {CC"isSharingEnabled",   CC"()Z",                   (void*)&WB_IsSharingEnabled},
2315   {CC"isShared",           CC"(Ljava/lang/Object;)Z", (void*)&WB_IsShared },
2316   {CC"isSharedClass",      CC"(Ljava/lang/Class;)Z",  (void*)&WB_IsSharedClass },
2317   {CC"areSharedStringsIgnored",           CC"()Z",    (void*)&WB_AreSharedStringsIgnored },
2318   {CC"getResolvedReferences", CC"(Ljava/lang/Class;)Ljava/lang/Object;", (void*)&WB_GetResolvedReferences},
2319   {CC"areOpenArchiveHeapObjectsMapped",   CC"()Z",    (void*)&WB_AreOpenArchiveHeapObjectsMapped},
2320   {CC"isCDSIncludedInVmBuild",            CC"()Z",    (void*)&WB_IsCDSIncludedInVmBuild },
2321   {CC"isJFRIncludedInVmBuild",            CC"()Z",    (void*)&WB_IsJFRIncludedInVmBuild },
2322   {CC"isJavaHeapArchiveSupported",      CC"()Z",      (void*)&WB_IsJavaHeapArchiveSupported },
2323 
2324   {CC"clearInlineCaches0",  CC"(Z)V",                 (void*)&WB_ClearInlineCaches },
2325   {CC"handshakeWalkStack", CC"(Ljava/lang/Thread;Z)I", (void*)&WB_HandshakeWalkStack },
2326   {CC"addCompilerDirective",    CC"(Ljava/lang/String;)I",
2327                                                       (void*)&WB_AddCompilerDirective },
2328   {CC"removeCompilerDirective",   CC"(I)V",           (void*)&WB_RemoveCompilerDirective },
2329   {CC"isGCSupported",             CC"(I)Z",           (void*)&WB_IsGCSupported},
2330   {CC"isGCSelected",              CC"(I)Z",           (void*)&WB_IsGCSelected},
2331   {CC"isGCSelectedErgonomically", CC"()Z",            (void*)&WB_IsGCSelectedErgonomically},
2332   {CC"supportsConcurrentGCPhaseControl", CC"()Z",     (void*)&WB_SupportsConcurrentGCPhaseControl},
2333   {CC"requestConcurrentGCPhase0", CC"(Ljava/lang/String;)Z",
2334                                                       (void*)&WB_RequestConcurrentGCPhase},
2335   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
2336                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
2337   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
2338   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
2339   {CC"disableElfSectionCache",    CC"()V",            (void*)&WB_DisableElfSectionCache },
2340   {CC"resolvedMethodRemovedCount",     CC"()I",       (void*)&WB_ResolvedMethodRemovedCount },
2341   {CC"protectionDomainRemovedCount",   CC"()I",       (void*)&WB_ProtectionDomainRemovedCount },
2342   {CC"aotLibrariesCount", CC"()I",                    (void*)&WB_AotLibrariesCount },
2343 };
2344 
2345 
2346 #undef CC
2347 
2348 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
2349   {
2350     if (WhiteBoxAPI) {
2351       // Make sure that wbclass is loaded by the null classloader
2352       InstanceKlass* ik = InstanceKlass::cast(JNIHandles::resolve(wbclass)->klass());
2353       Handle loader(THREAD, ik->class_loader());
2354       if (loader.is_null()) {
2355         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
2356         WhiteBox::set_used();
2357       }
2358     }
2359   }
2360 JVM_END