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