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