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