1 /*
   2  * Copyright (c) 2012, 2023, 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 #include "cds.h"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/cdsConstants.hpp"
  29 #include "cds/filemap.hpp"
  30 #include "cds/heapShared.hpp"
  31 #include "cds/metaspaceShared.hpp"
  32 #include "classfile/classLoaderDataGraph.hpp"
  33 #include "classfile/classLoaderStats.hpp"
  34 #include "classfile/javaClasses.inline.hpp"
  35 #include "classfile/modules.hpp"
  36 #include "classfile/protectionDomainCache.hpp"
  37 #include "classfile/stringTable.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/vmSymbols.hpp"
  41 #include "code/codeCache.hpp"
  42 #include "compiler/compilationPolicy.hpp"
  43 #include "compiler/directivesParser.hpp"
  44 #include "compiler/methodMatcher.hpp"
  45 #include "gc/shared/concurrentGCBreakpoints.hpp"
  46 #include "gc/shared/gcConfig.hpp"
  47 #include "gc/shared/gcLocker.inline.hpp"
  48 #include "gc/shared/genArguments.hpp"
  49 #include "gc/shared/genCollectedHeap.hpp"
  50 #include "jvmtifiles/jvmtiEnv.hpp"
  51 #include "logging/log.hpp"
  52 #include "memory/iterator.hpp"
  53 #include "memory/metadataFactory.hpp"
  54 #include "memory/metaspace/testHelpers.hpp"
  55 #include "memory/metaspaceUtils.hpp"
  56 #include "memory/oopFactory.hpp"
  57 #include "memory/resourceArea.hpp"
  58 #include "memory/universe.hpp"
  59 #include "oops/array.hpp"
  60 #include "oops/compressedOops.hpp"
  61 #include "oops/constantPool.inline.hpp"
  62 #include "oops/klass.inline.hpp"
  63 #include "oops/method.inline.hpp"
  64 #include "oops/objArrayKlass.hpp"
  65 #include "oops/objArrayOop.inline.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "oops/typeArrayOop.inline.hpp"
  68 #include "prims/jvmtiEnvBase.hpp"
  69 #include "prims/resolvedMethodTable.hpp"
  70 #include "prims/wbtestmethods/parserTests.hpp"
  71 #include "prims/whitebox.inline.hpp"
  72 #include "runtime/arguments.hpp"
  73 #include "runtime/atomic.hpp"
  74 #include "runtime/deoptimization.hpp"
  75 #include "runtime/fieldDescriptor.inline.hpp"
  76 #include "runtime/flags/jvmFlag.hpp"
  77 #include "runtime/flags/jvmFlagAccess.hpp"
  78 #include "runtime/frame.inline.hpp"
  79 #include "runtime/handles.inline.hpp"
  80 #include "runtime/handshake.hpp"
  81 #include "runtime/interfaceSupport.inline.hpp"
  82 #include "runtime/javaCalls.hpp"
  83 #include "runtime/javaThread.inline.hpp"
  84 #include "runtime/jniHandles.inline.hpp"
  85 #include "runtime/lockStack.hpp"
  86 #include "runtime/os.hpp"
  87 #include "runtime/stackFrameStream.inline.hpp"
  88 #include "runtime/synchronizer.hpp"
  89 #include "runtime/threadSMR.hpp"
  90 #include "runtime/vframe.hpp"
  91 #include "runtime/vm_version.hpp"
  92 #include "services/mallocSiteTable.hpp"
  93 #include "services/memoryService.hpp"
  94 #include "services/memTracker.hpp"
  95 #include "utilities/align.hpp"
  96 #include "utilities/debug.hpp"
  97 #include "utilities/elfFile.hpp"
  98 #include "utilities/exceptions.hpp"
  99 #include "utilities/macros.hpp"
 100 #include "utilities/nativeCallStack.hpp"
 101 #include "utilities/ostream.hpp"
 102 #if INCLUDE_G1GC
 103 #include "gc/g1/g1Arguments.hpp"
 104 #include "gc/g1/g1CollectedHeap.inline.hpp"
 105 #include "gc/g1/g1ConcurrentMark.hpp"
 106 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
 107 #include "gc/g1/heapRegionManager.hpp"
 108 #include "gc/g1/heapRegionRemSet.inline.hpp"
 109 #endif // INCLUDE_G1GC
 110 #if INCLUDE_PARALLELGC
 111 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
 112 #endif // INCLUDE_PARALLELGC
 113 #if INCLUDE_ZGC
 114 #include "gc/z/zAddress.inline.hpp"
 115 #endif // INCLUDE_ZGC
 116 #if INCLUDE_JVMCI
 117 #include "jvmci/jvmciEnv.hpp"
 118 #include "jvmci/jvmciRuntime.hpp"
 119 #endif
 120 #ifdef LINUX
 121 #include "os_linux.hpp"
 122 #include "osContainer_linux.hpp"
 123 #include "cgroupSubsystem_linux.hpp"
 124 #endif
 125 
 126 #define CHECK_JNI_EXCEPTION_(env, value)                               \
 127   do {                                                                 \
 128     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 129     THREAD->clear_pending_jni_exception_check();                       \
 130     if (HAS_PENDING_EXCEPTION) {                                       \
 131       return(value);                                                   \
 132     }                                                                  \
 133   } while (0)
 134 
 135 #define CHECK_JNI_EXCEPTION(env)                                       \
 136   do {                                                                 \
 137     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 138     THREAD->clear_pending_jni_exception_check();                       \
 139     if (HAS_PENDING_EXCEPTION) {                                       \
 140       return;                                                          \
 141     }                                                                  \
 142   } while (0)
 143 
 144 bool WhiteBox::_used = false;
 145 volatile bool WhiteBox::compilation_locked = false;
 146 
 147 class VM_WhiteBoxOperation : public VM_Operation {
 148  public:
 149   VM_WhiteBoxOperation()                         { }
 150   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
 151   bool allow_nested_vm_operations() const        { return true; }
 152 };
 153 
 154 
 155 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
 156   return (jlong)(void*)JNIHandles::resolve(obj);
 157 WB_END
 158 
 159 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
 160   return heapOopSize;
 161 WB_END
 162 
 163 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
 164   return (jint)os::vm_page_size();
 165 WB_END
 166 
 167 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
 168   return os::vm_allocation_granularity();
 169 WB_END
 170 
 171 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 172   return os::large_page_size();
 173 WB_END
 174 
 175 class WBIsKlassAliveClosure : public LockedClassesDo {
 176     Symbol* _name;
 177     int _count;
 178 public:
 179     WBIsKlassAliveClosure(Symbol* name) : _name(name), _count(0) {}
 180 
 181     void do_klass(Klass* k) {
 182       Symbol* ksym = k->name();
 183       if (ksym->fast_compare(_name) == 0) {
 184         _count++;
 185       } else if (k->is_instance_klass()) {
 186         // Need special handling for hidden classes because the JVM
 187         // appends "+<hex-address>" to hidden class names.
 188         InstanceKlass *ik = InstanceKlass::cast(k);
 189         if (ik->is_hidden()) {
 190           ResourceMark rm;
 191           char* k_name = ksym->as_C_string();
 192           // Find the first '+' char and truncate the string at that point.
 193           // NOTE: This will not work correctly if the original hidden class
 194           // name contains a '+'.
 195           char* plus_char = strchr(k_name, '+');
 196           if (plus_char != nullptr) {
 197             *plus_char = 0;
 198             char* c_name = _name->as_C_string();
 199             if (strcmp(c_name, k_name) == 0) {
 200               _count++;
 201             }
 202           }
 203         }
 204       }
 205     }
 206 
 207     int count() const {
 208         return _count;
 209     }
 210 };
 211 
 212 WB_ENTRY(jint, WB_CountAliveClasses(JNIEnv* env, jobject target, jstring name))
 213   oop h_name = JNIHandles::resolve(name);
 214   if (h_name == nullptr) {
 215     return 0;
 216   }
 217   Symbol* sym = java_lang_String::as_symbol(h_name);
 218   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 219 
 220   WBIsKlassAliveClosure closure(sym);
 221   ClassLoaderDataGraph::classes_do(&closure);
 222 
 223   // Return the count of alive classes with this name.
 224   return closure.count();
 225 WB_END
 226 
 227 WB_ENTRY(jint, WB_GetSymbolRefcount(JNIEnv* env, jobject unused, jstring name))
 228   oop h_name = JNIHandles::resolve(name);
 229   if (h_name == nullptr) {
 230     return 0;
 231   }
 232   Symbol* sym = java_lang_String::as_symbol(h_name);
 233   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 234   return (jint)sym->refcount();
 235 WB_END
 236 
 237 
 238 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 239 #if INCLUDE_JVMTI
 240   ResourceMark rm;
 241   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 242   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 243   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 244   assert(err == JVMTI_ERROR_NONE, "must not fail");
 245 #endif
 246 }
 247 WB_END
 248 
 249 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 250 #if INCLUDE_JVMTI
 251   ResourceMark rm;
 252   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 253   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 254   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 255   assert(err == JVMTI_ERROR_NONE, "must not fail");
 256 #endif
 257 }
 258 WB_END
 259 
 260 
 261 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 262   return (jlong)Arguments::max_heap_for_compressed_oops();
 263 }
 264 WB_END
 265 
 266 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 267   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap " SIZE_FORMAT " "
 268                 "Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 269                 MinHeapSize,
 270                 InitialHeapSize,
 271                 MaxHeapSize,
 272                 SpaceAlignment,
 273                 HeapAlignment);
 274 }
 275 WB_END
 276 
 277 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 278   size_t granularity = os::vm_allocation_granularity();
 279   ReservedHeapSpace rhs(100 * granularity, granularity, os::vm_page_size());
 280   VirtualSpace vs;
 281   vs.initialize(rhs, 50 * granularity);
 282 
 283   // Check if constraints are complied
 284   if (!( UseCompressedOops && rhs.base() != nullptr &&
 285          CompressedOops::base() != nullptr &&
 286          CompressedOops::use_implicit_null_checks() )) {
 287     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 288                   "\tUseCompressedOops is %d\n"
 289                   "\trhs.base() is " PTR_FORMAT "\n"
 290                   "\tCompressedOops::base() is " PTR_FORMAT "\n"
 291                   "\tCompressedOops::use_implicit_null_checks() is %d",
 292                   UseCompressedOops,
 293                   p2i(rhs.base()),
 294                   p2i(CompressedOops::base()),
 295                   CompressedOops::use_implicit_null_checks());
 296     return;
 297   }
 298   tty->print_cr("Reading from no access area... ");
 299   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 300                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 301 WB_END
 302 
 303 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 304                                            size_t magnitude, size_t iterations) {
 305   size_t granularity = os::vm_allocation_granularity();
 306   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, os::vm_page_size());
 307   VirtualSpace vs;
 308   if (!vs.initialize(rhs, 0)) {
 309     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 310     return 3;
 311   }
 312 
 313   int seed = os::random();
 314   tty->print_cr("Random seed is %d", seed);
 315 
 316   for (size_t i = 0; i < iterations; i++) {
 317 
 318     // Whether we will shrink or grow
 319     bool shrink = os::random() % 2L == 0;
 320 
 321     // Get random delta to resize virtual space
 322     size_t delta = (size_t)os::random() % magnitude;
 323 
 324     // If we are about to shrink virtual space below zero, then expand instead
 325     if (shrink && vs.committed_size() < delta) {
 326       shrink = false;
 327     }
 328 
 329     // Resizing by delta
 330     if (shrink) {
 331       vs.shrink_by(delta);
 332     } else {
 333       // If expanding fails expand_by will silently return false
 334       vs.expand_by(delta, true);
 335     }
 336   }
 337   return 0;
 338 }
 339 
 340 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 341         jlong reserved_space_size, jlong magnitude, jlong iterations))
 342   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 343                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 344                 iterations);
 345   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 346     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 347     return 1;
 348   }
 349 
 350   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 351   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 352   if (sizeof(size_t) < sizeof(jlong)) {
 353     jlong size_t_max_value = (jlong)SIZE_MAX;
 354     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 355         || iterations > size_t_max_value) {
 356       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 357       return 2;
 358     }
 359   }
 360 
 361   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 362                                         (size_t) magnitude, (size_t) iterations);
 363 WB_END
 364 
 365 WB_ENTRY(jboolean, WB_IsGCSupported(JNIEnv* env, jobject o, jint name))
 366   return GCConfig::is_gc_supported((CollectedHeap::Name)name);
 367 WB_END
 368 
 369 WB_ENTRY(jboolean, WB_IsGCSupportedByJVMCICompiler(JNIEnv* env, jobject o, jint name))
 370 #if INCLUDE_JVMCI
 371   if (EnableJVMCI) {
 372     // Enter the JVMCI env that will be used by the CompileBroker.
 373     JVMCIEnv jvmciEnv(thread, __FILE__, __LINE__);
 374     return jvmciEnv.runtime()->is_gc_supported(&jvmciEnv, (CollectedHeap::Name)name);
 375   }
 376 #endif
 377   return false;
 378 WB_END
 379 
 380 WB_ENTRY(jboolean, WB_IsGCSelected(JNIEnv* env, jobject o, jint name))
 381   return GCConfig::is_gc_selected((CollectedHeap::Name)name);
 382 WB_END
 383 
 384 WB_ENTRY(jboolean, WB_IsGCSelectedErgonomically(JNIEnv* env, jobject o))
 385   return GCConfig::is_gc_selected_ergonomically();
 386 WB_END
 387 
 388 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 389   oop p = JNIHandles::resolve(obj);
 390 #if INCLUDE_G1GC
 391   if (UseG1GC) {
 392     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 393     const HeapRegion* hr = g1h->heap_region_containing(p);
 394     return !(hr->is_young());
 395   }
 396 #endif
 397 #if INCLUDE_PARALLELGC
 398   if (UseParallelGC) {
 399     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 400     return !psh->is_in_young(p);
 401   }
 402 #endif
 403 #if INCLUDE_ZGC
 404   if (UseZGC) {
 405     if (ZGenerational) {
 406       return ZHeap::heap()->is_old(to_zaddress(p));
 407     } else {
 408       return Universe::heap()->is_in(p);
 409     }
 410   }
 411 #endif
 412 #if INCLUDE_SHENANDOAHGC
 413   if (UseShenandoahGC) {
 414     return Universe::heap()->is_in(p);
 415   }
 416 #endif
 417   GenCollectedHeap* gch = GenCollectedHeap::heap();
 418   return !gch->is_in_young(p);
 419 WB_END
 420 
 421 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 422   oop p = JNIHandles::resolve(obj);
 423   return p->size() * HeapWordSize;
 424 WB_END
 425 
 426 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 427   return (jlong)SpaceAlignment;
 428 WB_END
 429 
 430 WB_ENTRY(jlong, WB_GetHeapAlignment(JNIEnv* env, jobject o))
 431   return (jlong)HeapAlignment;
 432 WB_END
 433 
 434 WB_ENTRY(jboolean, WB_SupportsConcurrentGCBreakpoints(JNIEnv* env, jobject o))
 435   return Universe::heap()->supports_concurrent_gc_breakpoints();
 436 WB_END
 437 
 438 WB_ENTRY(void, WB_ConcurrentGCAcquireControl(JNIEnv* env, jobject o))
 439   ConcurrentGCBreakpoints::acquire_control();
 440 WB_END
 441 
 442 WB_ENTRY(void, WB_ConcurrentGCReleaseControl(JNIEnv* env, jobject o))
 443   ConcurrentGCBreakpoints::release_control();
 444 WB_END
 445 
 446 WB_ENTRY(void, WB_ConcurrentGCRunToIdle(JNIEnv* env, jobject o))
 447   ConcurrentGCBreakpoints::run_to_idle();
 448 WB_END
 449 
 450 WB_ENTRY(jboolean, WB_ConcurrentGCRunTo(JNIEnv* env, jobject o, jobject at))
 451   Handle h_name(THREAD, JNIHandles::resolve(at));
 452   ResourceMark rm;
 453   const char* c_name = java_lang_String::as_utf8_string(h_name());
 454   return ConcurrentGCBreakpoints::run_to(c_name);
 455 WB_END
 456 
 457 #if INCLUDE_G1GC
 458 
 459 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 460   if (UseG1GC) {
 461     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 462     oop result = JNIHandles::resolve(obj);
 463     const HeapRegion* hr = g1h->heap_region_containing(result);
 464     return hr->is_humongous();
 465   }
 466   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1IsHumongous: G1 GC is not enabled");
 467 WB_END
 468 
 469 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 470   if (UseG1GC) {
 471     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 472     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 473     return hr->is_humongous();
 474   }
 475   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToHumongousRegion: G1 GC is not enabled");
 476 WB_END
 477 
 478 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 479   if (UseG1GC) {
 480     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 481     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 482     return hr->is_free();
 483   }
 484   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToFreeRegion: G1 GC is not enabled");
 485 WB_END
 486 
 487 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 488   if (UseG1GC) {
 489     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 490     size_t nr = g1h->max_regions();
 491     return (jlong)nr;
 492   }
 493   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumMaxRegions: G1 GC is not enabled");
 494 WB_END
 495 
 496 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 497   if (UseG1GC) {
 498     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 499     size_t nr = g1h->num_free_regions();
 500     return (jlong)nr;
 501   }
 502   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumFreeRegions: G1 GC is not enabled");
 503 WB_END
 504 
 505 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 506   if (UseG1GC) {
 507     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 508     return g1h->concurrent_mark()->cm_thread()->in_progress();
 509   }
 510   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1InConcurrentMark: G1 GC is not enabled");
 511 WB_END
 512 
 513 WB_ENTRY(jint, WB_G1CompletedConcurrentMarkCycles(JNIEnv* env, jobject o))
 514   if (UseG1GC) {
 515     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 516     G1ConcurrentMark* cm = g1h->concurrent_mark();
 517     return cm->completed_mark_cycles();
 518   }
 519   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1CompletedConcurrentMarkCycles: G1 GC is not enabled");
 520 WB_END
 521 
 522 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 523   if (UseG1GC) {
 524     return (jint)HeapRegion::GrainBytes;
 525   }
 526   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1RegionSize: G1 GC is not enabled");
 527 WB_END
 528 
 529 WB_ENTRY(jboolean, WB_G1HasRegionsToUncommit(JNIEnv* env, jobject o))
 530   if (UseG1GC) {
 531     return G1CollectedHeap::heap()->has_uncommittable_regions();
 532   }
 533   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1HasRegionsToUncommit: G1 GC is not enabled");
 534 WB_END
 535 
 536 #endif // INCLUDE_G1GC
 537 
 538 #if INCLUDE_PARALLELGC
 539 
 540 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 541   if (UseParallelGC) {
 542     return GenAlignment;
 543   }
 544   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSVirtualSpaceAlignment: Parallel GC is not enabled");
 545 WB_END
 546 
 547 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 548   if (UseParallelGC) {
 549     return GenAlignment;
 550   }
 551   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSHeapGenerationAlignment: Parallel GC is not enabled");
 552 WB_END
 553 
 554 #endif // INCLUDE_PARALLELGC
 555 
 556 #if INCLUDE_G1GC
 557 
 558 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 559   if (UseG1GC) {
 560     ResourceMark rm(THREAD);
 561     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 562     MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 563     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 564     return JNIHandles::make_local(THREAD, h());
 565   }
 566   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1AuxiliaryMemoryUsage: G1 GC is not enabled");
 567 WB_END
 568 
 569 WB_ENTRY(jint, WB_G1ActiveMemoryNodeCount(JNIEnv* env, jobject o))
 570   if (UseG1GC) {
 571     G1NUMA* numa = G1NUMA::numa();
 572     return (jint)numa->num_active_nodes();
 573   }
 574   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1ActiveMemoryNodeCount: G1 GC is not enabled");
 575 WB_END
 576 
 577 WB_ENTRY(jintArray, WB_G1MemoryNodeIds(JNIEnv* env, jobject o))
 578   if (UseG1GC) {
 579     G1NUMA* numa = G1NUMA::numa();
 580     int num_node_ids = (int)numa->num_active_nodes();
 581     const int* node_ids = numa->node_ids();
 582 
 583     typeArrayOop result = oopFactory::new_intArray(num_node_ids, CHECK_NULL);
 584     for (int i = 0; i < num_node_ids; i++) {
 585       result->int_at_put(i, (jint)node_ids[i]);
 586     }
 587     return (jintArray) JNIHandles::make_local(THREAD, result);
 588   }
 589   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1MemoryNodeIds: G1 GC is not enabled");
 590 WB_END
 591 
 592 class OldRegionsLivenessClosure: public HeapRegionClosure {
 593 
 594  private:
 595   const int _liveness;
 596   size_t _total_count;
 597   size_t _total_memory;
 598   size_t _total_memory_to_free;
 599 
 600  public:
 601   OldRegionsLivenessClosure(int liveness) :
 602     _liveness(liveness),
 603     _total_count(0),
 604     _total_memory(0),
 605     _total_memory_to_free(0) { }
 606 
 607     size_t total_count() { return _total_count; }
 608     size_t total_memory() { return _total_memory; }
 609     size_t total_memory_to_free() { return _total_memory_to_free; }
 610 
 611   bool do_heap_region(HeapRegion* r) {
 612     if (r->is_old()) {
 613       size_t live = r->live_bytes();
 614       size_t size = r->used();
 615       size_t reg_size = HeapRegion::GrainBytes;
 616       if (size > 0 && ((int)(live * 100 / size) < _liveness)) {
 617         _total_memory += size;
 618         ++_total_count;
 619         if (size == reg_size) {
 620           // We don't include non-full regions since they are unlikely included in mixed gc
 621           // for testing purposes it's enough to have lowest estimation of total memory that is expected to be freed
 622           _total_memory_to_free += size - live;
 623         }
 624       }
 625     }
 626     return false;
 627   }
 628 };
 629 
 630 
 631 WB_ENTRY(jlongArray, WB_G1GetMixedGCInfo(JNIEnv* env, jobject o, jint liveness))
 632   if (!UseG1GC) {
 633     THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1GetMixedGCInfo: G1 GC is not enabled");
 634   }
 635   if (liveness < 0) {
 636     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "liveness value should be non-negative");
 637   }
 638 
 639   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 640   OldRegionsLivenessClosure rli(liveness);
 641   g1h->heap_region_iterate(&rli);
 642 
 643   typeArrayOop result = oopFactory::new_longArray(3, CHECK_NULL);
 644   result->long_at_put(0, rli.total_count());
 645   result->long_at_put(1, rli.total_memory());
 646   result->long_at_put(2, rli.total_memory_to_free());
 647   return (jlongArray) JNIHandles::make_local(THREAD, result);
 648 WB_END
 649 
 650 #endif // INCLUDE_G1GC
 651 
 652 // Alloc memory using the test memory type so that we can use that to see if
 653 // NMT picks it up correctly
 654 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 655   jlong addr = 0;
 656   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 657   return addr;
 658 WB_END
 659 
 660 // Alloc memory with pseudo call stack. The test can create pseudo malloc
 661 // allocation site to stress the malloc tracking.
 662 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 663   address pc = (address)(size_t)pseudo_stack;
 664   NativeCallStack stack(&pc, 1);
 665   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 666 WB_END
 667 
 668 // Alloc memory with pseudo call stack and specific memory type.
 669 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStackAndType(JNIEnv* env, jobject o, jlong size, jint pseudo_stack, jint type))
 670   address pc = (address)(size_t)pseudo_stack;
 671   NativeCallStack stack(&pc, 1);
 672   return (jlong)(uintptr_t)os::malloc(size, (MEMFLAGS)type, stack);
 673 WB_END
 674 
 675 // Free the memory allocated by NMTAllocTest
 676 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 677   os::free((void*)(uintptr_t)mem);
 678 WB_END
 679 
 680 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 681   jlong addr = 0;
 682 
 683   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 684   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 685 
 686   return addr;
 687 WB_END
 688 
 689 WB_ENTRY(jlong, WB_NMTAttemptReserveMemoryAt(JNIEnv* env, jobject o, jlong addr, jlong size))
 690   addr = (jlong)(uintptr_t)os::attempt_reserve_memory_at((char*)(uintptr_t)addr, (size_t)size);
 691   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 692 
 693   return addr;
 694 WB_END
 695 
 696 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 697   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 698   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 699 WB_END
 700 
 701 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 702   os::uncommit_memory((char *)(uintptr_t)addr, size);
 703 WB_END
 704 
 705 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 706   os::release_memory((char *)(uintptr_t)addr, size);
 707 WB_END
 708 
 709 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 710   int hash_size = MallocSiteTable::hash_buckets();
 711   assert(hash_size > 0, "NMT hash_size should be > 0");
 712   return (jint)hash_size;
 713 WB_END
 714 
 715 WB_ENTRY(jlong, WB_NMTNewArena(JNIEnv* env, jobject o, jlong init_size))
 716   Arena* arena =  new (mtTest) Arena(mtTest, size_t(init_size));
 717   return (jlong)arena;
 718 WB_END
 719 
 720 WB_ENTRY(void, WB_NMTFreeArena(JNIEnv* env, jobject o, jlong arena))
 721   Arena* a = (Arena*)arena;
 722   delete a;
 723 WB_END
 724 
 725 WB_ENTRY(void, WB_NMTArenaMalloc(JNIEnv* env, jobject o, jlong arena, jlong size))
 726   Arena* a = (Arena*)arena;
 727   a->Amalloc(size_t(size));
 728 WB_END
 729 
 730 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 731   assert(method != nullptr, "method should not be null");
 732   ThreadToNativeFromVM ttn(thread);
 733   return env->FromReflectedMethod(method);
 734 }
 735 
 736 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 737 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 738  private:
 739   int _result;
 740   const bool _make_not_entrant;
 741  public:
 742   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 743         _result(0), _make_not_entrant(make_not_entrant) { }
 744   int  result() const { return _result; }
 745 
 746   void doit() {
 747     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 748       if (t->has_last_Java_frame()) {
 749         for (StackFrameStream fst(t, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
 750           frame* f = fst.current();
 751           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 752             Deoptimization::deoptimize(t, *f);
 753             if (_make_not_entrant) {
 754                 CompiledMethod* cm = CodeCache::find_compiled(f->pc());
 755                 assert(cm != nullptr, "sanity check");
 756                 cm->make_not_entrant();
 757             }
 758             ++_result;
 759           }
 760         }
 761       }
 762     }
 763   }
 764 };
 765 
 766 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 767   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 768   VMThread::execute(&op);
 769   return op.result();
 770 WB_END
 771 
 772 WB_ENTRY(jboolean, WB_IsFrameDeoptimized(JNIEnv* env, jobject o, jint depth))
 773   bool result = false;
 774   if (thread->has_last_Java_frame()) {
 775     RegisterMap reg_map(thread,
 776                         RegisterMap::UpdateMap::include,
 777                         RegisterMap::ProcessFrames::include,
 778                         RegisterMap::WalkContinuation::skip);
 779     javaVFrame *jvf = thread->last_java_vframe(&reg_map);
 780     for (jint d = 0; d < depth && jvf != nullptr; d++) {
 781       jvf = jvf->java_sender();
 782     }
 783     result = jvf != nullptr && jvf->fr().is_deoptimized_frame();
 784   }
 785   return result;
 786 WB_END
 787 
 788 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 789   DeoptimizationScope deopt_scope;
 790   CodeCache::mark_all_nmethods_for_deoptimization(&deopt_scope);
 791   deopt_scope.deoptimize_marked();
 792 WB_END
 793 
 794 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 795   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 796   int result = 0;
 797   CHECK_JNI_EXCEPTION_(env, result);
 798 
 799   DeoptimizationScope deopt_scope;
 800   {
 801     MutexLocker mu(Compile_lock);
 802     methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 803     if (is_osr) {
 804       result += mh->method_holder()->mark_osr_nmethods(&deopt_scope, mh());
 805     } else {
 806       MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
 807       if (mh->code() != nullptr) {
 808         deopt_scope.mark(mh->code());
 809         ++result;
 810       }
 811     }
 812     CodeCache::mark_for_deoptimization(&deopt_scope, mh());
 813   }
 814 
 815   deopt_scope.deoptimize_marked();
 816 
 817   return result;
 818 WB_END
 819 
 820 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 821   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 822   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 823   MutexLocker mu(Compile_lock);
 824   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 825   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 826   if (code == nullptr) {
 827     return JNI_FALSE;
 828   }
 829   return !code->is_marked_for_deoptimization();
 830 WB_END
 831 
 832 static bool is_excluded_for_compiler(AbstractCompiler* comp, methodHandle& mh) {
 833   if (comp == nullptr) {
 834     return true;
 835   }
 836   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
 837   bool exclude = directive->ExcludeOption;
 838   DirectivesStack::release(directive);
 839   return exclude;
 840 }
 841 
 842 static bool can_be_compiled_at_level(methodHandle& mh, jboolean is_osr, int level) {
 843   if (is_osr) {
 844     return CompilationPolicy::can_be_osr_compiled(mh, level);
 845   } else {
 846     return CompilationPolicy::can_be_compiled(mh, level);
 847   }
 848 }
 849 
 850 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 851   if (method == nullptr || comp_level > CompilationPolicy::highest_compile_level()) {
 852     return false;
 853   }
 854   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 855   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 856   MutexLocker mu(Compile_lock);
 857   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 858 
 859   // The ExcludeOption directive is evaluated lazily upon compilation attempt. If a method was not tried to be compiled by
 860   // a compiler, yet, the method object is not set to be not compilable by that compiler. Thus, evaluate the compiler directive
 861   // to exclude a compilation of 'method'.
 862   if (comp_level == CompLevel_any) {
 863     // Both compilers could have ExcludeOption set. Check all combinations.
 864     bool excluded_c1 = is_excluded_for_compiler(CompileBroker::compiler1(), mh);
 865     bool excluded_c2 = is_excluded_for_compiler(CompileBroker::compiler2(), mh);
 866     if (excluded_c1 && excluded_c2) {
 867       // Compilation of 'method' excluded by both compilers.
 868       return false;
 869     }
 870 
 871     if (excluded_c1) {
 872       // C1 only has ExcludeOption set: Check if compilable with C2.
 873       return can_be_compiled_at_level(mh, is_osr, CompLevel_full_optimization);
 874     } else if (excluded_c2) {
 875       // C2 only has ExcludeOption set: Check if compilable with C1.
 876       return can_be_compiled_at_level(mh, is_osr, CompLevel_simple);
 877     }
 878   } else if (comp_level > CompLevel_none && is_excluded_for_compiler(CompileBroker::compiler((int)comp_level), mh)) {
 879     // Compilation of 'method' excluded by compiler used for 'comp_level'.
 880     return false;
 881   }
 882 
 883   return can_be_compiled_at_level(mh, is_osr, (int)comp_level);
 884 WB_END
 885 
 886 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 887   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 888   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 889   MutexLocker mu(Compile_lock);
 890   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 891   return mh->queued_for_compilation();
 892 WB_END
 893 
 894 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 895   if (compLevel < CompLevel_none || compLevel > CompilationPolicy::highest_compile_level()) {
 896     return false; // Intrinsic is not available on a non-existent compilation level.
 897   }
 898   jmethodID method_id, compilation_context_id;
 899   method_id = reflected_method_to_jmid(thread, env, method);
 900   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 901   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 902 
 903   DirectiveSet* directive;
 904   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 905   assert(comp != nullptr, "compiler not available");
 906   if (compilation_context != nullptr) {
 907     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 908     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 909     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 910     directive = DirectivesStack::getMatchingDirective(cch, comp);
 911   } else {
 912     // Calling with null matches default directive
 913     directive = DirectivesStack::getDefaultDirective(comp);
 914   }
 915   bool result = comp->is_intrinsic_available(mh, directive);
 916   DirectivesStack::release(directive);
 917   return result;
 918 WB_END
 919 
 920 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 921   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 922   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 923   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 924   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 925   return (code != nullptr ? code->comp_level() : CompLevel_none);
 926 WB_END
 927 
 928 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 929   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 930   CHECK_JNI_EXCEPTION(env);
 931   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 932   if (is_osr) {
 933     mh->set_not_osr_compilable("WhiteBox", comp_level);
 934   } else {
 935     mh->set_not_compilable("WhiteBox", comp_level);
 936   }
 937 WB_END
 938 
 939 WB_ENTRY(jint, WB_GetMethodDecompileCount(JNIEnv* env, jobject o, jobject method))
 940   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 941   CHECK_JNI_EXCEPTION_(env, 0);
 942   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 943   uint cnt = 0;
 944   MethodData* mdo = mh->method_data();
 945   if (mdo != nullptr) {
 946     cnt = mdo->decompile_count();
 947   }
 948   return cnt;
 949 WB_END
 950 
 951 // Get the trap count of a method for a specific reason. If the trap count for
 952 // that reason did overflow, this includes the overflow trap count of the method.
 953 // If 'reason' is null, the sum of the traps for all reasons will be returned.
 954 // This number includes the overflow trap count if the trap count for any reason
 955 // did overflow.
 956 WB_ENTRY(jint, WB_GetMethodTrapCount(JNIEnv* env, jobject o, jobject method, jstring reason_obj))
 957   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 958   CHECK_JNI_EXCEPTION_(env, 0);
 959   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 960   uint cnt = 0;
 961   MethodData* mdo = mh->method_data();
 962   if (mdo != nullptr) {
 963     ResourceMark rm(THREAD);
 964     char* reason_str = (reason_obj == nullptr) ?
 965       nullptr : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(reason_obj));
 966     bool overflow = false;
 967     for (uint reason = 0; reason < mdo->trap_reason_limit(); reason++) {
 968       if (reason_str != nullptr && !strcmp(reason_str, Deoptimization::trap_reason_name(reason))) {
 969         cnt = mdo->trap_count(reason);
 970         // Count in the overflow trap count on overflow
 971         if (cnt == (uint)-1) {
 972           cnt = mdo->trap_count_limit() + mdo->overflow_trap_count();
 973         }
 974         break;
 975       } else if (reason_str == nullptr) {
 976         uint c = mdo->trap_count(reason);
 977         if (c == (uint)-1) {
 978           c = mdo->trap_count_limit();
 979           if (!overflow) {
 980             // Count overflow trap count just once
 981             overflow = true;
 982             c += mdo->overflow_trap_count();
 983           }
 984         }
 985         cnt += c;
 986       }
 987     }
 988   }
 989   return cnt;
 990 WB_END
 991 
 992 WB_ENTRY(jint, WB_GetDeoptCount(JNIEnv* env, jobject o, jstring reason_obj, jstring action_obj))
 993   if (reason_obj == nullptr && action_obj == nullptr) {
 994     return Deoptimization::total_deoptimization_count();
 995   }
 996   ResourceMark rm(THREAD);
 997   const char *reason_str = (reason_obj == nullptr) ?
 998     nullptr : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(reason_obj));
 999   const char *action_str = (action_obj == nullptr) ?
1000     nullptr : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(action_obj));
1001 
1002   return Deoptimization::deoptimization_count(reason_str, action_str);
1003 WB_END
1004 
1005 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
1006   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1007   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
1008   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1009   CompiledMethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
1010   return (code != nullptr && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
1011 WB_END
1012 
1013 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
1014   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1015   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1016   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1017   bool result = mh->dont_inline();
1018   mh->set_dont_inline(value == JNI_TRUE);
1019   return result;
1020 WB_END
1021 
1022 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
1023   if (comp_level == CompLevel_any) {
1024     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
1025         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
1026   } else {
1027     return CompileBroker::queue_size(comp_level);
1028   }
1029 WB_END
1030 
1031 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
1032   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1033   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1034   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1035   bool result = mh->force_inline();
1036   mh->set_force_inline(value == JNI_TRUE);
1037   return result;
1038 WB_END
1039 
1040 #ifdef LINUX
1041 bool WhiteBox::validate_cgroup(const char* proc_cgroups,
1042                                const char* proc_self_cgroup,
1043                                const char* proc_self_mountinfo,
1044                                u1* cg_flags) {
1045   CgroupInfo cg_infos[CG_INFO_LENGTH];
1046   return CgroupSubsystemFactory::determine_type(cg_infos, proc_cgroups,
1047                                                     proc_self_cgroup,
1048                                                     proc_self_mountinfo, cg_flags);
1049 }
1050 #endif
1051 
1052 bool WhiteBox::compile_method(Method* method, int comp_level, int bci, JavaThread* THREAD) {
1053   // Screen for unavailable/bad comp level or null method
1054   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1055   if (method == nullptr) {
1056     tty->print_cr("WB error: request to compile null method");
1057     return false;
1058   }
1059   if (comp_level > CompilationPolicy::highest_compile_level()) {
1060     tty->print_cr("WB error: invalid compilation level %d", comp_level);
1061     return false;
1062   }
1063   if (comp == nullptr) {
1064     tty->print_cr("WB error: no compiler for requested compilation level %d", comp_level);
1065     return false;
1066   }
1067 
1068   // Check if compilation is blocking
1069   methodHandle mh(THREAD, method);
1070   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
1071   bool is_blocking = !directive->BackgroundCompilationOption;
1072   DirectivesStack::release(directive);
1073 
1074   // Compile method and check result
1075   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), CompileTask::Reason_Whitebox, CHECK_false);
1076   MutexLocker mu(THREAD, Compile_lock);
1077   bool is_queued = mh->queued_for_compilation();
1078   if ((!is_blocking && is_queued) || nm != nullptr) {
1079     return true;
1080   }
1081   // Check code again because compilation may be finished before Compile_lock is acquired.
1082   if (bci == InvocationEntryBci) {
1083     CompiledMethod* code = mh->code();
1084     if (code != nullptr && code->as_nmethod_or_null() != nullptr) {
1085       return true;
1086     }
1087   } else if (mh->lookup_osr_nmethod_for(bci, comp_level, false) != nullptr) {
1088     return true;
1089   }
1090   tty->print("WB error: failed to %s compile at level %d method ", is_blocking ? "blocking" : "", comp_level);
1091   mh->print_short_name(tty);
1092   tty->cr();
1093   if (is_blocking && is_queued) {
1094     tty->print_cr("WB error: blocking compilation is still in queue!");
1095   }
1096   return false;
1097 }
1098 
1099 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
1100   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1101   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1102   return WhiteBox::compile_method(Method::checked_resolve_jmethod_id(jmid), comp_level, bci, THREAD);
1103 WB_END
1104 
1105 WB_ENTRY(jboolean, WB_EnqueueInitializerForCompilation(JNIEnv* env, jobject o, jclass klass, jint comp_level))
1106   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1107   Method* clinit = ik->class_initializer();
1108   if (clinit == nullptr || clinit->method_holder()->is_not_initialized()) {
1109     return false;
1110   }
1111   return WhiteBox::compile_method(clinit, comp_level, InvocationEntryBci, THREAD);
1112 WB_END
1113 
1114 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
1115   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1116   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1117 
1118   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1119   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
1120   bool result = directive->PrintAssemblyOption;
1121   DirectivesStack::release(directive);
1122 
1123   return result;
1124 WB_END
1125 
1126 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
1127   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1128   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1129 
1130   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1131 
1132   ResourceMark rm(THREAD);
1133   const char* error_msg = nullptr;
1134   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1135   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
1136 
1137   if (m == nullptr) {
1138     assert(error_msg != nullptr, "Always have an error message");
1139     tty->print_cr("Got error: %s", error_msg);
1140     return -1; // Pattern failed
1141   }
1142 
1143   // Pattern works - now check if it matches
1144   int result;
1145   if (m->match(mh, InlineMatcher::force_inline)) {
1146     result = 2; // Force inline match
1147   } else if (m->match(mh, InlineMatcher::dont_inline)) {
1148     result = 1; // Dont inline match
1149   } else {
1150     result = 0; // No match
1151   }
1152   delete m;
1153   return result;
1154 WB_END
1155 
1156 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
1157   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1158   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1159 
1160   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1161 
1162   ResourceMark rm;
1163   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1164 
1165   const char* error_msg = nullptr;
1166 
1167   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg, false);
1168   if (m == nullptr) {
1169     assert(error_msg != nullptr, "Must have error_msg");
1170     tty->print_cr("Got error: %s", error_msg);
1171     return -1;
1172   }
1173 
1174   // Pattern works - now check if it matches
1175   int result = m->matches(mh);
1176   delete m;
1177   assert(result == 0 || result == 1, "Result out of range");
1178   return result;
1179 WB_END
1180 
1181 WB_ENTRY(void, WB_MarkMethodProfiled(JNIEnv* env, jobject o, jobject method))
1182   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1183   CHECK_JNI_EXCEPTION(env);
1184   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1185 
1186   MethodData* mdo = mh->method_data();
1187   if (mdo == nullptr) {
1188     Method::build_profiling_method_data(mh, CHECK_AND_CLEAR);
1189     mdo = mh->method_data();
1190   }
1191   mdo->init();
1192   InvocationCounter* icnt = mdo->invocation_counter();
1193   InvocationCounter* bcnt = mdo->backedge_counter();
1194   // set i-counter according to CompilationPolicy::is_method_profiled
1195   icnt->set(Tier4MinInvocationThreshold);
1196   bcnt->set(Tier4CompileThreshold);
1197 WB_END
1198 
1199 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
1200   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1201   CHECK_JNI_EXCEPTION(env);
1202   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1203   MutexLocker mu(THREAD, Compile_lock);
1204   MethodData* mdo = mh->method_data();
1205   MethodCounters* mcs = mh->method_counters();
1206 
1207   if (mdo != nullptr) {
1208     mdo->init();
1209     ResourceMark rm(THREAD);
1210     int arg_count = mdo->method()->size_of_parameters();
1211     for (int i = 0; i < arg_count; i++) {
1212       mdo->set_arg_modified(i, 0);
1213     }
1214     MutexLocker mu(THREAD, mdo->extra_data_lock());
1215     mdo->clean_method_data(/*always_clean*/true);
1216   }
1217 
1218   mh->clear_is_not_c1_compilable();
1219   mh->clear_is_not_c2_compilable();
1220   mh->clear_is_not_c2_osr_compilable();
1221   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
1222   if (mcs != nullptr) {
1223     mcs->clear_counters();
1224   }
1225 WB_END
1226 
1227 template <typename T, int type_enum>
1228 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value) {
1229   if (name == nullptr) {
1230     return false;
1231   }
1232   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1233   const char* flag_name = env->GetStringUTFChars(name, nullptr);
1234   CHECK_JNI_EXCEPTION_(env, false);
1235   const JVMFlag* flag = JVMFlag::find_declared_flag(flag_name);
1236   JVMFlag::Error result = JVMFlagAccess::get<T, type_enum>(flag, value);
1237   env->ReleaseStringUTFChars(name, flag_name);
1238   return (result == JVMFlag::SUCCESS);
1239 }
1240 
1241 template <typename T, int type_enum>
1242 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value) {
1243   if (name == nullptr) {
1244     return false;
1245   }
1246   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1247   const char* flag_name = env->GetStringUTFChars(name, nullptr);
1248   CHECK_JNI_EXCEPTION_(env, false);
1249   JVMFlag* flag = JVMFlag::find_flag(flag_name);
1250   JVMFlag::Error result = JVMFlagAccess::set<T, type_enum>(flag, value, JVMFlagOrigin::INTERNAL);
1251   env->ReleaseStringUTFChars(name, flag_name);
1252   return (result == JVMFlag::SUCCESS);
1253 }
1254 
1255 template <typename T>
1256 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
1257   ResourceMark rm(thread);
1258   jclass clazz = env->FindClass(name->as_C_string());
1259   CHECK_JNI_EXCEPTION_(env, nullptr);
1260   jmethodID methodID = env->GetStaticMethodID(clazz,
1261         vmSymbols::valueOf_name()->as_C_string(),
1262         sig->as_C_string());
1263   CHECK_JNI_EXCEPTION_(env, nullptr);
1264   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
1265   CHECK_JNI_EXCEPTION_(env, nullptr);
1266   return result;
1267 }
1268 
1269 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
1270   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
1271 }
1272 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
1273   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
1274 }
1275 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
1276   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
1277 }
1278 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
1279   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
1280 }*/
1281 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
1282   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
1283 }
1284 
1285 static const JVMFlag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
1286   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1287   const char* flag_name = env->GetStringUTFChars(name, nullptr);
1288   CHECK_JNI_EXCEPTION_(env, nullptr);
1289   const JVMFlag* result = JVMFlag::find_declared_flag(flag_name);
1290   env->ReleaseStringUTFChars(name, flag_name);
1291   return result;
1292 }
1293 
1294 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
1295   const JVMFlag* flag = getVMFlag(thread, env, name);
1296   return (flag != nullptr) && flag->is_constant_in_binary();
1297 WB_END
1298 
1299 WB_ENTRY(jboolean, WB_IsDefaultVMFlag(JNIEnv* env, jobject o, jstring name))
1300   const JVMFlag* flag = getVMFlag(thread, env, name);
1301   return (flag != nullptr) && flag->is_default();
1302 WB_END
1303 
1304 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
1305   const JVMFlag* flag = getVMFlag(thread, env, name);
1306   return (flag != nullptr) && !(flag->is_unlocked() || flag->is_unlocker());
1307 WB_END
1308 
1309 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
1310   bool result;
1311   if (GetVMFlag <JVM_FLAG_TYPE(bool)> (thread, env, name, &result)) {
1312     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1313     return booleanBox(thread, env, result);
1314   }
1315   return nullptr;
1316 WB_END
1317 
1318 template <typename T, int type_enum>
1319 jobject GetVMFlag_longBox(JNIEnv* env, JavaThread* thread, jstring name) {
1320   T result;
1321   if (GetVMFlag <T, type_enum> (thread, env, name, &result)) {
1322     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1323     return longBox(thread, env, result);
1324   }
1325   return nullptr;
1326 }
1327 
1328 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
1329   return GetVMFlag_longBox<JVM_FLAG_TYPE(int)>(env, thread, name);
1330 WB_END
1331 
1332 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
1333   return GetVMFlag_longBox<JVM_FLAG_TYPE(uint)>(env, thread, name);
1334 WB_END
1335 
1336 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
1337   return GetVMFlag_longBox<JVM_FLAG_TYPE(intx)>(env, thread, name);
1338 WB_END
1339 
1340 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
1341   return GetVMFlag_longBox<JVM_FLAG_TYPE(uintx)>(env, thread, name);
1342 WB_END
1343 
1344 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
1345   return GetVMFlag_longBox<JVM_FLAG_TYPE(uint64_t)>(env, thread, name);
1346 WB_END
1347 
1348 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
1349   return GetVMFlag_longBox<JVM_FLAG_TYPE(size_t)>(env, thread, name);
1350 WB_END
1351 
1352 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
1353   double result;
1354   if (GetVMFlag <JVM_FLAG_TYPE(double)> (thread, env, name, &result)) {
1355     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1356     return doubleBox(thread, env, result);
1357   }
1358   return nullptr;
1359 WB_END
1360 
1361 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
1362   ccstr ccstrResult;
1363   if (GetVMFlag <JVM_FLAG_TYPE(ccstr)> (thread, env, name, &ccstrResult)) {
1364     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1365     jstring result = env->NewStringUTF(ccstrResult);
1366     CHECK_JNI_EXCEPTION_(env, nullptr);
1367     return result;
1368   }
1369   return nullptr;
1370 WB_END
1371 
1372 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
1373   bool result = value == JNI_TRUE ? true : false;
1374   SetVMFlag <JVM_FLAG_TYPE(bool)> (thread, env, name, &result);
1375 WB_END
1376 
1377 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1378   int result = value;
1379   SetVMFlag <JVM_FLAG_TYPE(int)> (thread, env, name, &result);
1380 WB_END
1381 
1382 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1383   uint result = value;
1384   SetVMFlag <JVM_FLAG_TYPE(uint)> (thread, env, name, &result);
1385 WB_END
1386 
1387 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1388   intx result = value;
1389   SetVMFlag <JVM_FLAG_TYPE(intx)> (thread, env, name, &result);
1390 WB_END
1391 
1392 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1393   uintx result = value;
1394   SetVMFlag <JVM_FLAG_TYPE(uintx)> (thread, env, name, &result);
1395 WB_END
1396 
1397 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1398   uint64_t result = value;
1399   SetVMFlag <JVM_FLAG_TYPE(uint64_t)> (thread, env, name, &result);
1400 WB_END
1401 
1402 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1403   size_t result = value;
1404   SetVMFlag <JVM_FLAG_TYPE(size_t)> (thread, env, name, &result);
1405 WB_END
1406 
1407 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
1408   double result = value;
1409   SetVMFlag <JVM_FLAG_TYPE(double)> (thread, env, name, &result);
1410 WB_END
1411 
1412 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
1413   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1414   const char* ccstrValue;
1415   if (value == nullptr) {
1416     ccstrValue = nullptr;
1417   }
1418   else {
1419     ccstrValue = env->GetStringUTFChars(value, nullptr);
1420     CHECK_JNI_EXCEPTION(env);
1421   }
1422   {
1423     ccstr param = ccstrValue;
1424     ThreadInVMfromNative ttvfn(thread); // back to VM
1425     if (SetVMFlag <JVM_FLAG_TYPE(ccstr)> (thread, env, name, &param)) {
1426       assert(param == nullptr, "old value is freed automatically and not returned");
1427     }
1428   }
1429   if (value != nullptr) {
1430     env->ReleaseStringUTFChars(value, ccstrValue);
1431   }
1432 WB_END
1433 
1434 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
1435   WhiteBox::compilation_locked = true;
1436 WB_END
1437 
1438 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
1439   MonitorLocker mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
1440   WhiteBox::compilation_locked = false;
1441   mo.notify_all();
1442 WB_END
1443 
1444 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
1445   ResourceMark rm(THREAD);
1446   int len;
1447   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
1448   return (StringTable::lookup(name, len) != nullptr);
1449 WB_END
1450 
1451 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
1452   Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1453   Universe::heap()->collect(GCCause::_wb_full_gc);
1454 #if INCLUDE_G1GC
1455   if (UseG1GC) {
1456     // Needs to be cleared explicitly for G1
1457     Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1458   }
1459 #endif // INCLUDE_G1GC
1460 WB_END
1461 
1462 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1463   Universe::heap()->collect(GCCause::_wb_young_gc);
1464 WB_END
1465 
1466 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1467   // static+volatile in order to force the read to happen
1468   // (not be eliminated by the compiler)
1469   static char c;
1470   static volatile char* p;
1471 
1472   p = os::reserve_memory(os::vm_allocation_granularity());
1473   if (p == nullptr) {
1474     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1475   }
1476 
1477   c = *p;
1478 WB_END
1479 
1480 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1481   const char* features = VM_Version::features_string();
1482   ThreadToNativeFromVM ttn(thread);
1483   jstring features_string = env->NewStringUTF(features);
1484 
1485   CHECK_JNI_EXCEPTION_(env, nullptr);
1486 
1487   return features_string;
1488 WB_END
1489 
1490 CodeBlobType WhiteBox::get_blob_type(const CodeBlob* code) {
1491   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1492   return CodeCache::get_code_heap(code)->code_blob_type();
1493 }
1494 
1495 CodeHeap* WhiteBox::get_code_heap(CodeBlobType blob_type) {
1496   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1497   return CodeCache::get_code_heap(blob_type);
1498 }
1499 
1500 struct CodeBlobStub {
1501   CodeBlobStub(const CodeBlob* blob) :
1502       name(os::strdup(blob->name())),
1503       size(blob->size()),
1504       blob_type(static_cast<jint>(WhiteBox::get_blob_type(blob))),
1505       address((jlong) blob) { }
1506   ~CodeBlobStub() { os::free((void*) name); }
1507   const char* const name;
1508   const jint        size;
1509   const jint        blob_type;
1510   const jlong       address;
1511 };
1512 
1513 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1514   ResourceMark rm;
1515   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1516   CHECK_JNI_EXCEPTION_(env, nullptr);
1517   jobjectArray result = env->NewObjectArray(4, clazz, nullptr);
1518 
1519   jstring name = env->NewStringUTF(cb->name);
1520   CHECK_JNI_EXCEPTION_(env, nullptr);
1521   env->SetObjectArrayElement(result, 0, name);
1522 
1523   jobject obj = integerBox(thread, env, cb->size);
1524   CHECK_JNI_EXCEPTION_(env, nullptr);
1525   env->SetObjectArrayElement(result, 1, obj);
1526 
1527   obj = integerBox(thread, env, cb->blob_type);
1528   CHECK_JNI_EXCEPTION_(env, nullptr);
1529   env->SetObjectArrayElement(result, 2, obj);
1530 
1531   obj = longBox(thread, env, cb->address);
1532   CHECK_JNI_EXCEPTION_(env, nullptr);
1533   env->SetObjectArrayElement(result, 3, obj);
1534 
1535   return result;
1536 }
1537 
1538 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1539   ResourceMark rm(THREAD);
1540   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1541   CHECK_JNI_EXCEPTION_(env, nullptr);
1542   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1543   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1544   jobjectArray result = nullptr;
1545   if (code == nullptr) {
1546     return result;
1547   }
1548   int comp_level = code->comp_level();
1549   int insts_size = code->insts_size();
1550 
1551   ThreadToNativeFromVM ttn(thread);
1552   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1553   CHECK_JNI_EXCEPTION_(env, nullptr);
1554   result = env->NewObjectArray(5, clazz, nullptr);
1555   if (result == nullptr) {
1556     return result;
1557   }
1558 
1559   CodeBlobStub stub(code);
1560   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1561   CHECK_JNI_EXCEPTION_(env, nullptr);
1562   env->SetObjectArrayElement(result, 0, codeBlob);
1563 
1564   jobject level = integerBox(thread, env, comp_level);
1565   CHECK_JNI_EXCEPTION_(env, nullptr);
1566   env->SetObjectArrayElement(result, 1, level);
1567 
1568   jbyteArray insts = env->NewByteArray(insts_size);
1569   CHECK_JNI_EXCEPTION_(env, nullptr);
1570   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1571   env->SetObjectArrayElement(result, 2, insts);
1572 
1573   jobject id = integerBox(thread, env, code->compile_id());
1574   CHECK_JNI_EXCEPTION_(env, nullptr);
1575   env->SetObjectArrayElement(result, 3, id);
1576 
1577   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1578   CHECK_JNI_EXCEPTION_(env, nullptr);
1579   env->SetObjectArrayElement(result, 4, entry_point);
1580 
1581   return result;
1582 WB_END
1583 
1584 CodeBlob* WhiteBox::allocate_code_blob(int size, CodeBlobType blob_type) {
1585   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1586   BufferBlob* blob;
1587   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1588   if (full_size < size) {
1589     full_size += align_up(size - full_size, oopSize);
1590   }
1591   {
1592     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1593     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1594     if (blob != nullptr) {
1595       ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1596     }
1597   }
1598   // Track memory usage statistic after releasing CodeCache_lock
1599   MemoryService::track_code_cache_memory_usage();
1600   return blob;
1601 }
1602 
1603 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1604   if (size < 0) {
1605     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1606       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1607   }
1608   return (jlong) WhiteBox::allocate_code_blob(size, static_cast<CodeBlobType>(blob_type));
1609 WB_END
1610 
1611 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1612   if (addr == 0) {
1613     return;
1614   }
1615   BufferBlob::free((BufferBlob*) addr);
1616 WB_END
1617 
1618 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1619   ResourceMark rm;
1620   GrowableArray<CodeBlobStub*> blobs;
1621   {
1622     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1623     CodeHeap* heap = WhiteBox::get_code_heap(static_cast<CodeBlobType>(blob_type));
1624     if (heap == nullptr) {
1625       return nullptr;
1626     }
1627     for (CodeBlob* cb = (CodeBlob*) heap->first();
1628          cb != nullptr; cb = (CodeBlob*) heap->next(cb)) {
1629       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1630       new (stub) CodeBlobStub(cb);
1631       blobs.append(stub);
1632     }
1633   }
1634   ThreadToNativeFromVM ttn(thread);
1635   jobjectArray result = nullptr;
1636   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1637   CHECK_JNI_EXCEPTION_(env, nullptr);
1638   result = env->NewObjectArray(blobs.length(), clazz, nullptr);
1639   CHECK_JNI_EXCEPTION_(env, nullptr);
1640   if (result == nullptr) {
1641     return result;
1642   }
1643   int i = 0;
1644   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1645        it != blobs.end(); ++it) {
1646     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1647     CHECK_JNI_EXCEPTION_(env, nullptr);
1648     env->SetObjectArrayElement(result, i, obj);
1649     CHECK_JNI_EXCEPTION_(env, nullptr);
1650     ++i;
1651   }
1652   return result;
1653 WB_END
1654 
1655 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1656   return CompileBroker::get_compilation_activity_mode();
1657 WB_END
1658 
1659 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1660   if (addr == 0) {
1661     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1662       "WB_GetCodeBlob: addr is null");
1663   }
1664   ThreadToNativeFromVM ttn(thread);
1665   CodeBlobStub stub((CodeBlob*) addr);
1666   return codeBlob2objectArray(thread, env, &stub);
1667 WB_END
1668 
1669 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1670   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1671   CHECK_JNI_EXCEPTION_(env, 0);
1672   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1673   return (jlong) mh->method_data();
1674 WB_END
1675 
1676 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1677   return (jlong) thread->stack_size();
1678 WB_END
1679 
1680 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1681   return (jlong) thread->stack_overflow_state()->stack_available(
1682                    os::current_stack_pointer()) - (jlong)StackOverflow::stack_shadow_zone_size();
1683 WB_END
1684 
1685 
1686 int WhiteBox::array_bytes_to_length(size_t bytes) {
1687   return Array<u1>::bytes_to_length(bytes);
1688 }
1689 
1690 ///////////////
1691 // MetaspaceTestContext and MetaspaceTestArena
1692 WB_ENTRY(jlong, WB_CreateMetaspaceTestContext(JNIEnv* env, jobject wb, jlong commit_limit, jlong reserve_limit))
1693   metaspace::MetaspaceTestContext* context =
1694       new metaspace::MetaspaceTestContext("whitebox-metaspace-context", (size_t) commit_limit, (size_t) reserve_limit);
1695   return (jlong)p2i(context);
1696 WB_END
1697 
1698 WB_ENTRY(void, WB_DestroyMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1699   delete (metaspace::MetaspaceTestContext*) context;
1700 WB_END
1701 
1702 WB_ENTRY(void, WB_PurgeMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1703   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1704   context0->purge_area();
1705 WB_END
1706 
1707 WB_ENTRY(void, WB_PrintMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1708   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1709   context0->print_on(tty);
1710 WB_END
1711 
1712 WB_ENTRY(jlong, WB_GetTotalCommittedWordsInMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1713   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1714   return context0->committed_words();
1715 WB_END
1716 
1717 WB_ENTRY(jlong, WB_GetTotalUsedWordsInMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1718   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1719   return context0->used_words();
1720 WB_END
1721 
1722 WB_ENTRY(jlong, WB_CreateArenaInTestContext(JNIEnv* env, jobject wb, jlong context, jboolean is_micro))
1723   const Metaspace::MetaspaceType type = is_micro ? Metaspace::ReflectionMetaspaceType : Metaspace::StandardMetaspaceType;
1724   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1725   return (jlong)p2i(context0->create_arena(type));
1726 WB_END
1727 
1728 WB_ENTRY(void, WB_DestroyMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena))
1729   delete (metaspace::MetaspaceTestArena*) arena;
1730 WB_END
1731 
1732 WB_ENTRY(jlong, WB_AllocateFromMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena, jlong word_size))
1733   metaspace::MetaspaceTestArena* arena0 = (metaspace::MetaspaceTestArena*) arena;
1734   MetaWord* p = arena0->allocate((size_t) word_size);
1735   return (jlong)p2i(p);
1736 WB_END
1737 
1738 WB_ENTRY(void, WB_DeallocateToMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena, jlong p, jlong word_size))
1739   metaspace::MetaspaceTestArena* arena0 = (metaspace::MetaspaceTestArena*) arena;
1740   arena0->deallocate((MetaWord*)p, (size_t) word_size);
1741 WB_END
1742 
1743 WB_ENTRY(jlong, WB_GetMaxMetaspaceAllocationSize(JNIEnv* env, jobject wb))
1744   return (jlong) Metaspace::max_allocation_word_size() * BytesPerWord;
1745 WB_END
1746 
1747 //////////////
1748 
1749 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1750   if (size < 0) {
1751     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1752         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1753   }
1754 
1755   oop class_loader_oop = JNIHandles::resolve(class_loader);
1756   ClassLoaderData* cld = class_loader_oop != nullptr
1757       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1758       : ClassLoaderData::the_null_class_loader_data();
1759 
1760   void* metadata = MetadataFactory::new_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1761 
1762   return (jlong)(uintptr_t)metadata;
1763 WB_END
1764 
1765 WB_ENTRY(void, WB_DefineModule(JNIEnv* env, jobject o, jobject module, jboolean is_open,
1766                                 jstring version, jstring location, jobjectArray packages))
1767   Handle h_module (THREAD, JNIHandles::resolve(module));
1768   Modules::define_module(h_module, is_open, version, location, packages, CHECK);
1769 WB_END
1770 
1771 WB_ENTRY(void, WB_AddModuleExports(JNIEnv* env, jobject o, jobject from_module, jstring package, jobject to_module))
1772   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1773   Handle h_to_module (THREAD, JNIHandles::resolve(to_module));
1774   Modules::add_module_exports_qualified(h_from_module, package, h_to_module, CHECK);
1775 WB_END
1776 
1777 WB_ENTRY(void, WB_AddModuleExportsToAllUnnamed(JNIEnv* env, jobject o, jclass module, jstring package))
1778   Handle h_module (THREAD, JNIHandles::resolve(module));
1779   Modules::add_module_exports_to_all_unnamed(h_module, package, CHECK);
1780 WB_END
1781 
1782 WB_ENTRY(void, WB_AddModuleExportsToAll(JNIEnv* env, jobject o, jclass module, jstring package))
1783   Handle h_module (THREAD, JNIHandles::resolve(module));
1784   Modules::add_module_exports(h_module, package, Handle(), CHECK);
1785 WB_END
1786 
1787 WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jobject source_module))
1788   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1789   Handle h_source_module (THREAD, JNIHandles::resolve(source_module));
1790   Modules::add_reads_module(h_from_module, h_source_module, CHECK);
1791 WB_END
1792 
1793 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1794   if (inc < 0) {
1795     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1796         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1797   }
1798 
1799   jlong max_size_t = (jlong) ((size_t) -1);
1800   if (inc > max_size_t) {
1801     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1802         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1803   }
1804 
1805   size_t new_cap_until_GC = 0;
1806   size_t aligned_inc = align_down((size_t) inc, Metaspace::commit_alignment());
1807   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1808   if (!success) {
1809     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1810                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1811                 "due to contention with another thread");
1812   }
1813   return (jlong) new_cap_until_GC;
1814 WB_END
1815 
1816 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1817   return (jlong) MetaspaceGC::capacity_until_GC();
1818 WB_END
1819 
1820 // The function is only valid when CDS is available.
1821 WB_ENTRY(jlong, WB_MetaspaceSharedRegionAlignment(JNIEnv* env, jobject wb))
1822 #if INCLUDE_CDS
1823   return (jlong)MetaspaceShared::core_region_alignment();
1824 #else
1825   ShouldNotReachHere();
1826   return 0L;
1827 #endif
1828 WB_END
1829 
1830 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1831   oop obj_oop = JNIHandles::resolve(obj);
1832   return (jboolean) obj_oop->mark().has_monitor();
1833 WB_END
1834 
1835 WB_ENTRY(jint, WB_getLockStackCapacity(JNIEnv* env))
1836   return (jint) LockStack::CAPACITY;
1837 WB_END
1838 
1839 WB_ENTRY(jboolean, WB_supportsRecursiveLightweightLocking(JNIEnv* env))
1840   return (jboolean) VM_Version::supports_recursive_lightweight_locking();
1841 WB_END
1842 
1843 WB_ENTRY(jboolean, WB_DeflateIdleMonitors(JNIEnv* env, jobject wb))
1844   log_info(monitorinflation)("WhiteBox initiated DeflateIdleMonitors");
1845   return ObjectSynchronizer::request_deflate_idle_monitors_from_wb();
1846 WB_END
1847 
1848 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1849   VM_ForceSafepoint force_safepoint_op;
1850   VMThread::execute(&force_safepoint_op);
1851 WB_END
1852 
1853 WB_ENTRY(void, WB_ForceClassLoaderStatsSafepoint(JNIEnv* env, jobject wb))
1854   nullStream dev_null;
1855   ClassLoaderStatsVMOperation force_op(&dev_null);
1856   VMThread::execute(&force_op);
1857 WB_END
1858 
1859 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1860   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1861   return (jlong) ik->constants();
1862 WB_END
1863 
1864 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1865   return ConstantPool::CPCACHE_INDEX_TAG;
1866 WB_END
1867 
1868 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1869   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1870   ConstantPool* cp = ik->constants();
1871   if (cp->cache() == nullptr) {
1872       return -1;
1873   }
1874   return cp->cache()->length();
1875 WB_END
1876 
1877 WB_ENTRY(jobjectArray, WB_GetResolvedReferences(JNIEnv* env, jobject wb, jclass klass))
1878   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1879   objArrayOop resolved_refs= ik->constants()->resolved_references();
1880   return (jobjectArray)JNIHandles::make_local(THREAD, resolved_refs);
1881 WB_END
1882 
1883 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1884   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1885   ConstantPool* cp = ik->constants();
1886   if (cp->cache() == nullptr) {
1887     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1888   }
1889   jint cpci = index;
1890   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1891   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1892     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1893   }
1894   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1895   return cpi;
1896 WB_END
1897 
1898 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1899   return ConstantPool::encode_invokedynamic_index(index);
1900 WB_END
1901 
1902 WB_ENTRY(jint, WB_getIndyInfoLength(JNIEnv* env, jobject wb, jclass klass))
1903   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1904   ConstantPool* cp = ik->constants();
1905   if (cp->cache() == nullptr) {
1906       return -1;
1907   }
1908   return cp->resolved_indy_entries_length();
1909 WB_END
1910 
1911 WB_ENTRY(jint, WB_getIndyCPIndex(JNIEnv* env, jobject wb, jclass klass, jint index))
1912   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1913   ConstantPool* cp = ik->constants();
1914   if (cp->cache() == nullptr) {
1915       return -1;
1916   }
1917   return cp->resolved_indy_entry_at(index)->constant_pool_index();
1918 WB_END
1919 
1920 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb, jboolean preserve_static_stubs))
1921   VM_ClearICs clear_ics(preserve_static_stubs == JNI_TRUE);
1922   VMThread::execute(&clear_ics);
1923 WB_END
1924 
1925 template <typename T>
1926 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1927   assert(value != nullptr, "sanity");
1928   if (method == nullptr || name == nullptr) {
1929     return false;
1930   }
1931   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1932   CHECK_JNI_EXCEPTION_(env, false);
1933   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1934   // can't be in VM when we call JNI
1935   ThreadToNativeFromVM ttnfv(thread);
1936   const char* flag_name = env->GetStringUTFChars(name, nullptr);
1937   CHECK_JNI_EXCEPTION_(env, false);
1938   enum CompileCommand option = CompilerOracle::string_to_option(flag_name);
1939   env->ReleaseStringUTFChars(name, flag_name);
1940   if (option == CompileCommand::Unknown) {
1941     return false;
1942   }
1943   if (!CompilerOracle::option_matches_type(option, *value)) {
1944     return false;
1945   }
1946   return CompilerOracle::has_option_value(mh, option, *value);
1947 }
1948 
1949 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1950   bool result;
1951   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1952     // can't be in VM when we call JNI
1953     ThreadToNativeFromVM ttnfv(thread);
1954     return booleanBox(thread, env, result);
1955   }
1956   return nullptr;
1957 WB_END
1958 
1959 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1960   intx result;
1961   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1962     // can't be in VM when we call JNI
1963     ThreadToNativeFromVM ttnfv(thread);
1964     return longBox(thread, env, result);
1965   }
1966   return nullptr;
1967 WB_END
1968 
1969 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1970   uintx result;
1971   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
1972     // can't be in VM when we call JNI
1973     ThreadToNativeFromVM ttnfv(thread);
1974     return longBox(thread, env, result);
1975   }
1976   return nullptr;
1977 WB_END
1978 
1979 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1980   double result;
1981   if (GetMethodOption <double> (thread, env, method, name, &result)) {
1982     // can't be in VM when we call JNI
1983     ThreadToNativeFromVM ttnfv(thread);
1984     return doubleBox(thread, env, result);
1985   }
1986   return nullptr;
1987 WB_END
1988 
1989 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1990   ccstr ccstrResult;
1991   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
1992     // can't be in VM when we call JNI
1993     ThreadToNativeFromVM ttnfv(thread);
1994     jstring result = env->NewStringUTF(ccstrResult);
1995     CHECK_JNI_EXCEPTION_(env, nullptr);
1996     return result;
1997   }
1998   return nullptr;
1999 WB_END
2000 
2001 WB_ENTRY(jobject, WB_GetDefaultArchivePath(JNIEnv* env, jobject wb))
2002   const char* p = Arguments::get_default_shared_archive_path();
2003   ThreadToNativeFromVM ttn(thread);
2004   jstring path_string = env->NewStringUTF(p);
2005 
2006   CHECK_JNI_EXCEPTION_(env, nullptr);
2007 
2008   return path_string;
2009 WB_END
2010 
2011 WB_ENTRY(jboolean, WB_IsSharingEnabled(JNIEnv* env, jobject wb))
2012   return UseSharedSpaces;
2013 WB_END
2014 
2015 WB_ENTRY(jint, WB_GetCDSGenericHeaderMinVersion(JNIEnv* env, jobject wb))
2016 #if INCLUDE_CDS
2017   return (jint)CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION;
2018 #else
2019   ShouldNotReachHere();
2020   return (jint)-1;
2021 #endif
2022 WB_END
2023 
2024 WB_ENTRY(jint, WB_GetCDSCurrentVersion(JNIEnv* env, jobject wb))
2025 #if INCLUDE_CDS
2026   return (jint)CURRENT_CDS_ARCHIVE_VERSION;
2027 #else
2028   ShouldNotReachHere();
2029   return (jint)-1;
2030 #endif
2031 WB_END
2032 
2033 WB_ENTRY(jboolean, WB_CDSMemoryMappingFailed(JNIEnv* env, jobject wb))
2034   return FileMapInfo::memory_mapping_failed();
2035 WB_END
2036 
2037 WB_ENTRY(jboolean, WB_IsSharedInternedString(JNIEnv* env, jobject wb, jobject str))
2038   ResourceMark rm(THREAD);
2039   oop str_oop = JNIHandles::resolve(str);
2040   int length;
2041   jchar* chars = java_lang_String::as_unicode_string(str_oop, length, CHECK_(false));
2042   return StringTable::lookup_shared(chars, length) == str_oop;
2043 WB_END
2044 
2045 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
2046   return (jboolean)MetaspaceShared::is_in_shared_metaspace(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
2047 WB_END
2048 
2049 WB_ENTRY(jboolean, WB_AreSharedStringsMapped(JNIEnv* env))
2050   return ArchiveHeapLoader::is_mapped();
2051 WB_END
2052 
2053 WB_ENTRY(void, WB_LinkClass(JNIEnv* env, jobject wb, jclass clazz))
2054   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
2055   if (!k->is_instance_klass()) {
2056     return;
2057   }
2058   InstanceKlass *ik = InstanceKlass::cast(k);
2059   ik->link_class(THREAD); // may throw verification error
2060 WB_END
2061 
2062 WB_ENTRY(jboolean, WB_AreOpenArchiveHeapObjectsMapped(JNIEnv* env))
2063   return ArchiveHeapLoader::is_mapped();
2064 WB_END
2065 
2066 WB_ENTRY(jboolean, WB_IsCDSIncluded(JNIEnv* env))
2067 #if INCLUDE_CDS
2068   return true;
2069 #else
2070   return false;
2071 #endif // INCLUDE_CDS
2072 WB_END
2073 
2074 WB_ENTRY(jboolean, WB_isC2OrJVMCIIncluded(JNIEnv* env))
2075 #if COMPILER2_OR_JVMCI
2076   return true;
2077 #else
2078   return false;
2079 #endif
2080 WB_END
2081 
2082 WB_ENTRY(jboolean, WB_IsJVMCISupportedByGC(JNIEnv* env))
2083 #if INCLUDE_JVMCI
2084   return JVMCIGlobals::gc_supports_jvmci();
2085 #else
2086   return false;
2087 #endif
2088 WB_END
2089 
2090 WB_ENTRY(jboolean, WB_CanWriteJavaHeapArchive(JNIEnv* env))
2091   return HeapShared::can_write();
2092 WB_END
2093 
2094 
2095 WB_ENTRY(jboolean, WB_IsJFRIncluded(JNIEnv* env))
2096 #if INCLUDE_JFR
2097   return true;
2098 #else
2099   return false;
2100 #endif // INCLUDE_JFR
2101 WB_END
2102 
2103 WB_ENTRY(jboolean, WB_IsDTraceIncluded(JNIEnv* env))
2104 #if defined(DTRACE_ENABLED)
2105   return true;
2106 #else
2107   return false;
2108 #endif // DTRACE_ENABLED
2109 WB_END
2110 
2111 #if INCLUDE_CDS
2112 
2113 WB_ENTRY(jint, WB_GetCDSOffsetForName(JNIEnv* env, jobject o, jstring name))
2114   ResourceMark rm;
2115   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2116   jint result = (jint)CDSConstants::get_cds_offset(c_name);
2117   return result;
2118 WB_END
2119 
2120 WB_ENTRY(jint, WB_GetCDSConstantForName(JNIEnv* env, jobject o, jstring name))
2121   ResourceMark rm;
2122   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2123   jint result = (jint)CDSConstants::get_cds_constant(c_name);
2124   return result;
2125 WB_END
2126 
2127 #endif // INCLUDE_CDS
2128 
2129 WB_ENTRY(jboolean, WB_HandshakeReadMonitors(JNIEnv* env, jobject wb, jobject thread_handle))
2130   class ReadMonitorsClosure : public HandshakeClosure {
2131     jboolean _executed;
2132 
2133     void do_thread(Thread* th) {
2134       JavaThread* jt = JavaThread::cast(th);
2135       ResourceMark rm;
2136 
2137       GrowableArray<MonitorInfo*>* info = new GrowableArray<MonitorInfo*>();
2138 
2139       if (!jt->has_last_Java_frame()) {
2140         return;
2141       }
2142       RegisterMap rmap(jt,
2143                        RegisterMap::UpdateMap::include,
2144                        RegisterMap::ProcessFrames::include,
2145                        RegisterMap::WalkContinuation::skip);
2146       for (javaVFrame* vf = jt->last_java_vframe(&rmap); vf != nullptr; vf = vf->java_sender()) {
2147         GrowableArray<MonitorInfo*> *monitors = vf->monitors();
2148         if (monitors != nullptr) {
2149           int len = monitors->length();
2150           // Walk monitors youngest to oldest
2151           for (int i = len - 1; i >= 0; i--) {
2152             MonitorInfo* mon_info = monitors->at(i);
2153             if (mon_info->eliminated()) continue;
2154             oop owner = mon_info->owner();
2155             if (owner != nullptr) {
2156               info->append(mon_info);
2157             }
2158           }
2159         }
2160       }
2161       _executed = true;
2162     }
2163 
2164    public:
2165     ReadMonitorsClosure() : HandshakeClosure("WB_HandshakeReadMonitors"), _executed(false) {}
2166     jboolean executed() const { return _executed; }
2167   };
2168 
2169   ReadMonitorsClosure rmc;
2170   if (thread_handle != nullptr) {
2171     ThreadsListHandle tlh;
2172     JavaThread* target = nullptr;
2173     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, nullptr);
2174     if (is_alive) {
2175       Handshake::execute(&rmc, &tlh, target);
2176     }
2177   }
2178   return rmc.executed();
2179 WB_END
2180 
2181 WB_ENTRY(jint, WB_HandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle, jboolean all_threads))
2182   class TraceSelfClosure : public HandshakeClosure {
2183     jint _num_threads_completed;
2184 
2185     void do_thread(Thread* th) {
2186       JavaThread* jt = JavaThread::cast(th);
2187       ResourceMark rm;
2188 
2189       jt->print_on(tty);
2190       jt->print_stack_on(tty);
2191       tty->cr();
2192       Atomic::inc(&_num_threads_completed);
2193     }
2194 
2195   public:
2196     TraceSelfClosure(Thread* thread) : HandshakeClosure("WB_TraceSelf"), _num_threads_completed(0) {}
2197 
2198     jint num_threads_completed() const { return _num_threads_completed; }
2199   };
2200   TraceSelfClosure tsc(Thread::current());
2201 
2202   if (all_threads) {
2203     Handshake::execute(&tsc);
2204   } else if (thread_handle != nullptr) {
2205     ThreadsListHandle tlh;
2206     JavaThread* target = nullptr;
2207     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, nullptr);
2208     if (is_alive) {
2209       Handshake::execute(&tsc, &tlh, target);
2210     }
2211   }
2212   return tsc.num_threads_completed();
2213 WB_END
2214 
2215 WB_ENTRY(void, WB_AsyncHandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle))
2216   class TraceSelfClosure : public AsyncHandshakeClosure {
2217     JavaThread* _self;
2218     void do_thread(Thread* th) {
2219       assert(th->is_Java_thread(), "sanity");
2220       // AsynchHandshake handshakes are only executed by target.
2221       assert(_self == th, "Must be");
2222       assert(Thread::current() == th, "Must be");
2223       JavaThread* jt = JavaThread::cast(th);
2224       ResourceMark rm;
2225       jt->print_on(tty);
2226       jt->print_stack_on(tty);
2227       tty->cr();
2228     }
2229 
2230   public:
2231     TraceSelfClosure(JavaThread* self_target) : AsyncHandshakeClosure("WB_TraceSelf"), _self(self_target) {}
2232   };
2233   if (thread_handle != nullptr) {
2234     ThreadsListHandle tlh;
2235     JavaThread* target = nullptr;
2236     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, nullptr);
2237     if (is_alive) {
2238       TraceSelfClosure* tsc = new TraceSelfClosure(target);
2239       Handshake::execute(tsc, target);
2240     }
2241   }
2242 WB_END
2243 
2244 static volatile int _emulated_lock = 0;
2245 
2246 WB_ENTRY(void, WB_LockAndBlock(JNIEnv* env, jobject wb, jboolean suspender))
2247   JavaThread* self = JavaThread::current();
2248 
2249   {
2250     // Before trying to acquire the lock transition into a safepoint safe state.
2251     // Otherwise if either suspender or suspendee blocks for a safepoint
2252     // in ~ThreadBlockInVM the other one could loop forever trying to acquire
2253     // the lock without allowing the safepoint to progress.
2254     ThreadBlockInVM tbivm(self);
2255 
2256     // We will deadlock here if we are 'suspender' and 'suspendee'
2257     // suspended in ~ThreadBlockInVM. This verifies we only suspend
2258     // at the right place.
2259     while (Atomic::cmpxchg(&_emulated_lock, 0, 1) != 0) {}
2260     assert(_emulated_lock == 1, "Must be locked");
2261 
2262     // Sleep much longer in suspendee to force situation where
2263     // 'suspender' is waiting above to acquire lock.
2264     os::naked_short_sleep(suspender ? 1 : 10);
2265   }
2266   Atomic::store(&_emulated_lock, 0);
2267 WB_END
2268 
2269 // Some convenience methods to deal with objects from java
2270 int WhiteBox::offset_for_field(const char* field_name, oop object,
2271     Symbol* signature_symbol) {
2272   assert(field_name != nullptr && strlen(field_name) > 0, "Field name not valid");
2273 
2274   //Get the class of our object
2275   Klass* arg_klass = object->klass();
2276   //Turn it into an instance-klass
2277   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
2278 
2279   //Create symbols to look for in the class
2280   TempNewSymbol name_symbol = SymbolTable::new_symbol(field_name);
2281 
2282   //To be filled in with an offset of the field we're looking for
2283   fieldDescriptor fd;
2284 
2285   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
2286   if (res == nullptr) {
2287     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
2288         name_symbol->as_C_string());
2289     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
2290   }
2291 
2292   //fetch the field at the offset we've found
2293   int dest_offset = fd.offset();
2294 
2295   return dest_offset;
2296 }
2297 
2298 
2299 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
2300   int offset = offset_for_field(field_name, object,
2301       vmSymbols::string_signature());
2302   oop string = object->obj_field(offset);
2303   if (string == nullptr) {
2304     return nullptr;
2305   }
2306   const char* ret = java_lang_String::as_utf8_string(string);
2307   return ret;
2308 }
2309 
2310 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
2311   int offset =
2312       offset_for_field(field_name, object, vmSymbols::bool_signature());
2313   bool ret = (object->bool_field(offset) == JNI_TRUE);
2314   return ret;
2315 }
2316 
2317 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
2318   ResourceMark rm;
2319   Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(wbclass));
2320   const char* klass_name = klass->external_name();
2321 
2322   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
2323 
2324   //  one by one registration natives for exception catching
2325   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
2326   CHECK_JNI_EXCEPTION(env);
2327   for (int i = 0, n = method_count; i < n; ++i) {
2328     // Skip dummy entries
2329     if (method_array[i].fnPtr == nullptr) continue;
2330     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
2331       jthrowable throwable_obj = env->ExceptionOccurred();
2332       if (throwable_obj != nullptr) {
2333         env->ExceptionClear();
2334         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
2335           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
2336           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
2337           tty->print_cr("Warning: 'NoSuchMethodError' on register of %s::%s%s",
2338               klass_name, method_array[i].name, method_array[i].signature);
2339         }
2340       } else {
2341         // Registration failed unexpectedly.
2342         tty->print_cr("Warning: unexpected error on register of %s::%s%s. All methods will be unregistered",
2343             klass_name, method_array[i].name, method_array[i].signature);
2344         env->UnregisterNatives(wbclass);
2345         break;
2346       }
2347     }
2348   }
2349 }
2350 
2351 WB_ENTRY(jint, WB_AddCompilerDirective(JNIEnv* env, jobject o, jstring compDirect))
2352   // can't be in VM when we call JNI
2353   ThreadToNativeFromVM ttnfv(thread);
2354   const char* dir = env->GetStringUTFChars(compDirect, nullptr);
2355   CHECK_JNI_EXCEPTION_(env, 0);
2356   int ret;
2357   {
2358     ThreadInVMfromNative ttvfn(thread); // back to VM
2359     ret = DirectivesParser::parse_string(dir, tty);
2360   }
2361   env->ReleaseStringUTFChars(compDirect, dir);
2362   // -1 for error parsing directive. Return 0 as number of directives added.
2363   if (ret == -1) {
2364     ret = 0;
2365   }
2366   return (jint) ret;
2367 WB_END
2368 
2369 WB_ENTRY(void, WB_RemoveCompilerDirective(JNIEnv* env, jobject o, jint count))
2370   DirectivesStack::pop(count);
2371 WB_END
2372 
2373 // Checks that the library libfile has the noexecstack bit set.
2374 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
2375   jboolean ret = false;
2376 #ifdef LINUX
2377   // Can't be in VM when we call JNI.
2378   ThreadToNativeFromVM ttnfv(thread);
2379   const char* lf = env->GetStringUTFChars(libfile, nullptr);
2380   CHECK_JNI_EXCEPTION_(env, 0);
2381   ret = (jboolean) ElfFile::specifies_noexecstack(lf);
2382   env->ReleaseStringUTFChars(libfile, lf);
2383 #endif
2384   return ret;
2385 WB_END
2386 
2387 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
2388   LINUX_ONLY(return OSContainer::is_containerized();)
2389   return false;
2390 WB_END
2391 
2392 // Physical memory of the host machine (including containers)
2393 WB_ENTRY(jlong, WB_HostPhysicalMemory(JNIEnv* env, jobject o))
2394   LINUX_ONLY(return os::Linux::physical_memory();)
2395   return os::physical_memory();
2396 WB_END
2397 
2398 // Physical swap of the host machine (including containers), Linux only.
2399 WB_ENTRY(jlong, WB_HostPhysicalSwap(JNIEnv* env, jobject o))
2400   LINUX_ONLY(return (jlong)os::Linux::host_swap();)
2401   return -1; // Not used/implemented on other platforms
2402 WB_END
2403 
2404 WB_ENTRY(jint, WB_ValidateCgroup(JNIEnv* env,
2405                                     jobject o,
2406                                     jstring proc_cgroups,
2407                                     jstring proc_self_cgroup,
2408                                     jstring proc_self_mountinfo))
2409   jint ret = 0;
2410 #ifdef LINUX
2411   ThreadToNativeFromVM ttnfv(thread);
2412   const char* p_cgroups = env->GetStringUTFChars(proc_cgroups, nullptr);
2413   CHECK_JNI_EXCEPTION_(env, 0);
2414   const char* p_s_cgroup = env->GetStringUTFChars(proc_self_cgroup, nullptr);
2415   CHECK_JNI_EXCEPTION_(env, 0);
2416   const char* p_s_mountinfo = env->GetStringUTFChars(proc_self_mountinfo, nullptr);
2417   CHECK_JNI_EXCEPTION_(env, 0);
2418   u1 cg_type_flags = 0;
2419   // This sets cg_type_flags
2420   WhiteBox::validate_cgroup(p_cgroups, p_s_cgroup, p_s_mountinfo, &cg_type_flags);
2421   ret = (jint)cg_type_flags;
2422   env->ReleaseStringUTFChars(proc_cgroups, p_cgroups);
2423   env->ReleaseStringUTFChars(proc_self_cgroup, p_s_cgroup);
2424   env->ReleaseStringUTFChars(proc_self_mountinfo, p_s_mountinfo);
2425 #endif
2426   return ret;
2427 WB_END
2428 
2429 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
2430   os::print_os_info(tty);
2431 WB_END
2432 
2433 // Elf decoder
2434 WB_ENTRY(void, WB_DisableElfSectionCache(JNIEnv* env))
2435 #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX)
2436   ElfFile::_do_not_cache_elf_section = true;
2437 #endif
2438 WB_END
2439 
2440 WB_ENTRY(jlong, WB_ResolvedMethodItemsCount(JNIEnv* env, jobject o))
2441   return (jlong) ResolvedMethodTable::items_count();
2442 WB_END
2443 
2444 WB_ENTRY(jint, WB_ProtectionDomainRemovedCount(JNIEnv* env, jobject o))
2445   return (jint) ProtectionDomainCacheTable::removed_entries_count();
2446 WB_END
2447 
2448 WB_ENTRY(jint, WB_GetKlassMetadataSize(JNIEnv* env, jobject wb, jclass mirror))
2449   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2450   // Return size in bytes.
2451   return k->size() * wordSize;
2452 WB_END
2453 
2454 // See test/hotspot/jtreg/runtime/Thread/ThreadObjAccessAtExit.java.
2455 // It explains how the thread's priority field is used for test state coordination.
2456 //
2457 WB_ENTRY(void, WB_CheckThreadObjOfTerminatingThread(JNIEnv* env, jobject wb, jobject target_handle))
2458   oop target_oop = JNIHandles::resolve_non_null(target_handle);
2459   jlong tid = java_lang_Thread::thread_id(target_oop);
2460   JavaThread* target = java_lang_Thread::thread(target_oop);
2461 
2462   // Grab a ThreadsListHandle to protect the target thread whilst terminating
2463   ThreadsListHandle tlh;
2464 
2465   // Look up the target thread by tid to ensure it is present
2466   JavaThread* t = tlh.list()->find_JavaThread_from_java_tid(tid);
2467   if (t == nullptr) {
2468     THROW_MSG(vmSymbols::java_lang_RuntimeException(), "Target thread not found in ThreadsList!");
2469   }
2470 
2471   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: target thread is protected");
2472   // Allow target to terminate by boosting priority
2473   java_lang_Thread::set_priority(t->threadObj(), ThreadPriority(NormPriority + 1));
2474 
2475   // Now wait for the target to terminate
2476   while (!target->is_terminated()) {
2477     ThreadBlockInVM tbivm(thread);  // just in case target is involved in a safepoint
2478     os::naked_short_sleep(0);
2479   }
2480 
2481   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: target thread is terminated");
2482 
2483   // Now release the GC inducing thread - we have to re-resolve the external oop that
2484   // was passed in as GC may have occurred and we don't know if we can trust t->threadObj() now.
2485   oop original = JNIHandles::resolve_non_null(target_handle);
2486   java_lang_Thread::set_priority(original, ThreadPriority(NormPriority + 2));
2487 
2488   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: GC has been initiated - checking threadObj:");
2489 
2490   // The Java code should be creating garbage and triggering GC, which would potentially move
2491   // the threadObj oop. If the exiting thread is properly protected then its threadObj should
2492   // remain valid and equal to our initial target_handle. Loop a few times to give GC a chance to
2493   // kick in.
2494   for (int i = 0; i < 5; i++) {
2495     oop original = JNIHandles::resolve_non_null(target_handle);
2496     oop current = t->threadObj();
2497     if (original != current) {
2498       tty->print_cr("WB_CheckThreadObjOfTerminatingThread: failed comparison on iteration %d", i);
2499       THROW_MSG(vmSymbols::java_lang_RuntimeException(), "Target thread oop has changed!");
2500     } else {
2501       tty->print_cr("WB_CheckThreadObjOfTerminatingThread: successful comparison on iteration %d", i);
2502       ThreadBlockInVM tbivm(thread);
2503       os::naked_short_sleep(50);
2504     }
2505   }
2506 WB_END
2507 
2508 WB_ENTRY(void, WB_VerifyFrames(JNIEnv* env, jobject wb, jboolean log, jboolean update_map))
2509   ResourceMark rm; // for verify
2510   stringStream st;
2511   for (StackFrameStream fst(JavaThread::current(), update_map, true); !fst.is_done(); fst.next()) {
2512     frame* current_frame = fst.current();
2513     if (log) {
2514       current_frame->print_value_on(&st, nullptr);
2515     }
2516     current_frame->verify(fst.register_map());
2517   }
2518   if (log) {
2519     tty->print_cr("[WhiteBox::VerifyFrames] Walking Frames");
2520     tty->print_raw(st.freeze());
2521     tty->print_cr("[WhiteBox::VerifyFrames] Done");
2522   }
2523 WB_END
2524 
2525 WB_ENTRY(jboolean, WB_IsJVMTIIncluded(JNIEnv* env, jobject wb))
2526 #if INCLUDE_JVMTI
2527   return JNI_TRUE;
2528 #else
2529   return JNI_FALSE;
2530 #endif
2531 WB_END
2532 
2533 WB_ENTRY(void, WB_WaitUnsafe(JNIEnv* env, jobject wb, jint time))
2534     os::naked_short_sleep(time);
2535 WB_END
2536 
2537 WB_ENTRY(jstring, WB_GetLibcName(JNIEnv* env, jobject o))
2538   ThreadToNativeFromVM ttn(thread);
2539   jstring info_string = env->NewStringUTF(XSTR(LIBC));
2540   CHECK_JNI_EXCEPTION_(env, nullptr);
2541   return info_string;
2542 WB_END
2543 
2544 WB_ENTRY(void, WB_LockCritical(JNIEnv* env, jobject wb))
2545   GCLocker::lock_critical(thread);
2546 WB_END
2547 
2548 WB_ENTRY(void, WB_UnlockCritical(JNIEnv* env, jobject wb))
2549   GCLocker::unlock_critical(thread);
2550 WB_END
2551 
2552 WB_ENTRY(jboolean, WB_SetVirtualThreadsNotifyJvmtiMode(JNIEnv* env, jobject wb, jboolean enable))
2553   if (!Continuations::enabled()) {
2554     tty->print_cr("WB error: must be Continuations::enabled()!");
2555     return JNI_FALSE;
2556   }
2557   jboolean result = false;
2558 #if INCLUDE_JVMTI
2559   if (enable) {
2560     result = JvmtiEnvBase::enable_virtual_threads_notify_jvmti();
2561   } else {
2562     result = JvmtiEnvBase::disable_virtual_threads_notify_jvmti();
2563   }
2564 #endif
2565   return result;
2566 WB_END
2567 
2568 WB_ENTRY(void, WB_PreTouchMemory(JNIEnv* env, jobject wb, jlong addr, jlong size))
2569   void* const from = (void*)addr;
2570   void* const to = (void*)(addr + size);
2571   if (from > to) {
2572     os::pretouch_memory(from, to, os::vm_page_size());
2573   }
2574 WB_END
2575 
2576 WB_ENTRY(void, WB_CleanMetaspaces(JNIEnv* env, jobject target))
2577   ClassLoaderDataGraph::safepoint_and_clean_metaspaces();
2578 WB_END
2579 
2580 #define CC (char*)
2581 
2582 static JNINativeMethod methods[] = {
2583   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
2584   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
2585   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
2586   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
2587   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
2588   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
2589   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
2590   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
2591   {CC"getHeapAlignment",                 CC"()J",                   (void*)&WB_GetHeapAlignment},
2592   {CC"countAliveClasses0",               CC"(Ljava/lang/String;)I", (void*)&WB_CountAliveClasses },
2593   {CC"getSymbolRefcount",                CC"(Ljava/lang/String;)I", (void*)&WB_GetSymbolRefcount },
2594   {CC"parseCommandLine0",
2595       CC"(Ljava/lang/String;C[Ljdk/test/whitebox/parser/DiagnosticCommand;)[Ljava/lang/Object;",
2596       (void*) &WB_ParseCommandLine
2597   },
2598   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
2599                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
2600   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
2601                                                       (void*)&WB_AddToSystemClassLoaderSearch},
2602   {CC"getCompressedOopsMaxHeapSize", CC"()J",
2603       (void*)&WB_GetCompressedOopsMaxHeapSize},
2604   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
2605   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
2606   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
2607 #if INCLUDE_CDS
2608   {CC"getCDSOffsetForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetCDSOffsetForName},
2609   {CC"getCDSConstantForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetCDSConstantForName},
2610 #endif
2611 #if INCLUDE_G1GC
2612   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
2613   {CC"g1CompletedConcurrentMarkCycles", CC"()I",      (void*)&WB_G1CompletedConcurrentMarkCycles},
2614   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
2615   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
2616   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
2617   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
2618   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
2619   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
2620   {CC"g1HasRegionsToUncommit",  CC"()Z",              (void*)&WB_G1HasRegionsToUncommit},
2621   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
2622                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
2623   {CC"g1ActiveMemoryNodeCount", CC"()I",              (void*)&WB_G1ActiveMemoryNodeCount },
2624   {CC"g1MemoryNodeIds",    CC"()[I",                  (void*)&WB_G1MemoryNodeIds },
2625   {CC"g1GetMixedGCInfo",   CC"(I)[J",                 (void*)&WB_G1GetMixedGCInfo },
2626 #endif // INCLUDE_G1GC
2627 #if INCLUDE_PARALLELGC
2628   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
2629   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
2630 #endif
2631   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
2632   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
2633   {CC"NMTMallocWithPseudoStackAndType", CC"(JII)J",   (void*)&WB_NMTMallocWithPseudoStackAndType},
2634   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
2635   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
2636   {CC"NMTAttemptReserveMemoryAt",    CC"(JJ)J",       (void*)&WB_NMTAttemptReserveMemoryAt },
2637   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
2638   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
2639   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
2640   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
2641   {CC"NMTNewArena",         CC"(J)J",                 (void*)&WB_NMTNewArena        },
2642   {CC"NMTFreeArena",        CC"(J)V",                 (void*)&WB_NMTFreeArena       },
2643   {CC"NMTArenaMalloc",      CC"(JJ)V",                (void*)&WB_NMTArenaMalloc     },
2644   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
2645   {CC"isFrameDeoptimized", CC"(I)Z",                  (void*)&WB_IsFrameDeoptimized},
2646   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
2647   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
2648                                                       (void*)&WB_DeoptimizeMethod  },
2649   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
2650                                                       (void*)&WB_IsMethodCompiled  },
2651   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
2652                                                       (void*)&WB_IsMethodCompilable},
2653   {CC"isMethodQueuedForCompilation0",
2654       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
2655   {CC"isIntrinsicAvailable0",
2656       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
2657                                                       (void*)&WB_IsIntrinsicAvailable},
2658   {CC"makeMethodNotCompilable0",
2659       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
2660   {CC"testSetDontInlineMethod0",
2661       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
2662   {CC"getMethodCompilationLevel0",
2663       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
2664   {CC"getMethodDecompileCount0",
2665       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodDecompileCount},
2666   {CC"getMethodTrapCount0",
2667       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2668                                                       (void*)&WB_GetMethodTrapCount},
2669   {CC"getDeoptCount0",
2670       CC"(Ljava/lang/String;Ljava/lang/String;)I",    (void*)&WB_GetDeoptCount},
2671   {CC"getMethodEntryBci0",
2672       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
2673   {CC"getCompileQueueSize",
2674       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
2675   {CC"testSetForceInlineMethod0",
2676       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
2677   {CC"enqueueMethodForCompilation0",
2678       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
2679   {CC"enqueueInitializerForCompilation0",
2680       CC"(Ljava/lang/Class;I)Z",                      (void*)&WB_EnqueueInitializerForCompilation},
2681   {CC"markMethodProfiled",
2682       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_MarkMethodProfiled},
2683   {CC"clearMethodState0",
2684       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
2685   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
2686   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
2687   {CC"matchesMethod",
2688       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2689                                                       (void*)&WB_MatchesMethod},
2690   {CC"matchesInline",
2691       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2692                                                       (void*)&WB_MatchesInline},
2693   {CC"shouldPrintAssembly",
2694         CC"(Ljava/lang/reflect/Executable;I)Z",
2695                                                         (void*)&WB_ShouldPrintAssembly},
2696 
2697   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
2698   {CC"isDefaultVMFlag",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsDefaultVMFlag},
2699   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
2700   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
2701   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
2702   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
2703   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
2704   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
2705   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
2706   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
2707   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
2708   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
2709                                                       (void*)&WB_SetStringVMFlag},
2710   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
2711                                                       (void*)&WB_GetBooleanVMFlag},
2712   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
2713                                                       (void*)&WB_GetIntVMFlag},
2714   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2715                                                       (void*)&WB_GetUintVMFlag},
2716   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2717                                                       (void*)&WB_GetIntxVMFlag},
2718   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2719                                                       (void*)&WB_GetUintxVMFlag},
2720   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
2721                                                       (void*)&WB_GetUint64VMFlag},
2722   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2723                                                       (void*)&WB_GetSizeTVMFlag},
2724   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
2725                                                       (void*)&WB_GetDoubleVMFlag},
2726   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
2727                                                       (void*)&WB_GetStringVMFlag},
2728   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
2729   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
2730   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
2731   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
2732   {CC"allocateMetaspace",
2733      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
2734   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
2735   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
2736   {CC"metaspaceSharedRegionAlignment", CC"()J",       (void*)&WB_MetaspaceSharedRegionAlignment },
2737   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
2738   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
2739                                                       (void*)&WB_GetNMethod         },
2740   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
2741   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
2742   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
2743   {CC"getCompilationActivityMode",
2744                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
2745   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
2746                                                       (void*)&WB_GetMethodData      },
2747   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
2748   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
2749   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
2750   {CC"DefineModule",       CC"(Ljava/lang/Object;ZLjava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V",
2751                                                       (void*)&WB_DefineModule },
2752   {CC"AddModuleExports",   CC"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
2753                                                       (void*)&WB_AddModuleExports },
2754   {CC"AddReadsModule",     CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
2755                                                       (void*)&WB_AddReadsModule },
2756   {CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2757                                                       (void*)&WB_AddModuleExportsToAllUnnamed },
2758   {CC"AddModuleExportsToAll", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2759                                                       (void*)&WB_AddModuleExportsToAll },
2760   {CC"deflateIdleMonitors", CC"()Z",                  (void*)&WB_DeflateIdleMonitors },
2761   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
2762   {CC"getLockStackCapacity", CC"()I",                 (void*)&WB_getLockStackCapacity },
2763   {CC"supportsRecursiveLightweightLocking", CC"()Z",  (void*)&WB_supportsRecursiveLightweightLocking },
2764   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
2765   {CC"forceClassLoaderStatsSafepoint", CC"()V",       (void*)&WB_ForceClassLoaderStatsSafepoint },
2766   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
2767   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
2768   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
2769   {CC"getResolvedReferences0", CC"(Ljava/lang/Class;)[Ljava/lang/Object;", (void*)&WB_GetResolvedReferences},
2770   {CC"remapInstructionOperandFromCPCache0",
2771       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
2772   {CC"encodeConstantPoolIndyIndex0",
2773       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
2774   {CC"getIndyInfoLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_getIndyInfoLength},
2775   {CC"getIndyCPIndex0",    CC"(Ljava/lang/Class;I)I", (void*)&WB_getIndyCPIndex},
2776   {CC"getMethodBooleanOption",
2777       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
2778                                                       (void*)&WB_GetMethodBooleaneOption},
2779   {CC"getMethodIntxOption",
2780       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2781                                                       (void*)&WB_GetMethodIntxOption},
2782   {CC"getMethodUintxOption",
2783       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2784                                                       (void*)&WB_GetMethodUintxOption},
2785   {CC"getMethodDoubleOption",
2786       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
2787                                                       (void*)&WB_GetMethodDoubleOption},
2788   {CC"getMethodStringOption",
2789       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
2790                                                       (void*)&WB_GetMethodStringOption},
2791   {CC"getDefaultArchivePath",             CC"()Ljava/lang/String;",
2792                                                       (void*)&WB_GetDefaultArchivePath},
2793   {CC"getCDSGenericHeaderMinVersion",     CC"()I",    (void*)&WB_GetCDSGenericHeaderMinVersion},
2794   {CC"getCurrentCDSVersion",              CC"()I",    (void*)&WB_GetCDSCurrentVersion},
2795   {CC"isSharingEnabled",   CC"()Z",                   (void*)&WB_IsSharingEnabled},
2796   {CC"isSharedInternedString", CC"(Ljava/lang/String;)Z", (void*)&WB_IsSharedInternedString },
2797   {CC"isSharedClass",      CC"(Ljava/lang/Class;)Z",  (void*)&WB_IsSharedClass },
2798   {CC"areSharedStringsMapped",            CC"()Z",    (void*)&WB_AreSharedStringsMapped },
2799   {CC"linkClass",          CC"(Ljava/lang/Class;)V",  (void*)&WB_LinkClass},
2800   {CC"areOpenArchiveHeapObjectsMapped",   CC"()Z",    (void*)&WB_AreOpenArchiveHeapObjectsMapped},
2801   {CC"isCDSIncluded",                     CC"()Z",    (void*)&WB_IsCDSIncluded },
2802   {CC"isJFRIncluded",                     CC"()Z",    (void*)&WB_IsJFRIncluded },
2803   {CC"isDTraceIncluded",                  CC"()Z",    (void*)&WB_IsDTraceIncluded },
2804   {CC"isC2OrJVMCIIncluded",               CC"()Z",    (void*)&WB_isC2OrJVMCIIncluded },
2805   {CC"isJVMCISupportedByGC",              CC"()Z",    (void*)&WB_IsJVMCISupportedByGC},
2806   {CC"canWriteJavaHeapArchive",           CC"()Z",    (void*)&WB_CanWriteJavaHeapArchive },
2807   {CC"cdsMemoryMappingFailed",            CC"()Z",    (void*)&WB_CDSMemoryMappingFailed },
2808 
2809   {CC"clearInlineCaches0",  CC"(Z)V",                 (void*)&WB_ClearInlineCaches },
2810   {CC"handshakeReadMonitors", CC"(Ljava/lang/Thread;)Z", (void*)&WB_HandshakeReadMonitors },
2811   {CC"handshakeWalkStack", CC"(Ljava/lang/Thread;Z)I", (void*)&WB_HandshakeWalkStack },
2812   {CC"asyncHandshakeWalkStack", CC"(Ljava/lang/Thread;)V", (void*)&WB_AsyncHandshakeWalkStack },
2813   {CC"lockAndBlock", CC"(Z)V",                        (void*)&WB_LockAndBlock},
2814   {CC"checkThreadObjOfTerminatingThread", CC"(Ljava/lang/Thread;)V", (void*)&WB_CheckThreadObjOfTerminatingThread },
2815   {CC"verifyFrames",                CC"(ZZ)V",            (void*)&WB_VerifyFrames },
2816   {CC"addCompilerDirective",    CC"(Ljava/lang/String;)I",
2817                                                       (void*)&WB_AddCompilerDirective },
2818   {CC"removeCompilerDirective",   CC"(I)V",           (void*)&WB_RemoveCompilerDirective },
2819   {CC"isGCSupported",             CC"(I)Z",           (void*)&WB_IsGCSupported},
2820   {CC"isGCSupportedByJVMCICompiler", CC"(I)Z",        (void*)&WB_IsGCSupportedByJVMCICompiler},
2821   {CC"isGCSelected",              CC"(I)Z",           (void*)&WB_IsGCSelected},
2822   {CC"isGCSelectedErgonomically", CC"()Z",            (void*)&WB_IsGCSelectedErgonomically},
2823   {CC"supportsConcurrentGCBreakpoints", CC"()Z",      (void*)&WB_SupportsConcurrentGCBreakpoints},
2824   {CC"concurrentGCAcquireControl0", CC"()V",          (void*)&WB_ConcurrentGCAcquireControl},
2825   {CC"concurrentGCReleaseControl0", CC"()V",          (void*)&WB_ConcurrentGCReleaseControl},
2826   {CC"concurrentGCRunToIdle0",    CC"()V",            (void*)&WB_ConcurrentGCRunToIdle},
2827   {CC"concurrentGCRunTo0",        CC"(Ljava/lang/String;)Z",
2828                                                       (void*)&WB_ConcurrentGCRunTo},
2829   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
2830                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
2831   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
2832   {CC"validateCgroup",
2833       CC"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
2834                                                       (void*)&WB_ValidateCgroup },
2835   {CC"hostPhysicalMemory",        CC"()J",            (void*)&WB_HostPhysicalMemory },
2836   {CC"hostPhysicalSwap",          CC"()J",            (void*)&WB_HostPhysicalSwap },
2837   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
2838   {CC"disableElfSectionCache",    CC"()V",            (void*)&WB_DisableElfSectionCache },
2839   {CC"resolvedMethodItemsCount",  CC"()J",            (void*)&WB_ResolvedMethodItemsCount },
2840   {CC"protectionDomainRemovedCount",   CC"()I",       (void*)&WB_ProtectionDomainRemovedCount },
2841   {CC"getKlassMetadataSize", CC"(Ljava/lang/Class;)I",(void*)&WB_GetKlassMetadataSize},
2842 
2843   {CC"createMetaspaceTestContext", CC"(JJ)J",         (void*)&WB_CreateMetaspaceTestContext},
2844   {CC"destroyMetaspaceTestContext", CC"(J)V",         (void*)&WB_DestroyMetaspaceTestContext},
2845   {CC"purgeMetaspaceTestContext", CC"(J)V",           (void*)&WB_PurgeMetaspaceTestContext},
2846   {CC"printMetaspaceTestContext", CC"(J)V",           (void*)&WB_PrintMetaspaceTestContext},
2847   {CC"getTotalCommittedWordsInMetaspaceTestContext", CC"(J)J",(void*)&WB_GetTotalCommittedWordsInMetaspaceTestContext},
2848   {CC"getTotalUsedWordsInMetaspaceTestContext", CC"(J)J", (void*)&WB_GetTotalUsedWordsInMetaspaceTestContext},
2849   {CC"createArenaInTestContext", CC"(JZ)J",           (void*)&WB_CreateArenaInTestContext},
2850   {CC"destroyMetaspaceTestArena", CC"(J)V",           (void*)&WB_DestroyMetaspaceTestArena},
2851   {CC"allocateFromMetaspaceTestArena", CC"(JJ)J",     (void*)&WB_AllocateFromMetaspaceTestArena},
2852   {CC"deallocateToMetaspaceTestArena", CC"(JJJ)V",    (void*)&WB_DeallocateToMetaspaceTestArena},
2853   {CC"maxMetaspaceAllocationSize", CC"()J",           (void*)&WB_GetMaxMetaspaceAllocationSize},
2854 
2855   {CC"isJVMTIIncluded", CC"()Z",                      (void*)&WB_IsJVMTIIncluded},
2856   {CC"waitUnsafe", CC"(I)V",                          (void*)&WB_WaitUnsafe},
2857   {CC"getLibcName",     CC"()Ljava/lang/String;",     (void*)&WB_GetLibcName},
2858 
2859   {CC"lockCritical",    CC"()V",                      (void*)&WB_LockCritical},
2860   {CC"unlockCritical",  CC"()V",                      (void*)&WB_UnlockCritical},
2861   {CC"setVirtualThreadsNotifyJvmtiMode", CC"(Z)Z",    (void*)&WB_SetVirtualThreadsNotifyJvmtiMode},
2862   {CC"preTouchMemory",  CC"(JJ)V",                    (void*)&WB_PreTouchMemory},
2863   {CC"cleanMetaspaces", CC"()V",                      (void*)&WB_CleanMetaspaces},
2864 };
2865 
2866 
2867 #undef CC
2868 
2869 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
2870   {
2871     if (WhiteBoxAPI) {
2872       // Make sure that wbclass is loaded by the null classloader
2873       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(wbclass)));
2874       Handle loader(THREAD, ik->class_loader());
2875       if (loader.is_null()) {
2876         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
2877         WhiteBox::set_used();
2878       }
2879     }
2880   }
2881 JVM_END