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