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